Skip to content

Latest commit

 

History

History
748 lines (652 loc) · 45.9 KB

V2.md

File metadata and controls

748 lines (652 loc) · 45.9 KB

opencode V2 support

Working plan for supporting opencode 1.x (V1) and opencode 2.x (V2) from one package. Written 2026-09-23 against @opencode/plugin@2.0.11 and @opencode-ai/plugin@1.18.31. Tracker: issue #31. This file supersedes the "not planned" verdict recorded in AGENTS.md.

MCP bridge and Code Mode correction (2026-09-30)

An OpenCode 2.0.18 / plugin 0.32.0 session reported a connected GitHub MCP in OpenCode but MCP servers (on disk): servers in the doctor. The disk reader was still treating V2's mcp.servers container as a V1 server. The MCP bridge now normalizes both shapes, supports disabled, uses V2 per-server replacement and parent-first discovery through filesystem root, and preserves V1 semantics. Host selection is per call/model, never a process-global major-version flag.

Code Mode is a separate problem: its MCP functions are behind a synthesized execute model tool, not server-prefixed tools. The V2 registry shim cannot supply its schema. Explicit proxyOpencodeTools: ["execute"] now reads the current AI SDK tool snapshot, including its real schema and visibility, and the prompt names mcp__opencode_proxy__execute. It remains opt-in and is refused by the read-only preset, since its catalog can include non-MCP tools.

For Code Mode-only routing, pair it with bridgeOpencodeMcp: false and strictMcpConfig: true; do not supply duplicate servers via mcpConfig. Individual proxies instead require codemode: false on the selected servers and proxyOpencodeMcpTools: true. Without that, individual proxy discovery warns and keeps its existing direct fallback. No server is silently excluded based solely on the existence of execute.

Regression coverage: V2 config shapes, disabled/runtime overlays, global and project replacement, ancestor/.opencode precedence, credential-free doctor data, model-visible schemas and a fake-CLI execute → broker → tool-result round trip. These are offline tests, not a live Claude inference probe. See the README's V2 Code Mode recipe for deployment and full-restart guidance.

What changed, and why the old verdict is void

AGENTS.md parked V2 on the reasoning that the v2 API was an additive alternative surface inside opencode 1.x (@opencode-ai/plugin/v2), with no reload of the model implementation path and therefore no payoff. That reading is now wrong on the premise.

V2 is a new major of opencode itself, not a second plugin API inside 1.x. From the migration guide: V1 and V2 both use the opencode command, are no longer installed side by side, and the V2 installer replaces the V1 binary. And, stated as a warning rather than a footnote:

V1 plugin implementations do not run in V2. Moving a file or renaming its config entry is not enough.

So this is not an optimisation. The day the maintainer's opencode moves to 2.x, this plugin stops existing for them, along with every account provider, proxy tool and model id it registers. That is the actual deadline.

Shipped and confirmed on the registry: @opencode/plugin@2.0.11, @opencode/client@2.0.11, @opencode/ai@2.0.11. V1's latest is @opencode-ai/plugin@1.18.31, which is what we build against today.

The decisive question, and its answer

This plugin does not describe a provider. It implements one: ClaudeCodeLanguageModel is a real LanguageModelV3 that spawns and drives the claude CLI. Any migration lives or dies on whether V2 lets a plugin supply a model implementation.

The published V2 plugin documentation says no. Its provider surface is metadata only: ctx.provider.transform adds { info, models }, where info.package names a package opencode instantiates itself ("aisdk:@ai-sdk/openai-compatible", "@opencode/ai/providers/openai-compatible"). Model transforms "apply restrictions and overrides". Nothing in the documented API returns a model object. Taken at face value that would have forced a rewrite into a local HTTP shim speaking the Anthropic Messages protocol, with the CLI behind it.

The shipped package says otherwise. @opencode/plugin@2.0.11 carries an aisdk domain that the website does not document, and it is exactly the escape hatch needed:

// package/dist/promise/aisdk.d.ts
import type { LanguageModelV3 } from "@ai-sdk/provider"

export interface AISDKHooks {
  sdk: {
    readonly model: Model.Info
    readonly package: string
    readonly options: Record<string, any>
    sdk?: any
  }
  language: {
    readonly model: Model.Info
    readonly sdk: any
    readonly options: Record<string, any>
    language?: LanguageModelV3
  }
}
export interface AISDKDomain {
  readonly hook: ModelHooks<AISDKHooks>
}

ctx.aisdk is on the plugin context (dist/promise/context.d.ts), and ModelHooks takes an optional { providerID } scope, so the hook can be limited to our own providers rather than intercepting everyone's models.

Two facts make this cheap rather than a rewrite:

  1. @opencode/plugin@2.0.11 depends on @ai-sdk/provider at 3.0.8. This package already depends on ^3.0.8 and has 3.0.10 installed.
  2. ClaudeCodeLanguageModel.specificationVersion is already "v3".

So the expensive part of this plugin, the several thousand lines of CLI transport, session management, proxy MCP broker and stream translation, is already the exact type V2 asks for. The port is a new entrypoint and a new wiring layer, not a rewrite of the thing that took a year to get right.

