plugins.mdx 13 KB

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