plugins.mdx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. ---
  2. title: "Plugins"
  3. description: "Extend OpenCode with plugins."
  4. ---
  5. Plugins extend OpenCode in-process. They can transform agents, models, commands,
  6. integrations, references, skills, and tools; intercept model requests and tool
  7. execution; and call a subset of the V2 client.
  8. <Warning>
  9. The V2 plugin API is beta. Entrypoints, hooks, draft shapes, and configuration may change before the stable release.
  10. Use the `/v2` exports described on this page.
  11. </Warning>
  12. ## Load plugins
  13. Plugins can be loaded from npm packages, explicit local paths, or config
  14. directories. Each module must have one default export containing a unique
  15. plugin `id` and a `setup` function.
  16. ### Configuration
  17. Add ordered entries to the `plugins` field in `opencode.json(c)`:
  18. ```jsonc title="opencode.jsonc"
  19. {
  20. "$schema": "https://opencode.ai/config.json",
  21. "plugins": [
  22. "opencode-acme-plugin@1.2.0",
  23. "@acme/opencode-plugin",
  24. "./plugins/local.ts",
  25. {
  26. "package": "./plugins/reviewer.ts",
  27. "options": {
  28. "agent": "reviewer",
  29. "strict": true,
  30. },
  31. },
  32. ],
  33. }
  34. ```
  35. A string is either a package specifier or a local path. Local paths must start
  36. with `./` or `../` and resolve relative to the configuration file containing
  37. the entry. Absolute paths and `file://` URLs are also supported. Both scoped
  38. packages and versioned package specifiers are supported.
  39. Use the object form to pass JSON configuration to the plugin. OpenCode passes
  40. `options` unchanged as `ctx.options`; omitted options become an empty object.
  41. The plugin owns validation and defaults for its options.
  42. See [Config](/config#locations) for configuration locations and precedence.
  43. Entries from all applicable files are processed from lowest to highest
  44. precedence rather than replacing the entire array.
  45. ### Local discovery
  46. OpenCode automatically scans this directory in every discovered OpenCode config
  47. directory:
  48. ```text
  49. .opencode/plugins/
  50. ```
  51. The equivalent global directory is `~/.config/opencode/plugins/`. Direct `.ts`
  52. and `.js` children are loaded. An immediate child directory is also loaded as a
  53. package when OpenCode can resolve a string `exports`, `module`, or `main`
  54. entrypoint, or an `index.ts` or `index.js` file.
  55. A `plugins/` directory beside a project-root `opencode.json` is not discovered
  56. automatically. Put it under `.opencode/`, or add its file explicitly with a
  57. relative config entry.
  58. ### Enable and disable
  59. A string beginning with `-` disables plugins by their exported `id`. `*`
  60. matches every ID, and a suffix of `.*` matches an ID prefix. Directives are
  61. applied in order:
  62. ```jsonc title="opencode.jsonc"
  63. {
  64. "plugins": ["./plugins/reviewer.ts", "-acme.reviewer", "-opencode.provider.*", "opencode.provider.openai"],
  65. }
  66. ```
  67. Package specifiers and local paths locate plugin modules; they are not disable
  68. selectors. Use the `id` from the plugin's default export to disable it. A later
  69. ID entry re-enables a loaded or built-in plugin. Explicit config directives run
  70. after local auto-discovery, so they can disable discovered plugins by ID.
  71. User plugins are activated in configured order between OpenCode's internal
  72. plugin phases. Hooks run sequentially in registration order, and later hooks
  73. observe earlier mutations. Do not depend on the internal phase ordering while
  74. the API is beta.
  75. ### Installation and dependencies
  76. OpenCode installs bare package entries and their production dependencies into
  77. an isolated cache. Package installation does not run lifecycle scripts.
  78. Published packages should expose their plugin entrypoint and include every
  79. runtime import in `dependencies`.
  80. Local files and local package directories are imported directly. OpenCode does
  81. **not** install their dependencies. Install dependencies in a `package.json`
  82. visible from the plugin file, for example:
  83. ```sh
  84. cd .opencode
  85. bun add @opencode-ai/plugin@next
  86. ```
  87. Match the plugin package version to the OpenCode release you target.
  88. Configuration and discovered plugin files under watched config directories are
  89. reloaded when they change. Reloading replaces the active plugin generation and
  90. releases its scoped registrations. Restart OpenCode after changing an npm
  91. package version or a local dependency when no watched file changed.
  92. ## Create a plugin
  93. Export the result of `Plugin.define` as the module default:
  94. ```ts title=".opencode/plugins/reviewer.ts"
  95. import { Plugin } from "@opencode-ai/plugin/v2"
  96. export default Plugin.define({
  97. id: "acme.reviewer",
  98. setup: async (ctx) => {
  99. const description =
  100. typeof ctx.options.description === "string" ? ctx.options.description : "Reviews code for regressions"
  101. await ctx.agent.transform((agents) => {
  102. agents.update("reviewer", (agent) => {
  103. agent.description = description
  104. agent.mode = "subagent"
  105. })
  106. })
  107. },
  108. })
  109. ```
  110. `setup` runs each time the plugin is activated. Register long-lived behavior
  111. during setup; do not wait there on an infinite event stream. It may return a
  112. synchronous or asynchronous cleanup function. OpenCode awaits that cleanup
  113. when the plugin is disabled, reloaded, or shut down:
  114. ```ts
  115. setup: async (ctx) => {
  116. const controller = new AbortController()
  117. const task = synchronize(ctx, controller.signal)
  118. return async () => {
  119. controller.abort()
  120. await task
  121. }
  122. }
  123. ```
  124. Hook registrations are released automatically with the same plugin scope. Use
  125. the returned cleanup for resources the plugin owns, such as timers, watchers,
  126. connections, and background tasks.
  127. ### Context
  128. The plugin context is essentially an [OpenCode server client](/build/client).
  129. Its read and action methods use the same inputs and responses as the client. It
  130. adds plugin-only methods for transforms, runtime hooks, reloads, registrations,
  131. and plugin options.
  132. | Capability | Available operations |
  133. | ---------------------- | -------------------------------------------------------------------------------------------- |
  134. | `ctx.agent` | `list`, `transform`, `reload` |
  135. | `ctx.catalog.provider` | `list`, `get` |
  136. | `ctx.catalog.model` | `list`, `default` |
  137. | `ctx.catalog` | `transform`, `reload` |
  138. | `ctx.command` | `list`, `transform`, `reload` |
  139. | `ctx.integration` | `list`, `get`, `connect`, `attempt`, `transform`, `reload`, and connection lookup/resolution |
  140. | `ctx.plugin` | `list` currently active plugin IDs |
  141. | `ctx.reference` | `list`, `transform`, `reload` |
  142. | `ctx.session` | `create`, `get`, `prompt`, `command`, `interrupt`, and `hook` |
  143. | `ctx.skill` | `list`, `transform`, `reload` |
  144. | `ctx.tool` | `transform` and `hook` |
  145. | `ctx.aisdk` | `hook` |
  146. | `ctx.event` | `subscribe` to the current public server event stream |
  147. | `ctx.options` | Readonly options from the matching config object |
  148. ### Transform hooks
  149. Transform hooks let a plugin modify how OpenCode is configured. Use them to add
  150. or remove definitions, override settings, choose defaults, and provide tools or
  151. other sources.
  152. | Transform | Draft operations |
  153. | ----------------------- | ------------------------------------------------------------------------------------------------------- |
  154. | `agent.transform` | `list`, `get`, `default`, `update`, `remove` |
  155. | `catalog.transform` | Provider `list`, `get`, `update`, `remove`; model `get`, `update`, `remove`; default model `get`, `set` |
  156. | `command.transform` | `list`, `get`, `update`, `remove` |
  157. | `integration.transform` | Integration `list`, `get`, `update`, `remove`; method `list`, `update`, `remove` |
  158. | `reference.transform` | `add`, `remove`, `list` |
  159. | `skill.transform` | `source`, `list` |
  160. | `tool.transform` | `add` |
  161. Here's an example that keeps models synced from a remote source:
  162. ```js title=".opencode/plugins/remote-models.js"
  163. import { Plugin } from "@opencode-ai/plugin/v2"
  164. export default Plugin.define({
  165. id: "acme.remote-models",
  166. setup: async (ctx) => {
  167. let models = []
  168. await ctx.catalog.transform((catalog) => {
  169. for (const model of models) {
  170. catalog.model.update(model.providerID, model.id, (draft) => Object.assign(draft, model))
  171. }
  172. })
  173. const refresh = async () => {
  174. const response = await fetch("https://example.com/opencode/models.json", {
  175. signal: AbortSignal.timeout(10_000),
  176. })
  177. if (!response.ok) return
  178. models = await response.json()
  179. await ctx.catalog.reload()
  180. }
  181. await refresh()
  182. const timer = setInterval(() => void refresh().catch(console.error), 60_000)
  183. return () => clearInterval(timer)
  184. },
  185. })
  186. ```
  187. `ctx.catalog.reload()` replays every catalog transform to derive the new
  188. catalog. Each plugin's logic remains composed with the others, so a later
  189. plugin can still modify models added by an earlier one. The catalog updates
  190. without restarting OpenCode.
  191. ### Runtime hooks
  192. Runtime hooks intercept live operations. Their event objects expose specific
  193. mutable fields:
  194. | Hook | Mutable fields |
  195. | ------------------------------------------- | ------------------------------------------------------------------------------ |
  196. | `ctx.aisdk.hook("sdk", callback)` | `sdk`, after inspecting `model`, `package`, and `options` |
  197. | `ctx.aisdk.hook("language", callback)` | `language`, after inspecting `model`, `sdk`, and `options` |
  198. | `ctx.session.hook("request", callback)` | `system`, `messages`, and the `tools` record immediately before model dispatch |
  199. | `ctx.tool.hook("execute.before", callback)` | `input`, before the selected tool executes |
  200. | `ctx.tool.hook("execute.after", callback)` | `result`, `output`, and `outputPaths`, after execution settles |
  201. For example, remove a tool from selected model requests and normalize another
  202. tool's input:
  203. ```ts title=".opencode/plugins/guards.ts"
  204. import { Plugin } from "@opencode-ai/plugin/v2"
  205. export default Plugin.define({
  206. id: "acme.guards",
  207. setup: async (ctx) => {
  208. await ctx.session.hook("request", (event) => {
  209. delete event.tools.write
  210. })
  211. await ctx.tool.hook("execute.before", (event) => {
  212. if (event.tool !== "lookup" || typeof event.input !== "object" || event.input === null) return
  213. event.input = { ...event.input, source: "plugin" }
  214. })
  215. },
  216. })
  217. ```
  218. A hook failure fails the operation it intercepts. Keep runtime hooks fast and
  219. handle expected errors inside the callback.
  220. ## Examples
  221. ### Add a tool
  222. Pass a tool declaration to `tools.add`. Define its input with JSON Schema and
  223. use an async executor:
  224. ```js title=".opencode/plugins/greeting.js"
  225. import { Plugin } from "@opencode-ai/plugin/v2"
  226. export default Plugin.define({
  227. id: "acme.greeting",
  228. setup: async (ctx) => {
  229. await ctx.tool.transform((tools) => {
  230. tools.add({
  231. name: "greeting",
  232. description: "Create a greeting",
  233. jsonSchema: {
  234. type: "object",
  235. properties: {
  236. name: { type: "string" },
  237. },
  238. required: ["name"],
  239. additionalProperties: false,
  240. },
  241. execute: async ({ name }) => {
  242. const text = `Hello, ${name}!`
  243. return {
  244. structured: { greeting: text },
  245. content: [{ type: "text", text }],
  246. }
  247. },
  248. })
  249. })
  250. },
  251. })
  252. ```
  253. Unsupported characters in tool and group names are normalized to underscores.
  254. The resulting exposed key must begin with a letter and contain at most 64
  255. letters, digits, underscores, or hyphens. Set `options` on the declaration to
  256. configure registration with `{ group, codemode }`:
  257. - `group` prefixes and groups the exposed tool name.
  258. - `codemode` defaults to `true` and makes the tool available through the
  259. `execute` CodeMode tool. Set `codemode: false` to expose it directly to the
  260. provider.
  261. The executor receives a second context argument containing `sessionID`,
  262. `agent`, `assistantMessageID`, and `toolCallID`.
  263. ### Add a command
  264. ```js title=".opencode/plugins/review-command.js"
  265. import { Plugin } from "@opencode-ai/plugin/v2"
  266. export default Plugin.define({
  267. id: "acme.review-command",
  268. setup: async (ctx) => {
  269. await ctx.command.transform((commands) => {
  270. commands.update("review", (command) => {
  271. command.description = "Review the current changes"
  272. command.template = "Review the current changes for correctness and missing tests."
  273. })
  274. })
  275. },
  276. })
  277. ```
  278. ### Set the default model
  279. ```js title=".opencode/plugins/default-model.js"
  280. import { Plugin } from "@opencode-ai/plugin/v2"
  281. export default Plugin.define({
  282. id: "acme.default-model",
  283. setup: async (ctx) => {
  284. await ctx.catalog.transform((catalog) => {
  285. catalog.model.default.set("anthropic", "claude-sonnet-4-5")
  286. })
  287. },
  288. })
  289. ```
  290. ## Publish a package
  291. A package plugin uses the same default export as a local plugin. A minimal
  292. manifest is:
  293. ```json title="package.json"
  294. {
  295. "name": "opencode-acme-plugin",
  296. "version": "1.0.0",
  297. "type": "module",
  298. "exports": "./src/index.ts",
  299. "dependencies": {
  300. "@opencode-ai/plugin": "next"
  301. }
  302. }
  303. ```
  304. Use versions compatible with the OpenCode release you target and test the
  305. installed package, not only a workspace-linked copy. Because the plugin API is
  306. beta, publish compatible plugin updates when V2 entrypoints or contracts
  307. change.
  308. ## Verify loading
  309. List active plugin IDs through the V2 API:
  310. ```sh
  311. opencode2 api get /api/plugin
  312. ```
  313. If a plugin is absent, check the server log described in
  314. [Troubleshooting](/troubleshooting#read-logs). Invalid modules and setup failures are
  315. logged; one failing package does not prevent unrelated valid packages from
  316. being resolved.
  317. ## Effect
  318. OpenCode provides a first-class Effect API for plugins through the
  319. `@opencode-ai/plugin/v2/effect` entrypoint. Install `effect` alongside the
  320. plugin package and export an `effect` function instead of `setup`:
  321. ```sh
  322. bun add @opencode-ai/plugin@next effect
  323. ```
  324. ```ts title=".opencode/plugins/reviewer-effect.ts"
  325. import { Plugin } from "@opencode-ai/plugin/v2/effect"
  326. import { Effect } from "effect"
  327. export default Plugin.define({
  328. id: "acme.reviewer-effect",
  329. effect: (ctx) =>
  330. Effect.gen(function* () {
  331. yield* ctx.agent.transform((agents) => {
  332. agents.update("reviewer", (agent) => {
  333. agent.description = "Reviews code for regressions"
  334. agent.mode = "subagent"
  335. })
  336. })
  337. }),
  338. })
  339. ```
  340. Context operations return Effects. The plugin effect is scoped, so finalizers,
  341. fibers, and registrations are released when the plugin reloads or unloads.
  342. OpenCode does not expose its private Core services to the plugin; use the
  343. capabilities on `ctx`.
  344. Typed tools can use `Schema` from `effect` and the contracts exported from
  345. `@opencode-ai/plugin/v2/effect/tool`. Their executors return an Effect and may
  346. fail with the typed tool failure channel.