Official

opencode-v2

OpenCode 2 agent provider: runs opencode serve (2.x) and talks to its /api over HTTP and server-sent events.

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/opencode-v2@0.1.4

Permissions in 0.1.4

  • Provide agents agents.provideMediumAdds agents to the app.Provide the OpenCode 2 agent, and serve plugin tools to it through the host's loopback MCP server
  • Run named programs processMediumStarts the listed programs.Run the OpenCode 2 server (`opencode serve`, or the binary you choose in Settings), read its version and update it (`opencode upgrade`), and ask npm for the newest versionPrograms: opencode${settings.binaryPath}npm
  • Network access netMediumConnects to the listed hosts.Talk to the OpenCode server it starts on this computer, at the port it picks for each launch, to the OpenCode background service on this computer, and to the external server you choose in SettingsHosts: localhost:*${settings.serverUrl}
  • Environment variables envMediumReads the listed environment variables.Read the user name and password of the OpenCode server, and where OpenCode keeps its background service recordVariables: OPENCODE_SERVER_USERNAMEOPENCODE_SERVER_PASSWORDDIVERGENCE_OPENCODE_SERVER_PASSWORDXDG_STATE_HOMEHOME
  • Read files fs.readMediumReads files in the listed places.Read the record of the OpenCode background service (its address and password) so chats use the service you already run instead of starting another serverPlaces: ~/.local/state/opencode/service.json

Files

NOTES.md19 KB
# OpenCode 2 provider plugin — decisions

The provider was checked against the OpenCode `v2.3.0` source and release notes on November 14, 2026. The installed binary is `2.2.7`, whose form validation, usage route and compaction start event remain compatible. Older foreground subagent results are still supported. The source reference is github.com/anomalyco/opencode:

| What                                                                         | Where in the source                                                                                                              |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| HTTP routes, query and body shapes                                           | `packages/protocol/src/groups/*.ts`, `packages/protocol/openapi.json` (served at `GET /openapi.json`; `GET /doc` is the web app) |
| Session events                                                               | `packages/schema/src/session-event.ts`                                                                                           |
| Permission, form and catalog events                                          | `packages/schema/src/{permission,form,provider,model,agent,command,skill}.ts`, `event-manifest.ts`                               |
| Session semantics (inbox, steer and queue, execution, retries, instructions) | `specs/v2/session.md`                                                                                                            |
| The event stream                                                             | `specs/v2/event-stream-architecture.md`                                                                                          |
| Catalog lifecycle                                                            | `specs/v2/catalog-config-plugin-lifecycle.md`                                                                                    |
| The subagent tool                                                            | `packages/core/src/tool/plugin/subagent.ts`, `session/subagent-completion.ts`                                                    |
| MCP tools and code mode                                                      | `packages/core/src/tool/mcp.ts`, `mcp/client.ts`                                                                                 |

The 1.x provider (`plugins/opencode`) stays in the repository, off by default (`disabledByDefault`). The two serve different agent ids (`opencode`, `opencode-v2`), so a chat started on one never resumes on the other: 2.x sessions live in a different store.

| File                                       | What it holds                                                                       |
| ------------------------------------------ | ----------------------------------------------------------------------------------- |
| `main.ts`                                  | registration and the settings that pick the binary or an external server            |
| `server.ts`                                | the `opencode serve` child, credentials, requests                                   |
| `api.ts`                                   | Zod schemas of the API shapes and events the plugin reads                           |
| `agent.ts`                                 | the agent: event stream, runs, subagents, approvals, forms, every `agent/*` handler |
| `map.ts`                                   | tool rows, question cards, usage and history (pure)                                 |
| `history.ts`, `usage.ts` | imported child executions and plans, and Console usage windows |
| `types.ts`                                 | the agent's state: config, chats, subagents, calls, the event stream                |
| `options.ts`, `prompt.ts`, `permission.ts` | options from the live catalog, prompt bodies, the permission ruleset                |

## Transport

`opencode serve --hostname 127.0.0.1 --port 0` with a password made up for the plugin's lifetime (2.x refuses anonymous requests). `--port 0` works in 2.x: the startup line `server listening on http://127.0.0.1:<port>` names the port, and `GET /api/info` confirms the server. The binary must report a 2.x version; a 1.x binary is refused with a message naming the setting to change.