Not yet verified, and it is the first thing to probe: whether a provider registered with no resolvable package still reaches the language hook, or whether opencode tries to instantiate the SDK first and fails before we are asked. The sdk hook exists and lets us supply that object too, which suggests the seam is intentional, but a suggestion is not a measurement.

Dual support is officially supported, and our entrypoint is already half of it

From the plugin migration guide, verbatim shape:

export default {
  ...Plugin.define({
    id: "example",
    async setup(ctx) { /* v2 */ },
  }),
  async server() {
    return { /* v1 hooks */ }
  },
}

V1 calls server(), V2 calls setup(). The two implementations stay separate; nothing is translated for us. V1 object entrypoints require opencode >= 1.18.29, which is below the 1.18.31 we already verify against, so adopting this costs no V1 users.

We are already at that shape. src/index.ts:653:

export default {
  id: "@khalilgharbaoui/opencode-claude-code-plugin",
  server,
}

Adding V2 is spreading Plugin.define({...}) into that object. The seam exists; what has to be built is what goes behind it.

Hook mapping

V1 V2 Note
provider returning models() ctx.provider.transform + ctx.aisdk.hook("language") The load-bearing one. Metadata and implementation split across two calls.
chat.params (agent tagging) ctx.session.hook("context"), set event.options V2 gives sessionID directly instead of the x-session-affinity header.
config (registering /btw, /claude-code-doctor) ctx.command.transform with a real execute() Strictly better. V1 forces us to inject into the user's config object and guard against clobbering their own command of that name.
event (session.deleted) ctx.event.subscribe() with an AbortController Cleanup moves into the function setup returns.
MCP bridging (--mcp-config on disk) ctx.mcp.transform May retire a lot of mcp-bridge.ts, including the content-addressed scratch file.
skill bridge ctx.skill.transform / ctx.skill.list() V2 can register a skill directly instead of staging a throwaway plugin dir.
proxy tool discovery ctx.tool.list() V1's registry deliberately excludes MCP tools, which is why proxyOpencodeMcpTools had to read doStream's tools argument. Re-measure on V2.
tool.execute.before/after ctx.tool.hook("execute.before"/"after") Not used here today.
(none; V1 had experimental.chat.messages.transform) ctx.session.hook("context") Edits the request's copy of the history. For a request to another provider, src/portable-history.ts turns the CLI's provider-executed tool parts (toolu_ ids) into text, because an OpenAI-compatible provider refuses them. Replayed parts carry no providerMetadata, so the id is the only signal (measured on 2.2.6, 2026-11-12).
permission.ask ctx.permission.hook("evaluate") Not used here today.

V2 also adds things V1 never had that this plugin has hand-rolled around: ctx.storage for durable plugin state, ctx.session.hook("retry") for provider failure policy (which is the natural home for account failover), and ctx.session.hook("compaction") with a result field that can skip the model call entirely.

Open questions, in the order they should be probed

Each is cheap, each is a measurement rather than a reasoning step, and none needs product code.

  1. Does an unresolvable package still reach aisdk.hook("language")? Register a provider with a nonsense package, hook both sdk and language, log what arrives. If it does not, the answer is to supply the sdk object from the sdk hook too. Everything else in this plan depends on this one.
  2. How does the model learn which session it is serving? V1 reads the x-session-affinity request header, and session affinity is the key to process reuse, proxy call routing and the todo ledger. Check what V2 passes into doStream; if it passes nothing, ctx.session.hook("context") knows the sessionID and can stash it.
  3. Is there a native question tool in V2? Account failover and the plan-mode bridge both end a turn on a synthetic question tool-call and resume from its tool result. V2 registers tools through plugins, so confirm the tool exists and the round-trip still works before porting either feature.
  4. Do MCP tools appear in ctx.tool.list()? If yes, resolveMcpProxyToolDefs gets simpler and the doStream tools argument read can go.
  5. Does the proxy still get permission prompts? V2 renamed permission actions (bash to shell, task to subagent, write/patch to edit) and replaced the per-tool map with one ordered array. The proxy exists so Claude's tool calls run under opencode's permissions; confirm that still holds.
  6. How do we run V2 at all without losing V1? The installer replaces the V1 binary and both use the opencode command. Testing needs a pinned V2 binary in an isolated path with its own XDG_CONFIG_HOME, the same discipline the live probes already use.

Measured on opencode 2.0.11 (2026-09-23, Claude Code 2.1.280)

