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.3
Permissions in 0.1.3
Files
NOTES.md14.6 KB
# OpenCode 2 provider plugin — decisions
The reference for every shape here is the OpenCode source at the tag of the installed version (github.com/anomalyco/opencode, `v2.0.16`):
| 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) |
| `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`.
- Not offered: usage limits, sign-in.
## 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.
- 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 (`session.created` with `parentID`, titled with the call's `description`), reports it in `session.tool.progress` metadata (`{sessionID, status}`), and ends with `<subagent sessionID=".." state="completed">TEXT</subagent>`. A call that continues an earlier child (`sessionID` input) creates no session: the progress event names it, and the plugin looks it up. A background call answers at once (`status: "running"`); its result arrives later as a `session.synthetic` message in the parent with `metadata.source: "subagent"`. Every event of a child session goes to the chat with `taskId` = the child; `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}`. A submit with every field empty is a reply with `{}`, which takes the defaults; only a cancel dismisses. An answer to a form or approval that no longer waits answers `{ notPending: true }`.
## 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
`pnpm -C plugins test` runs the mapping and agent tests against a scripted server (`testing.test.ts`). 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 installed 2.0.28 binary's embedded source 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. 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.
Local HTTP access and starting a probe server were denied by the execution sandbox, so the installed source and scripted HTTP fixtures establish the contract here. The OpenCode 1 provider is unchanged because this is a 2.x shell service contract, rather than a field that can be copied into 1.x.
No comments yet.