Unless the agent points at an external server (a configured one or the discovered background service), `initialize` reports `maintenance`: the binary's `--version` against the newest `@opencode/cli` on npm. OpenCode 2 updates itself (`opencode upgrade` finds the method it was installed with), so `agent/update` runs that and stops the local server, which is the old build.

Everything lives under `/api`. Catalog routes take `location[directory]=<folder>`; the session list takes `directory`.

## One event stream

`GET /api/event` is one stream for every location (each frame carries its `location`). It is volatile by contract: a slow reader is cut off and events during a disconnect are lost. The plugin opens it before the first prompt and waits for the first frame (`server.connected`). A dropped connection reconnects with backoff; after it, runs whose session is no longer active (`GET /api/session/active`) end with the outcome `GET /api/session/{id}` reports, and pending permissions and forms are read again (`GET /api/permission/request`, `GET /api/form`) so no card waits for an answer that cannot come. Only a local server that exited, or an external one unreachable for a minute, fails the runs. A run whose prompt the server has not answered yet is left out of that check, since it may not be active there yet. The catch-up is tried twice; when both fail, each running chat gets an error notice instead of spinning in silence. A discovered background service is forgotten when a request or the stream to it fails, so the next call finds it again or starts a server of its own.

## Labelled conversation context

Context is sent with the human request as labelled text, with persisted native-message provenance. POST admission and correlated `session.inbox.delivered` consumption are separate receipts; history replay reports the combined envelope instead of treating it as a new human message. Create/resume starts no inference.

The local transport passed a live OpenCode 2.0.16 A→B→A tool-only JSONL retrieval and native-session reuse check, including recreation of A's provider runtime. This was a provider transport check, not full native-app GUI acceptance or agent-driven `dvg`/IPC regeneration acceptance.

Ordinary workspace files and command execution are advertised for provider-owned servers and configured loopback servers running directly on this host. Loopback is not proof of a shared filesystem for SSH forwarding or containers; those deployments are outside this local-access assumption. Nonloopback external servers advertise labelled ingress but not access to host-local artifacts or commands.

## The catalog is built after the start

A server builds its providers, models and agents in the background after it starts (catalog transforms run as plugins activate), so the first reads can answer empty lists, and the model routes answer 503 ("Location plugins did not finish activating") while a folder's OpenCode plugins still activate. A catalog with no usable model, or a 503, is read again for up to 20 s, at once when a catalog event (`provider.updated`, `model.updated`, `agent.updated`, ...) arrives. A catalog still empty after that is cached like any other, so later pickers fail at once; the next catalog event or reconnect drops it. A stored model the catalog no longer lists is not shown as the choice: the default (or the first usable model) is, which is what the session runs on. Those events also drop the cached catalog and send every chat of that folder its options again (`config_options`).

## Sessions, model and mode

- Create: `POST /api/session` with `location`, `agent`, `model` and the permission ruleset.
- Model, variant and mode are session state in 2.x, not prompt fields: `POST /api/session/{id}/model` `{model:{providerID,id,variant?}}` and `POST /api/session/{id}/agent` `{agent}`. The plugin sends each one before a prompt only when it changed since it last told the session.
- The model option value is `<providerID>/<id>`, where `id` is the catalog entry's own id (two entries can share one provider model, for example a "fast" entry).
- Prompt: `POST /api/session/{id}/prompt` `{id, text, files?, skills?}`. The message id is `msg_<host item id>`. A prompt during a run is sent with `delivery: "steer"` and returns the active run id (`steer: true`). The active run is read after the waits of preparation, and a steer whose run ended while its context was being kept is rejected rather than sent under the finished run's id.
- Mentions stay in the text; each file or skill attachment names its span (`mention: {start, end, text}`). Images and audio go as `data:` URIs.
- A prompt whose text starts with a command the server lists goes to `POST /api/session/{id}/command` `{name, text}`. A refused command ends its own run, but one sent as a steer rejects only its input.
- Cancel: `POST /api/session/{id}/interrupt` on the chat and its subagents, after pending permissions are rejected and forms dismissed.
- Plugin instructions: the instruction entry `divergence` (`PUT /api/experimental/session/{id}/instructions/entries/divergence`).
- Rollback: 2.x has no message delete (only GET under `/message`). The plugin checks the message exists (`GET .../message/msg_<id>`), refuses when the session already has a staged revert that restored files (staging again would write them back), then `POST .../revert/stage {messageID, files: false}` and `POST .../revert/commit` at once. `files: false` keeps the workspace untouched; commit deletes the boundary message and every later message. Divergence restores the files from its own checkpoints. Research: `plans/performance-and-markdown/research/opencode-2-message-deletion.md`.
- Sign-in is not offered.