Sandbox. ~/opencode-v2-sandbox. The binary is extracted from @opencode/cli-darwin-arm64@2.0.11 with no install scripts run (2.0.12 to 2.0.14 answer 403 on their tarballs even though latest says 2.0.14; that was Aikido Endpoint Protection's minimum-package-age policy on this machine, not npm, see AGENTS.md). env.sh redirects all four XDG dirs and TMPDIR. The plugin is loaded through work/.opencode/plugins/claude-code.js, a one-line re-export of this working tree's dist/. Always pass --standalone, or V2 starts its shared background service. V1 and V2 both read ~/.opencode/ as a config layer, so a plugin listed there is installed into the sandbox too (it fails harmlessly when it is a V1 plugin). The V1 regression probe runs the real 1.18.32 binary with a scratch XDG_CONFIG_HOME under /tmp/v1probe and asserts plugin ready exactly once.

The probes, answered.

  1. The model path works. AISDK.language never imports package. It checks the aisdk: prefix, gets the SDK object from the sdk hooks, then the model from the language hooks, falling back to sdk.languageModel(modelID ?? id). Our sdk hook returns createClaudeCode(settings) and a real turn streamed through it.
  2. Session affinity arrives as a header. callOptions forwards request.http.headers as the V3 headers, and session.hook("model.request") sets them. We set x-session-affinity (already what the language model reads) and x-opencode-agent, with kind: "compaction" | "title" mapped to those agent names.
  3. question exists with V1's exact input shape. todowrite does not, so the todo ledger's synthetic calls are dropped on V2.
  4. MCP tools in ctx.tool.list(): not measured yet.
  5. Permissions: a proxied shell ran under --auto. The interactive prompt is not measured yet.
  6. Running V2 without losing V1: done, above.

Things the plan did not predict.

  • A plugin's provider transform cannot see the config's provider settings. V2 applies the config file's provider block through its own opencode.config.provider plugin, after plugin transforms, so config overrides plugin defaults. accounts was absent from the seed record. v2.ts reads it from the same on-disk layers as the MCP bridge (opencodeConfigLayers) plus the V2-native plugin options. Per-call settings are unaffected: the sdk hook's options already hold the merged result.
  • opencode 1.18.32 calls a dual export's setup as well as server. A first build that set a process-wide "V2 mode" there made V1 emit shell and V1 rejected every tool call. The vocabulary is now carried per model (ClaudeCodeConfig.hostApi, set only by the V2 sdk hook), and setup registers nothing unless the context has the V2 provider, aisdk and session domains and no 1.x app.version.
  • V2 renamed tools and fields, and an unknown name is an error, not a harmless row. src/host-tools.ts rewrites the stream at its edge, on V2 only: bash to shell (no description), task to subagent (subagent_type to agent, task_id to sessionID), filePath to path for edit/write/read. It drops todowrite, plan_enter, plan_exit and notebookedit. Read off each tool's registered name and input schema in @opencode/core/dist/tool/plugin/*.js.
  • A configured plugin path must be a directory, and V2 resolves <dir>/server then <dir>/index, never package.json#main. An npm name resolves through exports, so published installs work. A local directory install needs a root entry file.
  • Found on the way, a V1 bug: overageStatus: "rejected" alone was treated as a rejection, so a served turn could end on the account-failover form. Fixed on master in 65379ea.

Live evidence, one build for both majors (branch v2-support):

Feature opencode 2.0.11 opencode 1.18.32
text turn, account providers yes yes
proxied tool runs in opencode shell completed bash completed
Claude-executed tool rendered read completed unchanged
subagent dispatch subagent to general, agent list offered unchanged
reasoning variant #low reached the CLI as effort=low unchanged
compaction lean path, summary kept the codeword unchanged
title request stub, one spawn per session unchanged
/claude-code-doctor report, no spawn unchanged
bundled skill listed by skill.list unchanged
/btw side question answered from the live session, no turn unchanged
deleted session released claude state for deleted session unchanged
local install plugins: ["<repo>/dist"] file:// as before

Not verified live on V2, each for a stated reason: account failover and the plan-mode form (a real usage limit and a headless ExitPlanMode cannot be produced on demand; both use V2's question tool, whose input matches V1's), permission prompts in the TUI (probes ran with --auto), and an npm-name install (needs a publish; it resolves through exports["."]).

Known V2 gaps, deliberate: /btw is answered after a running turn rather than inside it, and there is no todo panel because V2 has no todowrite. (2026-10-18: /btw now answers inside the running turn on V2 too, from the event stream; the remaining gaps are the todo panel, bridgeMcpOauthTokens, and the missing tool rows for Claude's EnterPlanMode, ExitPlanMode and NotebookEdit. See the 2026-10-18 section below.)

Measured on opencode 2.0.16 (2026-09-27, plugin 0.28.1, Claude Code 2.1.280)

Prompted by PR #46, whose reporter ran 2.0.16 while every check above ran on 2.0.11. The sandbox binary is now @opencode/cli-darwin-arm64@2.0.16 (tarball fetched with curl, shasum checked against the registry document; 2.0.11 kept as bin/opencode-2.0.11).

  • Plugin API drift, 2.0.11 to 2.0.16: diff -r over @opencode/plugin's dist finds one .d.ts change, readonly signal: AbortSignal added to the tool context in promise/tool.d.ts. Nothing this plugin uses moved. @ai-sdk/provider is still pinned at 3.0.8.
  • One run --standalone turn, plugins: ["<repo>/dist"]: a Claude-executed read rendered, a proxied shell ran in opencode, the reply quoted both results. Exactly one plugin ready block, no Tool result name changed (the 0.28.1 fix), no WARN except the Stripe MCP server needing auth.
  • Subagent dispatch: task reached opencode as subagent, the general agent answered, the parent quoted it.
  • npm-name install works, which closes the last item the 0.26.0 release left open: plugins: ["@khalilgharbaoui/opencode-claude-code-plugin@0.27.0"] resolved through exports["."] to dist/index.js, printed plugin ready and served a turn, with and without a provider.claude-code block. @0.28.1 still failed with NpmInstallFailedError from this Mac, where npm view lists nothing newer than 0.27.1: Aikido's minimum-package-age filter (AGENTS.md), not the package.
  • A probe mistake worth recording, so nobody re-diagnoses it as a bug: with no accounts configured the provider id is claude-code, so -m claude-code-default/<model> fails with Model unavailable while the plugin has loaded correctly and the ready block lists providers: ["claude-code"].

Still not verified on V2, for the same reasons as before: account failover and the plan-mode form (need a real usage limit and a headless ExitPlanMode), and permission prompts in the TUI (every probe ran with --auto).

Measured on opencode 2.0.16 (2026-09-30, plugin 0.32.0, Claude Code 2.1.280)

Background subagents, end to end. Sandbox as above, its own cwd work-v2bg, the plugin loaded from the v2-background worktree's dist, provider claude-code-appical, model claude-haiku-4-5@appical, always --standalone --auto.

  • The gate: background subagent gate {"supported":true,"registryResolved":true,"hostApi":"v2","note":"task accepts \background`; task_status and task_cancel are registered"}`.
  • Start: a background: true dispatch answered The subagent is working in the background (sessionID: ses_f0cb9005fffekrDPNa1Px8Jp0J). You will be notified automatically when it finishes. Prose, not XML: only a completed subagent call is wrapped in <subagent ...>.
  • task_status: <task id="ses_f0cb9005fffekrDPNa1Px8Jp0J" state="running">, with no run-state route involved (opencode 2 gives a plugin no session.active), so the answer came from the child's own transcript.
  • task_cancel: <task id="..." state="cancelled"> / Stopped. No completion notification will arrive for it., and cancelled background subagent {...,"wasRunning":true} in the log.
  • Collect once: a finished child collected as <task id="ses_f0cb60c51ffeiwoGyeGQHYGZAk" state="completed"><task_result>FAST_PROBE_DONE</task_result>, and the immediate second task_status answered Already delivered to this conversation earlier ... without repeating the output.
  • The parent guard: task_status and task_cancel on a session id that was not this conversation's child were both refused with is not a subagent of this conversation.
  • Completion delivery: opencode pushed <subagent sessionID="..." state="completed" description="..."> into the parent session as a synthetic message, which arrived as its own Claude turn.
  • /claude-code-doctor rendered its new Background subagents section. It read Not read yet this process, which is correct: opencode run --standalone is a fresh process per invocation and the doctor branch is answered before a turn plans its proxy tools. The populated rendering is covered by test/doctor.test.ts.

Two probe traps found here: opencode run --standalone ends its private server with the run, so a background child started in that run is interrupted rather than finishing (keep the turn alive with a proxied bash sleep if you need a completion inside one run); and opencode pair starts the background service as a side effect, which opencode service stop ends. opencode run --server <url> against a hand-started opencode serve was not made to work: it wants credentials the CLI would not take from the URL.

Measured on opencode 2.2.5 (2026-11-03 and 2026-11-04, plugin 0.67.1 and the compat/opencode-2-2 branch, Claude Code 2.1.314)

The full sweep is h #g287 in docs/agents-history.md. Headless: a text turn, a proxied shell with a CLI-native read, reuse, /compact, /claude-code-doctor and /btw during a running turn all pass. Interactive: the same plus two images, a 130-second proxied call kept in the foreground and the plan approval through the Form route all pass. The plugin API is additive from 2.1.2: SessionDomain still has list and no active.

  • provider.claude-code.options.transport breaks opencode 2's config load. With "interactive", "auto" or "headless" there, opencode models fails with UnexpectedStatus: 500 (measured on 2.1.4, 2.2.0 and 2.2.5; "http" loads). transport is opencode 2's own provider setting (http | websocket). providers.claude-code.settings.transport loads, but opencode logs it as a skipped malformed value and drops the block from its own view. Choose the transport with interactive: true (what every earlier V2 probe here used), the plugin tuple's options, or CLAUDE_CODE_INTERACTIVE_TRANSPORT=1.
  • The built-in Claude Agent provider (claude-agent, 2.2.3+) coexists. Its provider id, model ids (opus, sonnet, haiku, claude-fable-5-1[1m]) and /connect method (claude-login) clash with nothing of the plugin's (claude-code, claude-code-cli). Both answered in one opencode, and a session moved from one to the other replayed its thread as text, the expected path.

Measured on opencode 2.1.4: interrupts (2026-10-25, plugin 0.61.2, Claude Code 2.1.293)

After the maintainer reported that Esc Esc "still does nothing" (h #g267). A private serve and the real TUI driven by expect, scratch XDG dirs, haiku. Nothing in the plugin needed to change.

  • doStream gets no abortSignal at all on 2.1.4, on every call. A stop reaches the plugin only as a cancel of the stream it returned (stopOnCancel) or as session.execution.interrupted, and both work: a stop mid-reply interrupts the CLI within milliseconds, a stop at a parked proxied call releases it and interrupts the CLI, and a stop while a foreground subagent runs ends the parent and the child.
  • The TUI sends POST /api/session/{id}/interrupt?resume=true, resume as a QUERY parameter, and only on the second Esc. Its command is enabled only while it reads the session as running, with the prompt focused and no overlay open.
  • resume=true delivers what is queued at once: with a prompt waiting (delivery: "steer"), the interrupt ends the execution and a new one starts about 10 ms later with that prompt. On screen that reads as an interrupt that did nothing, while the plugin did stop the turn.
  • A rebuild is re-imported, but turns stay on the first copy (h #g268): a file:// install's rebuild is a new loading plugin within a second and the old setup is disposed, while every later turn still runs the first copy's language model. Before src/session-event-relay.ts, that cost the serving copy its event subscription, so a stop at a parked call after any rebuild did nothing in the plugin.
  • From h #g269 the newest copy takes over by itself at the first turn no older copy has work in flight, each conversation resuming its Claude session there (src/plugin-copies.ts). Measured on 2.1.4 across two rebuilds, one of them during a parked bash call, which its holder finished.
  • Probe trap: the plugin log ignores the scratch XDG dirs and writes to ~/.local/share/opencode-claude-code/plugin.log; opencode.log records event streams and non-2xx answers only, so a successful interrupt leaves no line there.

Measured on opencode 2.0.31 (2026-10-16, plugin 0.55.0, Claude Code 2.1.293)

Sandbox binary @opencode/cli-darwin-arm64@2.0.31 (tarball fetched with curl, sha1 checked against the registry document), kept as bin/opencode-2.0.31 beside 2.0.22. Plugin API drift 2.0.22 to 2.0.31 (diff -r over @opencode/plugin's declarations): additive only. The plugin context gains credential: Pick<CredentialApi, "activate">; the permission domain gains assert(input), which evaluates the session's rules and prompts when approval is needed; integrations gain an external method; vcs gains an optional init; the TUI DialogSelect gains actions and search; new runtime.d.ts and runtime-modules.d.ts. session.d.ts is unchanged, so the SessionDomain Pick still has no active. The MCP status vocabulary is identical. Live with the local dist, opencode run --standalone from a subdirectory of a scratch repository: the session's own cwd (issue #113), a proxied shell, a CLI-native read. Details in AGENTS.md history (h #g240).

Measured on opencode 2.0.31 and 2.0.22 (2026-10-18, plugin 0.58.0 and the v2-parity branch, Claude Code 2.1.293)

The parity audit (h #g253). Private serves under scratch XDG dirs, a throwaway observer plugin that recorded every event its ctx.event.subscribe() received and emitted an RPC ping every 4 s, and the real claude on haiku. The newer API is 2.0.32 on npm, which could not be read from this Mac (Aikido's minimum-age filter blocked its tarball); 2.0.31's @opencode/plugin and @opencode/client were.

  • Run state is in the event stream, not where the types say. Every turn is bracketed by session.execution.started and succeeded / interrupted (reason: "user"), agreeing to the millisecond with GET /api/session/active through a 15 s permission hold and an 8 s tool run. session.status and session.idle are declared in the client types and were emitted zero times. Same on 2.0.22.
  • Nothing aborts the provider stream at a tool boundary, including an operator's interrupt during a parked proxied call: the plugin saw no abort at all, and the parked call stayed pending until the server exited.
  • A command's execute runs the moment it is issued, busy or not (delivery: "steer" either way). It must return a promise: one that returned nothing answered the HTTP call with a 500.
  • RPC events work end to end. Every events.emit appeared on the bus as rpc.<id>.<event>; a sidebar half's data.listen received them and ui.toast.show rendered them (TUI on 2.0.31; bus only on 2.0.22). The credential domain is activate only, so a stored MCP token cannot be read.
  • setup runs once per location in one process: in the TUI, for the project directory and the home directory, so every registration exists twice.
  • The A/B, new build against v0.58.0, same config: a proxied write with a 5 s deadline held 15 s at a permission prompt was kept and written (v0.58.0 timed it out twice); a stop during a parked sleep 30 released the call and interrupted the CLI at once (v0.58.0 did nothing); /btw sent mid-turn landed its receipt and answer inside the running turn with no /btw message (v0.58.0 queued one); a warning reached the bus and, in a --standalone TUI, rendered as a claude-code toast (v0.58.0 showed nothing).
  • Probe trap: the TUI without --standalone started the background service (serve --service, reparented to init) under the scratch dirs; opencode service stop with the same environment ended it.

Measured on opencode 2.0.22 (2026-10-03, plugin 0.36.4, Claude Code 2.1.286)

The compatibility sweep. Full evidence, including the CLI schema diff and the Claude Code side, is in docs/agents-history.md (h #g191).

Sandbox. ~/opencode-v2-sandbox as before. The binary is now @opencode/cli-darwin-arm64@2.0.22 (tarball fetched with curl, sha1 cb4602cdcaaaba8005702af7e4a26629645439c2, checked against the registry's single-version document because Aikido's minimum-package-age policy rewrites the packument on this machine; 2.0.21 is blocked outright). bin/opencode-2.0.16 and bin/opencode-2.0.11 are kept beside it. Its own cwd is work-compat, the plugin loaded from this worktree's dist, no accounts (so the provider id is claude-code and the model claude-code/claude-haiku-4-5), cliPath pointing at an unpacked Claude Code 2.1.286 under /tmp, and always --standalone --auto.

  • Plugin API drift, 2.0.16 to 2.0.22: diff -r over @opencode/plugin's dist finds three additive changes. SessionDomain's Pick gained remove and compact; integration.connection.status was added; the TUI context gained a model accessor with variant selection. Nothing this plugin uses moved, and session.active is still not in the Pick, so the shim's limits recorded above still hold. @opencode/schema's config/mcp and mcp are byte-identical from 2.0.16 to 2.0.20 (its 2.0.21 and 2.0.22 are blocked here), so the mcp.servers reading is current.
  • Passing live: a text turn (V2TEXTOK, exactly one plugin ready, opencode: 2.0.22); a Claude-executed read; a proxied shell; the MCP bridge against a real local stdio server (cbm, the maintainer's codebase-memory-mcp, read-only); a subagent dispatch (V2SUBOK); two prompts in one session, the second recalling the first's codeword through the history-replay path; /claude-code-doctor; and /claude-code-doctor bundle (12.2 KB, home path rewritten to ~, session ids hashed, no key, bearer or prompt text anywhere in it).
  • Two defects found here, both fixed in this lane and both host-agnostic. A CLI-executed tool call could end a step without a result, which opencode 2.0.22 reports as Provider did not return a tool result while opencode 1.18.34 silently leaves the row pending (h #g190). And what a reused child wrote between turns was replayed as bare text at the top of the next reply (h #g189). Both were reproduced on 2.0.22 and verified fixed on it.
  • The interactive transport (2026-10-05, Claude Code 2.1.288): with settings.interactive: true, a text turn (V2ALPHA) and a CLI-executed Bash turn both ran over the PTY, the folder trust dialog accepted on the way. So Bun.Terminal exists in V2's serve --stdio plugin process and the transport does not fall back to headless here (h #g196). run prints the CLI-executed tool's output as a raw {"output":...} object, and does the same for the identical turn headless.
  • Not re-run on 2.0.22: the npm-name install, measured on 2.0.16 above; the gate was re-read live here and still reports {"supported":true,"hostApi":"v2"}. The background-subagent triple was left for later and re-run in full on 2026-10-08, see the section below.
  • --resume across a restart, measured 2026-10-05 (h #g197): every run --standalone is a new plugin process, so run --standalone -c is exactly an opencode restart. With resumeAfterRestart (default on) the second run logged resuming the claude session from before the restart and recalled the first run's codeword (HERON) without a replay. The paragraph below predates that.
  • Formerly not measurable on V2: --resume. A V2 plugin keeps no claude process across run --standalone invocations, and a persistent V2 server is out of bounds here (opencode service start may register a login item, and run --server was never made to work). The --resume path is host-agnostic, lives in buildCliArgs, and was verified on opencode 1.18.34 by letting idleProcessTimeoutMs evict the process between two prompts.

Measured on opencode 2.0.22 (2026-10-07, plugin 0.46.1, Claude Code 2.1.288)

The three checks that had been open since 2026-09-23 because each needs an answer posted back into a running turn. Full evidence in docs/agents-history.md (h #g219).

Sandbox. ~/opencode-v2-sandbox/bin/opencode as before, but a private serve rather than run --standalone, because a form and a permission both have to be answered while the turn is still going. Port 4781x on 127.0.0.1, OPENCODE_SERVER_PASSWORD set and HTTP Basic opencode:<password> on every call, routes under /api/..., the OpenAPI document at /openapi.json. Each probe got its own scratch XDG_CONFIG_HOME/DATA/CACHE/STATE, its own TMPDIR and its own cwd, the plugin loaded from a worktree's dist, and plugin ready asserted to appear exactly once. Never opencode service start, never opencode pair.

  • The account-switch form, and the switch (PASS). accountFailover: "ask", accounts: ["alpha"], cliPath a scratch fake claude that answers --version with 2.1.288, emits a limited turn (rate_limit_event, a <synthetic> assistant frame with error: "rate_limit" and is_api_error_message: true, then a result with subtype: "success" and is_error: true) when reached through a wrapper, and plain text when reached as the bare binary. The form arrived at GET /api/session/{id}/form as a Form with metadata.kind: "question", one string field with default and stop options and the reset time in its description. Answering it with POST .../form/{formID}/reply {"answer":{"q0":"default"}} (204) wrote the tool result back as V1's own sentence, User has answered your questions: "<question>"="default"., so unwrapOpencodeQuestionResult needed no V2 branch. The next spawn ran the bare fake with CLAUDE_CONFIG_DIR unset and --model claude-haiku-4-5 with the @alpha marker stripped, and the turn carried the ▌ **account failover:** note.
  • The plan-mode approval form on the interactive transport (PASS). interactive: true, permissionMode: "plan", planModeQuestion: true, the real claude on the default account, haiku. The TUI parked 2.1.288's three-choice approval dialog (interactive transport is waiting on a plan approval), the plugin raised the Plan approval form, yes through the same Form route produced interactive transport answering a plan approval {approved: true}, and the SAME TUI turn wrote the file and ended on end_turn.
  • A permission prompt in front of a proxied call (PASS). Every earlier V2 probe ran with --auto, so this path had never been exercised. With permissions: [{action: "write"|"edit", resource: "*", effect: "ask"}] in the config, a proxied write was queued and the step drained, opencode raised a request at GET /api/session/{id}/permission, the call sat parked, and POST .../permission/{requestID}/reply {"decision":"once"} resolved it inside the same step (resolved pending proxy call). The file was written.

Two probe traps found here.

  • POST /api/session/{id}/prompt takes {text} only and returns as soon as the message is recorded. The model is chosen separately with POST /api/session/{id}/model ({"model":{"providerID":...,"id":...}}), and a driver that waits on the prompt call sees neither the form nor the permission, because both appear after it has already returned. Poll GET /api/session/active for busy instead.
  • A provider's package is not only a label on 2.0.22. opencode npm-installs the name inside V2_PLUGIN_PACKAGE's aisdk: prefix when the model is first asked for, and calls that copy's provider factory beside the configured one. With a local dist plugin the npm copy resolved to 0.40.0 here (Aikido's minimum-package-age filter) and wrote 0.40.0's plan-mode WARN into the same plugin.log, a line the current source cannot produce. It serves nothing (the sdk hook replaces event.sdk, and the turn ran on the local build) and plugin ready still appears once, because setup() runs only for the configured plugin. Read a V2 probe's log knowing two builds write to it.

Measured on opencode 2.0.22 (2026-10-08, plugin 0.53.0, scripted fake claude)

The three features shipped in v0.51.0 to v0.53.0 that had been run live on opencode 1.18.35 only. Full evidence in docs/agents-history.md (h #g229).

Sandbox. The same private serve recipe as the 2026-10-07 run above, on ports 4783x, with its own scratch HOME, all four XDG dirs and TMPDIR, three cwds (one per feature), the plugin loaded from a worktree's dist, and cliPath pointing at a scripted fake claude that answers --version with 2.1.293, records every spawn's argv / CLAUDE_CONFIG_DIR / effort, writes a real transcript JSONL where Claude Code writes one, and calls the proxy MCP server with a two-task task_batch when asked to. Nothing was billed. The second account is a scratch config dir under the scratch HOME (~/.claude-alpha), so the provider ids are claude-code-default and claude-code-alpha.

  • The by-hand account carry (PASS). One opencode session, a turn on claude-code-default then a turn on claude-code-alpha/claude-haiku-4-5@alpha. The second spawn ran with CLAUDE_CONFIG_DIR=<scratch>/.claude-alpha and --resume <the default account's session id>, the transcript was in alpha's own projects/<encoded cwd>/ at 0600, the source was left where it was, and the envelope carried only the new message. Switching back resumed again under a FRESH uuid, because the default's own path still held the stale original, and the file that came home was alpha's longer copy (the size rule, h #g218). Both turns logged continuing this conversation's claude session under the new model or effort instead of replaying it with from and account set.
  • accountGroups (PASS). The same switch with {"alpha": "work"}: no --resume, no transcript copied (alpha wrote a new session of its own), an envelope holding only the latest message and nothing of the first turn, the ▌ **account group:** note as its own text part naming both accounts and both groups, and one NOTICE, starting fresh on this account: it is in another account group {reason: "another-account-group", account: "alpha", from: "default", group: "work"}. The ready block printed the resolved accountGroups: ["alpha=work"].
  • subagentDispatch: "ask" (PASS after one fix). A task_batch with an implementor and a designer raised the one-question form at GET /api/session/{id}/form as a Form with metadata.kind: "question"; Customise…, then the per-type form (one field per agent type plus an Account row offering default, alpha, Per type…), then the per-type account form, each answered 204 by POST .../form/{formID}/reply {"answer":{"q0":…,"q1":…,"q2":…}}. The children then spawned as claude-opus-5-5 / CLAUDE_CODE_EFFORT_LEVEL=high / ~/.claude-alpha and claude-haiku-5-5 / low / the default dir. Same as last time reproduced both on a second dispatch, and still did after the serve was stopped and restarted on the same opencode session, from the store under the scratch XDG_STATE_HOME.

The one defect, and it was V2-only. opencode 2's own subagent tool prompts a child with ["You are a subagent spawned by another session.", prompt].join("\n") rather than the prompt verbatim, which is what 1.18.35 sends and what the claim key was built on (h #g227). So no child matched its claim and every one of them ran the defaults, silently, after the operator had answered three screens saying otherwise. Fixed in promptMatchesClaim; see (h #g229).

Two probe traps found here.

  • GET /api/model and GET /api/provider answer {data: []} for a provider a plugin registers, even while turns on it run fine, so a driver has to name claude-code-<account>/<model> itself.
  • GET /api/session/{id}/form is {data: [Form]} whose fields[] carry options[].label, not a JSON Schema, and the same form keeps being returned until the reply lands, so a driver must track which ids it has answered. A reply to a form id it has not read yet is a 400 naming frm_.

Measured on opencode 2.0.22 (2026-10-08, plugin 0.53.1, scripted fake claude)

Background subagents end to end, which had only ever been run on 2.0.16 (the section above). Full evidence in docs/agents-history.md (h #g230).

Sandbox. The private serve recipe of the two sections above, on ports 4785x, with its own scratch HOME, all four XDG dirs and TMPDIR, two cwds, the plugin loaded from a worktree's dist, and cliPath pointing at a scripted fake claude that answers --version with 2.1.293, records every spawn's argv / CLAUDE_CONFIG_DIR / effort, reads the proxy MCP server's url and bearer out of its own --mcp-config, and runs a per-turn script of tools/list and tools/call requests against it. A turn's prompt names the script ([[CLI:<name>]]), and because that marker survives into a child session's prompt the one binary plays the parent and every subagent. Nothing was billed.

  • The gate (PASS). background subagent gate {"supported":true,"registryResolved":true,"hostApi":"v2","note":"task accepts \background`; task_status and task_cancel are registered"}, and the proxy's own tools/listreturned exactly["task","task_batch","task_status","task_cancel"]withTASK_BACKGROUND_NOTE_V2ending thetask` description.
  • A background dispatch and its push (PASS). background: true answered in 133 ms with The subagent is working in the background (sessionID: ses_...). You will be notified automatically when it finishes. The completion arrived in the parent as a synthetic message, <subagent sessionID="..." state="completed" description="fast probe">, and ran as its own Claude turn. A cancel pushes one too, state="cancelled".
  • task_status (PASS). Running in 3 ms off the child's own transcript (V2 still exposes no session.active); finished, the result once, then Already delivered to this conversation earlier ... without repeating it.
  • task_cancel (PASS). Stopped. plus cancelled background subagent {...,"wasRunning":true} on a running child, and on an already finished one Could not cancel background task ...: opencode did not accept the abort, so V2's session.interrupt does answer {interrupted: false} and Stopped. is gated on a true interrupt here. task_status and task_cancel naming a second top-level session were both refused with is not a subagent of this conversation.
  • subagentDispatch: "ask" over a background dispatch (PASS). The form arrived at GET /api/session/{id}/form, Customise… opened the per-type screen, and the background child spawned with --model claude-opus-5-5, CLAUDE_CODE_EFFORT_LEVEL=high and CLAUDE_CONFIG_DIR=<scratch>/.claude-alpha (subagent dispatch choice claimed by its child session). The background behaviour was unchanged by the form.
  • /claude-code-doctor (PASS). The Background subagents section read yes / registered / v2 / opencode 2 offers background unconditionally, so the registry is not consulted, with one ledger row naming the collected child and the cancelled one.

The one defect, host-specific and quiet. Two strings still described opencode 1's envelope to a V2 model: the background input field's own description (<task id="..." state="running">, read off the live schema) and BACKGROUND_SUBAGENT_HINT, the system-prompt block, read off the spawn's own --append-system-prompt-file. Neither breaks a dispatch; both cost the recovery path, because a model that believes them has no id to pass to task_status or task_cancel. Fixed, with the field naming both majors and the hint gaining a V2 twin; see (h #g230).

Phases

Phase 0, probes. Answer the six questions above with throwaway plugins against a sandboxed V2. No changes to this package. Write findings back into this file. Stop here and re-plan if question 1 comes back negative, because that answer changes the architecture rather than the schedule.

Phase 1, separate the transport from the V1 glue. Nothing under the CLI transport should know what an opencode plugin API looks like. Today src/opencode-types.ts is a hand-written mirror of V1's types and the V1 wiring lives in src/index.ts. Target: index.ts becomes a thin dual entrypoint, v1.ts holds today's server(), v2.ts holds setup(), and everything else is shared and API-agnostic. This phase ships on its own with zero behaviour change and the full suite green.

Phase 2, V2 entrypoint, feature by feature. Order by dependency: provider and models first (nothing works without a model), then commands, then MCP, then skills, then the question-dependent features (failover, plan mode) once probe 3 has an answer. V1 stays the default and stays untouched.

Phase 3, parity and release. A parity checklist per feature with its V2 evidence, the README and the bundled skill updated to say which opencode majors are supported, and a minor release. Support both until the maintainer's own opencode is on 2.x and has stayed there.

Rules for this lane

  • V1 may not regress. 660 tests green at every step, and no V1 behaviour changed because V2 would prefer it differently.
  • Every V2 claim gets a measurement, the same standard the rest of AGENTS.md holds. The website's provider documentation would have sent this lane down a rewrite; the shipped .d.ts did not. Read the package.
  • Do not convert the maintainer's own opencode config to native V2 shape yet. V1 and V2 read the same paths, and the migration guide warns against pointing V1 at converted files.
  • Do not install V2 over the working V1 until the port runs, because the installer replaces the binary and there is no plugin on the other side yet.

Test strategy

The suite drives V1 by calling server(input) with a fake plugin input. V2 needs the same treatment: a fake Context with the domains we touch, so setup(ctx) can be asserted offline exactly as the V1 hooks are. Shared code keeps its existing tests. The probes in phase 0 are live and paid, and stay out of npm test.