plugins.mdx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. ---
  2. title: Plugin
  3. description: Scrivi plugin per estendere OpenCode.
  4. ---
  5. I plugin ti permettono di estendere OpenCode agganciandoti a vari eventi e personalizzando il comportamento. Puoi creare plugin per aggiungere nuove funzionalità, integrare servizi esterni o modificare il comportamento predefinito di OpenCode.
  6. Per esempi, dai un'occhiata ai [plugin](/docs/ecosystem#plugins) creati dalla community.
  7. ---
  8. ## Usare un plugin
  9. Ci sono due modi per caricare i plugin.
  10. ---
  11. ### Da file locali
  12. Metti file JavaScript o TypeScript nella directory dei plugin.
  13. - `.opencode/plugins/` - plugin a livello progetto
  14. - `~/.config/opencode/plugins/` - plugin globali
  15. I file in queste directory vengono caricati automaticamente all'avvio.
  16. ---
  17. ### Da npm
  18. Specifica i pacchetti npm nel tuo file di configurazione.
  19. ```json title="opencode.json"
  20. {
  21. "$schema": "https://opencode.ai/config.json",
  22. "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]
  23. }
  24. ```
  25. Sono supportati sia pacchetti npm normali sia scoped.
  26. Sfoglia i plugin disponibili nell'[ecosistema](/docs/ecosystem#plugins).
  27. ---
  28. ### Come vengono installati i plugin
  29. I **plugin npm** vengono installati automaticamente usando Bun all'avvio. I pacchetti e le loro dipendenze vengono cache-ati in `~/.cache/opencode/node_modules/`.
  30. I **plugin locali** vengono caricati direttamente dalla directory dei plugin. Per usare pacchetti esterni, devi creare un `package.json` nella directory di configurazione (vedi [Dipendenze](#dependencies)) oppure pubblicare il plugin su npm e [aggiungerlo alla configurazione](/docs/config#plugins).
  31. ---
  32. ### Ordine di caricamento
  33. I plugin vengono caricati da tutte le sorgenti e tutti gli hook vengono eseguiti in sequenza. L'ordine di caricamento è:
  34. 1. Config globale (`~/.config/opencode/opencode.json`)
  35. 2. Config di progetto (`opencode.json`)
  36. 3. Directory plugin globale (`~/.config/opencode/plugins/`)
  37. 4. Directory plugin di progetto (`.opencode/plugins/`)
  38. I pacchetti npm duplicati con lo stesso nome e versione vengono caricati una sola volta. Tuttavia, un plugin locale e un plugin npm con nomi simili vengono entrambi caricati separatamente.
  39. ---
  40. ## Creare un plugin
  41. Un plugin è un **modulo JavaScript/TypeScript** che esporta una o più funzioni di plugin. Ogni funzione riceve un oggetto di contesto e restituisce un oggetto di hook.
  42. ---
  43. ### Dipendenze
  44. I plugin locali e gli strumenti personalizzati possono usare pacchetti npm esterni. Aggiungi un `package.json` alla tua directory di configurazione con le dipendenze di cui hai bisogno.
  45. ```json title=".opencode/package.json"
  46. {
  47. "dependencies": {
  48. "shescape": "^2.1.0"
  49. }
  50. }
  51. ```
  52. OpenCode esegue `bun install` all'avvio per installarle. I tuoi plugin e strumenti potranno poi importarle.
  53. ```ts title=".opencode/plugins/my-plugin.ts"
  54. import { escape } from "shescape"
  55. export const MyPlugin = async (ctx) => {
  56. return {
  57. "tool.execute.before": async (input, output) => {
  58. if (input.tool === "bash") {
  59. output.args.command = escape(output.args.command)
  60. }
  61. },
  62. }
  63. }
  64. ```
  65. ---
  66. ### Struttura base
  67. ```js title=".opencode/plugins/example.js"
  68. export const MyPlugin = async ({ project, client, $, directory, worktree }) => {
  69. console.log("Plugin initialized!")
  70. return {
  71. // Hook implementations go here
  72. }
  73. }
  74. ```
  75. La funzione del plugin riceve:
  76. - `project`: informazioni sul progetto corrente.
  77. - `directory`: la working directory corrente.
  78. - `worktree`: il path del worktree git.
  79. - `client`: un client SDK di opencode per interagire con l'AI.
  80. - `$`: la [shell API](https://bun.com/docs/runtime/shell) di Bun per eseguire comandi.
  81. ---
  82. ### Supporto TypeScript
  83. Per i plugin TypeScript, puoi importare i tipi dal pacchetto plugin:
  84. ```ts title="my-plugin.ts" {1}
  85. import type { Plugin } from "@opencode-ai/plugin"
  86. export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => {
  87. return {
  88. // Type-safe hook implementations
  89. }
  90. }
  91. ```
  92. ---
  93. ### Eventi
  94. I plugin possono sottoscrivere eventi come mostrato sotto nella sezione Esempi. Ecco l'elenco dei diversi eventi disponibili.
  95. #### Eventi dei comandi
  96. - `command.executed`
  97. #### Eventi dei file
  98. - `file.edited`
  99. - `file.watcher.updated`
  100. #### Eventi di installazione
  101. - `installation.updated`
  102. #### Eventi LSP
  103. - `lsp.client.diagnostics`
  104. - `lsp.updated`
  105. #### Eventi dei messaggi
  106. - `message.part.removed`
  107. - `message.part.updated`
  108. - `message.removed`
  109. - `message.updated`
  110. #### Eventi dei permessi
  111. - `permission.asked`
  112. - `permission.replied`
  113. #### Eventi del server
  114. - `server.connected`
  115. #### Eventi delle sessioni
  116. - `session.created`
  117. - `session.compacted`
  118. - `session.deleted`
  119. - `session.diff`
  120. - `session.error`
  121. - `session.idle`
  122. - `session.status`
  123. - `session.updated`
  124. #### Eventi della todo
  125. - `todo.updated`
  126. #### Eventi della shell
  127. - `shell.env`
  128. #### Eventi degli strumenti
  129. - `tool.execute.after`
  130. - `tool.execute.before`
  131. #### Eventi TUI
  132. - `tui.prompt.append`
  133. - `tui.command.execute`
  134. - `tui.toast.show`
  135. ---
  136. ## Esempi
  137. Ecco alcuni esempi di plugin che puoi usare per estendere opencode.
  138. ---
  139. ### Invia notifiche
  140. Invia notifiche quando avvengono certi eventi:
  141. ```js title=".opencode/plugins/notification.js"
  142. export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => {
  143. return {
  144. event: async ({ event }) => {
  145. // Send notification on session completion
  146. if (event.type === "session.idle") {
  147. await $`osascript -e 'display notification "Session completed!" with title "opencode"'`
  148. }
  149. },
  150. }
  151. }
  152. ```
  153. Stiamo usando `osascript` per eseguire AppleScript su macOS. Qui lo usiamo per inviare notifiche.
  154. :::note
  155. Se usi l'app desktop di OpenCode, può inviare automaticamente notifiche di sistema quando una risposta è pronta o quando una sessione va in errore.
  156. :::
  157. ---
  158. ### Protezione .env
  159. Impedisci a opencode di leggere i file `.env`:
  160. ```javascript title=".opencode/plugins/env-protection.js"
  161. export const EnvProtection = async ({ project, client, $, directory, worktree }) => {
  162. return {
  163. "tool.execute.before": async (input, output) => {
  164. if (input.tool === "read" && output.args.filePath.includes(".env")) {
  165. throw new Error("Do not read .env files")
  166. }
  167. },
  168. }
  169. }
  170. ```
  171. ---
  172. ### Inietta variabili d'ambiente
  173. Inietta variabili d'ambiente in tutte le esecuzioni di shell (strumenti AI e terminale utente):
  174. ```javascript title=".opencode/plugins/inject-env.js"
  175. export const InjectEnvPlugin = async () => {
  176. return {
  177. "shell.env": async (input, output) => {
  178. output.env.MY_API_KEY = "secret"
  179. output.env.PROJECT_ROOT = input.cwd
  180. },
  181. }
  182. }
  183. ```
  184. ---
  185. ### Strumenti personalizzati
  186. I plugin possono anche aggiungere strumenti personalizzati a opencode:
  187. ```ts title=".opencode/plugins/custom-tools.ts"
  188. import { type Plugin, tool } from "@opencode-ai/plugin"
  189. export const CustomToolsPlugin: Plugin = async (ctx) => {
  190. return {
  191. tool: {
  192. mytool: tool({
  193. description: "This is a custom tool",
  194. args: {
  195. foo: tool.schema.string(),
  196. },
  197. async execute(args, context) {
  198. const { directory, worktree } = context
  199. return `Hello ${args.foo} from ${directory} (worktree: ${worktree})`
  200. },
  201. }),
  202. },
  203. }
  204. }
  205. ```
  206. L'helper `tool` crea uno strumento personalizzato che opencode può chiamare. Accetta una funzione di schema Zod e restituisce una definizione di tool con:
  207. - `description`: cosa fa lo strumento
  208. - `args`: schema Zod per gli argomenti dello strumento
  209. - `execute`: funzione eseguita quando lo strumento viene chiamato
  210. I tuoi strumenti personalizzati saranno disponibili in opencode insieme agli strumenti integrati.
  211. :::note
  212. Se uno strumento di un plugin usa lo stesso nome di uno strumento integrato, lo strumento del plugin ha la precedenza.
  213. :::
  214. ---
  215. ### Logging
  216. Usa `client.app.log()` invece di `console.log` per logging strutturato:
  217. ```ts title=".opencode/plugins/my-plugin.ts"
  218. export const MyPlugin = async ({ client }) => {
  219. await client.app.log({
  220. body: {
  221. service: "my-plugin",
  222. level: "info",
  223. message: "Plugin initialized",
  224. extra: { foo: "bar" },
  225. },
  226. })
  227. }
  228. ```
  229. Livelli: `debug`, `info`, `warn`, `error`. Vedi la [documentazione SDK](https://opencode.ai/docs/sdk) per i dettagli.
  230. ---
  231. ### Hook di compaction
  232. Personalizza il contesto incluso quando una sessione viene compattata:
  233. ```ts title=".opencode/plugins/compaction.ts"
  234. import type { Plugin } from "@opencode-ai/plugin"
  235. export const CompactionPlugin: Plugin = async (ctx) => {
  236. return {
  237. "experimental.session.compacting": async (input, output) => {
  238. // Inject additional context into the compaction prompt
  239. output.context.push(`
  240. ## Custom Context
  241. Include any state that should persist across compaction:
  242. - Current task status
  243. - Important decisions made
  244. - Files being actively worked on
  245. `)
  246. },
  247. }
  248. }
  249. ```
  250. L'hook `experimental.session.compacting` scatta prima che l'LLM generi un riassunto di continuazione. Usalo per iniettare contesto specifico di dominio che il prompt di compaction predefinito potrebbe non includere.
  251. Puoi anche sostituire completamente il prompt di compaction impostando `output.prompt`:
  252. ```ts title=".opencode/plugins/custom-compaction.ts"
  253. import type { Plugin } from "@opencode-ai/plugin"
  254. export const CustomCompactionPlugin: Plugin = async (ctx) => {
  255. return {
  256. "experimental.session.compacting": async (input, output) => {
  257. // Replace the entire compaction prompt
  258. output.prompt = `
  259. You are generating a continuation prompt for a multi-agent swarm session.
  260. Summarize:
  261. 1. The current task and its status
  262. 2. Which files are being modified and by whom
  263. 3. Any blockers or dependencies between agents
  264. 4. The next steps to complete the work
  265. Format as a structured prompt that a new agent can use to resume work.
  266. `
  267. },
  268. }
  269. }
  270. ```
  271. Quando `output.prompt` è impostato, sostituisce completamente il prompt di compaction predefinito. In questo caso l'array `output.context` viene ignorato.