Session listing follows every `cursor.next` until exhausted. Continuation requests send the cursor and page size because the cursor carries the initial filters.

## Runs

`session.execution.started` / `succeeded` / `failed` / `interrupted` bound a run. A run the plugin did not start (a queued prompt, a background subagent result) is announced with `run_started`. Exactly one `run_finished` per run: the run is removed before it is reported.

## Event mapping

- Text and reasoning: `session.{text,reasoning}.delta` append to the item `<messageID>/<kind>/<ordinal>`; `.ended` replaces it with the whole block, so a lost delta does not stay lost.
- Tools: a call id is unique only within a step, so the item id is `<assistantMessageID>/<callID>`. `session.tool.input.started` starts the row, `session.tool.called` gives its input and title, `.success` and `.failed` end it. Edits carry the patches in `metadata.files`; commands show their output as a terminal with `metadata.exit`. Plugin tools reach OpenCode as `divergence_<tool>`; the row title drops the prefix.
- Successful `todowrite` calls publish `metadata.todos` as the host plan. History restores the latest successful list without adding transcript rows. Native `cancelled` todos stay `cancelled` only when `agent/initialize` lists `planCancelled` in `hostFeatures`; other hosts keep receiving `completed`. History versions include the negotiated plan status support so a host upgrade rereads cached plans.
- Image file content becomes host image content in live tools and history. Inline base64 data and local file URIs are supported; other downloadable media need a broader host attachment contract.
- Compaction starts with `compacting`, from either the native start event or a manual request. Duplicate starts are combined. Completion sends `compacted`; native failure or a failed manual request clears the running indication, and the error remains visible.
- Usage: `session.usage.updated` (cumulative cost) with the tokens of the last `session.step.ended`, and the context window of the model the step ran on.
- `session.retry.scheduled` is a warning; `session.step.failed` an error.

## Subagents

The `subagent` tool creates a child session and reports its id in tool metadata. In 2.3.0 every call returns immediately with `status: "running"`, including follow-ups to existing children. Final reports arrive as synthetic messages with `metadata.source: "subagent"`, `childID` and `state`; the report body supplies the task summary. Child execution events determine live status. Imported tasks use the active execution list, the child session outcome and busy/idle timestamps, and the latest applicable synthetic report. The launch tool completing never completes a background child. Older foreground calls retain their final result when metadata says `completed`. Imports containing child tasks omit a parent-only history version because child execution state can change without updating the parent timestamp. Child history failures propagate instead of silently producing empty transcripts. Every event of a child session goes to the chat with `taskId` set to the child, and `cancel_task` interrupts the child and its own children.

## Approvals and forms

`permission.asked` → an approval with OpenCode's replies (`once`, `always` when the request names what it saves, `reject`), answered with `POST /api/session/{id}/permission/{requestID}/reply {decision}`. Full access answers `once` itself; when that reply fails, the card is shown as in the other modes. The question tool asks through a form: `form.created` → a question card; answered with `POST .../form/{id}/reply {answer}`, dismissed with `DELETE .../form/{id}`. The plugin applies each native field default when its answer is empty, including hidden fields, and omits answers whose `when` conditions are inactive. Conditions use earlier normalized answers, so inactive fields also disable dependent fields. Question fields carry their native defaults and conditions, with condition keys mapped to the same field ids used by the card and native `neq` mapped to host `ne`. Older hosts ignore these optional fields and still use the plugin's submission rules. OpenCode's `packages/schema/src/form.ts` has no secret field or password format, so the plugin does not infer `secret` from a hidden field. External actions use the question URL and a boolean acknowledgement. Only a cancel dismisses the form. The existing contract exposes only one external URL per question. An answer to a form or approval that no longer waits answers `{ notPending: true }`.

## Usage limits

