--- name: create-update-opencode-plugin description: > Use this skill when creating, updating, debugging, or configuring OpenCode V2 plugins: local plugin directories under `.opencode/plugins/` or `~/.config/opencode/plugins/`, published packages in `opencode.json(c)`, server plugins (`Plugin.define` setup/effect), CLI/TUI extensions, and embedded `@opencode/client` or `@opencode/sdk` integrations. Covers plugin discovery and enablement, synchronous domain transforms (agent, provider, model, tool, command, skill, MCP, VCS, worktree, ...), runtime hooks (session, tool, shell, permission), custom tools, storage, RPC contracts, Cloudflare workerd, and OpenTUI 0.6. Use when customizing domains at runtime, protecting files or shell commands, publishing packages with `./rpc` or `./tui` exports, or debugging plugin load/execution. license: MIT compatibility: claude-code, codex, chatgpt, hermes, opencode, copilot, antigravity metadata: audience: developers workflow: plugin-development --- # OpenCode Plugin Development (V2) Build server plugins with `@opencode/plugin` (Promise) or `@opencode/plugin/effect`, and terminal plugins with `@opencode/plugin/tui`. V1 plugins (`server()` hooks) still load; see [Support V1](#support-v1) and the [migration guide](https://opencode.ai/v2/docs/build/plugins/migrate-v1). ## Quick Start Local plugins load automatically from `.opencode/plugins/` or `~/.config/opencode/plugins/`; OpenCode resolves `@opencode/plugin` at runtime. ```ts title=".opencode/plugins/example/index.ts" import { Plugin } from "@opencode/plugin" export default Plugin.define({ id: "example", async setup(ctx) { await ctx.storage.set("loaded", true) return () => console.log("unloaded") }, }) ``` Effect plugins use `Plugin.define({ id, effect })` from `@opencode/plugin/effect`; the plugin `Scope` closes on reload/unload. Declare `effect@4.0.1` as a peer and never bundle it. ## Loading - **Auto-discovery**: direct `.ts`/`.js` files and immediate package directories under `.opencode/plugins/` or `~/.config/opencode/plugins/`. - **Configured**: add packages/directories to `plugins` in `opencode.json(c)`. Relative paths resolve from the config file; local paths must be directories with an `index`/`server` module (single-file paths are skipped). - **Precedence**: `~/.config/opencode/opencode.jsonc` < `./opencode.jsonc` < `./.opencode/opencode.jsonc`; arrays merge lowest to highest. - **Control**: `-id` disables, `*` matches all, `.*` matches an ID prefix, later IDs re-enable. `opencode.config.policy` and `opencode.provider.opencode` cannot be disabled. - **CLI**: `opencode plugin add|list|check|update|remove`; npm versions/tags/ranges and Git specs work, tarball/npm alias targets do not. CLI-only plugins use `cli.json`. - **Reload**: watched config dirs reload automatically; use `opencode service restart` for unwatched local dependencies. Details: `references/loading-and-configuration.md`. ## Context `ctx` exposes `app`, `location` (`directory`, `workspaceID`, `project`), `options`, and domains `agent`, `provider`, `model`, `command`, `integration`, `mcp`, `reference`, `skill`, `tool`, `vcs`, `websearch`, `worktree`, `session`, `permission`, `generate`, `event`, `storage`, `rpc`, `plugin`, `credential`, `aisdk`. `ctx.location` is the plugin instance location. ## Transforms Synchronous edits applied in registration order per domain. Load external data before the callback; `reload()` replays transforms without rerunning setup. Domains: `agent`, `provider`, `model`, `command`, `integration`, `mcp`, `reference`, `skill`, `tool`, `vcs`, `websearch`, `worktree`; each exposes an editor plus `reload()`. `transform` returns a `Registration`; `dispose()` removes it. Effect transforms are `yield*`-ed in the plugin scope. Per-domain editor signatures: `references/domain-transforms.md`; advanced domains: `references/domain-transforms-advanced.md`. ## Hooks Hooks intercept live operations; later hooks see earlier changes. Session hooks: `prompt`, `context`, `compaction`, `generate`, `title`, `model.request`, `http.request`, `http.response`, `experimental.ws.*`, `retry` (provider-scoped except `prompt`). Tool: `execute.before/after`. Shell: `create.before`. Permission: `evaluate`. Details: `references/events-and-hooks.md`. Permission requests use `ctx.permission.assert/list/get/reply`; session rules use `ctx.session.update({ sessionID, permissions })`. Details: `references/permissions.md`. ## Custom Tools Register with `ctx.tool.transform`: Promise plugins use JSON Schema or Standard Schema, Effect plugins use `Schema`. Executors return `{ content }` (Promise) or `{ output }` (Effect), receive `context.progress`, and Promise executors also receive `context.signal`. Effective ids are `namespace_name` (dots/unsupported chars become `_`). Details: `references/custom-tools-guide.md`. ## Storage Durable JSON scoped to the plugin: `ctx.storage.get/set/remove/scan({ prefix, after?, limit? })`. Use `ctx.storage`, not raw file writes. ## RPC Define contracts with `Rpc.define` from `@opencode/plugin/rpc`, register with `ctx.rpc.register(Acme, handlers)`, and call with `client.rpc(Acme)` or `ctx.rpc(Acme)`. Subscribe with `events.on`/`events.subscribe`. Event data must be an object; `rpc.*` errors are reserved; subscriptions are live-only. Details: `references/rpc.md`. ## CLI / TUI Plugins `@opencode/plugin/tui` adds commands, keymaps, routes, slots, dialogs, toasts, panels, data, notifications, Markdown renderers, and storage. Use `usePlugin()` in Solid components. OpenTUI 0.6 resources need `context.renderer.nativeScene` as owner. See `references/tui-plugins.md`; UI patterns: `references/tui-ui.md`; slots/panels: `references/tui-panels.md`. ## Client & SDK - **`@opencode/client`**: `OpenCode.make({ baseUrl, headers, fetch? })`; per-request options are the final argument (`signal`, `headers`); streams are async iterables over a lazy shared connection. - **`@opencode/client/service`** (Node): `Service.discover/ensure/stop/headers`. - **`@opencode/sdk`**: embedded host; `OpenCode.create({ plugins })`, `opencode.sessions.*`, `opencode.events.*`, `opencode.plugin(plugin)`. - **Effect variants**: `@opencode/client/effect`, `@opencode/sdk/effect`, `@opencode/plugin/effect`; Effects/Streams, `Scope` lifetime, `effect@4.0.1`. - **Cloudflare**: `@opencode/sdk/workerd` (`OpenCodeWorkerd.create({ storage, config, plugins })`) with `state.blockConcurrencyWhile`; enable `nodejs_compat`. See `references/client-and-sdk.md`; Cloudflare: `references/cloudflare.md`. ## Publishing ```json { "name": "opencode-acme-plugin", "version": "1.0.0", "type": "module", "exports": { ".": "./src/index.ts", "./rpc": "./src/rpc.ts" }, "dependencies": { "@opencode/plugin": "latest" } } ``` `./rpc` shares the contract without loading the implementation. TUI plugins export `./tui` and declare peers `@opentui/core`, `@opentui/solid`, `solid-js` (`>=0.6.6`). Effect plugins declare `effect` as a peer, pin the same version under `devDependencies`, and never bundle `effect`. CLI-only packages use `cli.json`. Test the installed package, not only a workspace link. ## Support V1 ```ts import { Plugin } from "@opencode/plugin" export default { ...Plugin.define({ id: "example", async setup(ctx) { await ctx.tool.hook("execute.before", () => {}) } }), async server() { return { "tool.execute.before": async () => {} } }, } ``` V1 calls `server()`; V2 reads `id` + `setup()`/`effect()` and ignores `server()`. The V1 object form is supported in OpenCode `1.18.29`; test with the oldest V1 release you target. ## Gotchas - **Transforms are synchronous**; never await inside the callback. Load data first. - **Local plugin paths are directories**; a path to a single file is skipped. - **Project-root `plugins/` is not auto-discovered**; move it under `.opencode/` or configure it. - **Config arrays merge**; use `-id` to disable instead of deleting lower-precedence entries. - **Built-in plugins cannot be disabled**: `opencode.config.policy`, `opencode.provider.opencode`. - **Hooks mutate drafts only**; they never change persisted history or configuration. - **Tool snapshots** are per model request; reload/dispose affects future requests only. - **Prompt hooks are not exactly-once**; retries may run them, but only the first admission wins. - **RPC event data must be an object**; `rpc.*` errors are reserved; subscriptions are live-only. - **Effect plugins must not bundle `effect`**; only public `effect/*` subpaths are provided. - **OpenTUI 0.6**: pass `nativeScene` to `SyntaxStyle`/buffers, use `getLayout()`/ `invalidateIntrinsicSize()` instead of removed getters, and destroy resources with `context.renderer.idle()`. - **Cleanup**: dispose registrations, clear intervals, abort event streams, or close Effect scopes. - **Secrets**: read from env or `ctx.integration.connection.resolve()`; never hardcode. ## Reference Triggers | Reference | When to use | File | |-----------|-------------|------| | Loading & Configuration | Discovery, config precedence, enablement, CLI management, reload | `references/loading-and-configuration.md` | | Domain Transforms | Agent, provider, model, command, MCP, reference examples | `references/domain-transforms.md` | | Advanced Transforms | Skill, integration, VCS, websearch, worktree, session, credential | `references/domain-transforms-advanced.md` | | Hooks & Events | Session/tool/shell hooks, permission evaluate, event subscriptions | `references/events-and-hooks.md` | | Permissions | `assert/list/get/reply`, session-scoped rules | `references/permissions.md` | | Custom Tools | Schemas, namespaces, executors, snapshots | `references/custom-tools-guide.md` | | Lifecycle & Patterns | Lifecycle, options, storage, reload, publishing, V1, validation | `references/lifecycle-and-advanced-patterns.md` | | RPC | Defining, registering, calling, subscribing | `references/rpc.md` | | Client & SDK | Client, SDK, Effect variants, Effect packaging | `references/client-and-sdk.md` | | Cloudflare | `@opencode/sdk/workerd` Durable Object host | `references/cloudflare.md` | | CLI / TUI Core | Setup, client, events, sessions, location data, OpenTUI 0.6 | `references/tui-plugins.md` | | TUI UI Patterns | Markdown, keymaps, storage, dialogs, routes, tabs, model | `references/tui-ui.md` | | TUI Slots & Panels | Slots, session panels, formatting, publishing | `references/tui-panels.md` | | Upstream docs | Checking exact upstream wording, a field name, or a page the digest does not cover | `references/docs/` (8 pages) | `references/docs/` holds the unmodified OpenCode V2 plugin pages (8 files: build overview, server, TUI, GUI, RPC, migration, plus the two configuration pages), each starting with ``. Load them when this digest and the live docs disagree. ## Scripts `scripts/scaffold_plugin.ts --name [--with-tool]` creates a plugin; `scripts/validate_plugin_structure.ts ` auto-detects the mode (entry/id/`Plugin.define` vs config `plugins[]`); and `scripts/validate_plugin_mcp.ts ` validates the `mcp` block. ## Validation Checklist - [ ] Unique plugin `id`; `Plugin.define` with `setup` or `effect` - [ ] Local plugin is a directory with `index`/`server`; package entrypoints resolve - [ ] Types import from `@opencode/plugin` (`/effect`, `/tui`, `/rpc`) - [ ] Effect plugin: `effect` peer + pinned dev dependency; not bundled - [ ] Transform callbacks synchronous; external data loaded before transform/reload - [ ] Tool schemas include descriptions/types; executors honor `context.signal` - [ ] Hooks mutate drafts only; before-hook errors are instructive - [ ] RPC events carry object data; `rpc.*` names avoided - [ ] TUI resources use `nativeScene` and are destroyed on renderer idle - [ ] Registrations, intervals, and subscriptions cleaned up - [ ] Storage uses `ctx.storage` (JSON), not raw file writes