`usage_limits` reads `/api/experimental/usage/limits` for the known session and catalog locations, or the default location when none is known. Native Go rolling, weekly and monthly allowances become windows with the supplied percentages, blocked flags and reset times. Console budgets retain their native workspace and budget metadata. Per-model budgets use each model's spend; combined sets use the reported total. Window ids include the Console workspace id, and repeated locations for one workspace are combined. A native null response means the location is not signed in. Failed reads propagate instead of replacing limits with empty data. Selecting limits by the active workspace needs workspace scoping in the host request.

## Permissions

The shared modes become a session ruleset (`PATCH /api/session/{id} {permissions}`; the session's rules follow the agent's and the last match wins). Supervised asks for everything but reads, searches, the question tool and starting subagents; Auto-accept edits allows `edit`; Full access allows everything. Auto is not offered: OpenCode has no approval reviewer (its `--auto` flag allows whatever is not denied, with nothing deciding). A chat that has not chosen a mode starts in Auto-accept edits, the shared default for agents without a reviewer.

## Plugin tools

The host serves the session's tools (`host/mcp.serve`); the plugin adds the address for the folder with `PUT /api/experimental/mcp/divergence {config:{type:"remote", url, codemode:false}}` — a runtime-only server, not written to the user's config. `codemode: false` makes them direct tools instead of entries behind OpenCode's code-mode `execute` tool. The status is checked with `GET /api/mcp`; a failure is a warning in the chat.

## Tests

`node --import ./plugins/testing/register.mjs --test plugins/opencode-v2/*.test.ts` runs the provider suite from the repository root. `audit.test.ts` covers the 2.3.0 findings, including forms, imported executions, image results, pagination, terminal cancellation, usage limits, plans and compaction. The server is scripted by `testing.test.ts`. `pnpm typecheck:plugins` checks the plugin types, and `node scripts/slop/check.mjs` checks the repository rules. The live test is `DIVERGENCE_E2E_OPENCODE_MODEL=opencode/space-bunny-free cargo test -p divergence-host --test e2e opencode_v2_calls_a_plugin_tool -- --ignored`: one turn that calls a plugin tool, then the chat imported again from OpenCode's history.

## Background terminals

The 2.3.0 shell contract, also present in the installed 2.2.7 binary, exposes `shellID` and `status: "running"` in a background shell tool's successful result. Its `GET /api/shell/:id/output` response is `{ data: { output, cursor, size, truncated } }`, using an absolute byte cursor. The provider polls this route while the task lives and caps its captured output at 256 KiB. Completion is the native `session.synthetic` event with `metadata.source: "shell"`, `shellID`, `state`, `exit`, `signal` and `timeout`; its `<shell>` block holds the final output. The `shell.exited` event settles the task immediately, before that notification is delivered. Individual terminal cancellation calls `DELETE /api/shell/:id` with the owning workspace location, then publishes the cancelled snapshot while leaving the parent run and other tasks running. A failed delete preserves the running task and reports the error. Foreground shell tools and subagent handling stay separate. The public schema and routes are in `packages/schema/src/shell.ts` and `packages/protocol/src/groups/shell.ts` in the upstream repository.

## MCP Apps

OpenCode 2.3.0 cannot provide MCP Apps through its HTTP API, so the plugin leaves `capabilities.mcpApps` off even when the host lists `mcpApps`. `packages/protocol/src/groups/mcp.ts` offers a resource catalog but no resource read or tool call route for clients. In `packages/core/src/mcp/client.ts`, `toCallToolResult` turns embedded text resources into plain text without their URI, MIME type or `_meta.ui`. Blob resources keep their URI and MIME type temporarily, but `packages/core/src/tool/mcp.ts` turns HTML into a text resource description. `packages/schema/src/tool.ts` exposes only text and file content, so live events and history contain no embedded HTML resource that can safely become an `mcp_app` block.

OpenCode preserves `structuredContent` as its tool output, but drops the MCP result's `_meta` and converts its content. An MCP error becomes a native tool failure with a text message. Recovering the original `CallToolResult` or resource metadata requires upstream support; parsing HTML out of text would invent the missing resource identity and metadata.

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.1.5latestNov 21, 2026>=5 <672.4 KB5 permissionsListed
0.1.4Nov 16, 2026>=5 <672 KB5 permissionsListed
0.1.3Nov 11, 2026>=5 <662.4 KB5 permissionsListed
0.1.2Nov 9, 2026>=5 <659.2 KB5 permissionsListed
0.1.1Oct 27, 2026>=2 <458.4 KB5 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.