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.
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.
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.
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:
@opencode/plugin@2.0.11depends on@ai-sdk/providerat 3.0.8. This package already depends on^3.0.8and has 3.0.10 installed.ClaudeCodeLanguageModel.specificationVersionis 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.
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.
| 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.
Each is cheap, each is a measurement rather than a reasoning step, and none needs product code.
- Does an unresolvable
packagestill reachaisdk.hook("language")? Register a provider with a nonsense package, hook bothsdkandlanguage, log what arrives. If it does not, the answer is to supply thesdkobject from thesdkhook too. Everything else in this plan depends on this one. - How does the model learn which session it is serving? V1 reads the
x-session-affinityrequest header, and session affinity is the key to process reuse, proxy call routing and the todo ledger. Check what V2 passes intodoStream; if it passes nothing,ctx.session.hook("context")knows thesessionIDand can stash it. - Is there a native
questiontool in V2? Account failover and the plan-mode bridge both end a turn on a syntheticquestiontool-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. - Do MCP tools appear in
ctx.tool.list()? If yes,resolveMcpProxyToolDefsgets simpler and thedoStreamtoolsargument read can go. - Does the proxy still get permission prompts? V2 renamed permission actions
(
bashtoshell,tasktosubagent,write/patchtoedit) 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. - How do we run V2 at all without losing V1? The installer replaces the V1 binary
and both use the
opencodecommand. Testing needs a pinned V2 binary in an isolated path with its ownXDG_CONFIG_HOME, the same discipline the live probes already use.
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.
- The model path works.
AISDK.languagenever importspackage. It checks theaisdk:prefix, gets the SDK object from thesdkhooks, then the model from thelanguagehooks, falling back tosdk.languageModel(modelID ?? id). Oursdkhook returnscreateClaudeCode(settings)and a real turn streamed through it. - Session affinity arrives as a header.
callOptionsforwardsrequest.http.headersas the V3headers, andsession.hook("model.request")sets them. We setx-session-affinity(already what the language model reads) andx-opencode-agent, withkind: "compaction" | "title"mapped to those agent names. questionexists with V1's exact input shape.todowritedoes not, so the todo ledger's synthetic calls are dropped on V2.- MCP tools in
ctx.tool.list(): not measured yet. - Permissions: a proxied
shellran under--auto. The interactive prompt is not measured yet. - 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.providerplugin, after plugin transforms, so config overrides plugin defaults.accountswas absent from the seed record.v2.tsreads it from the same on-disk layers as the MCP bridge (opencodeConfigLayers) plus the V2-native pluginoptions. Per-call settings are unaffected: thesdkhook'soptionsalready hold the merged result. - opencode 1.18.32 calls a dual export's
setupas well asserver. A first build that set a process-wide "V2 mode" there made V1 emitshelland V1 rejected every tool call. The vocabulary is now carried per model (ClaudeCodeConfig.hostApi, set only by the V2sdkhook), andsetupregisters nothing unless the context has the V2provider,aisdkandsessiondomains and no 1.xapp.version. - V2 renamed tools and fields, and an unknown name is an error, not a harmless row.
src/host-tools.tsrewrites the stream at its edge, on V2 only:bashtoshell(nodescription),tasktosubagent(subagent_typetoagent,task_idtosessionID),filePathtopathforedit/write/read. It dropstodowrite,plan_enter,plan_exitandnotebookedit. Read off each tool's registerednameand input schema in@opencode/core/dist/tool/plugin/*.js. - A configured plugin path must be a directory, and V2 resolves
<dir>/serverthen<dir>/index, neverpackage.json#main. An npm name resolves throughexports, 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 in65379ea.
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.)
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 -rover@opencode/plugin'sdistfinds one.d.tschange,readonly signal: AbortSignaladded to the tool context inpromise/tool.d.ts. Nothing this plugin uses moved.@ai-sdk/provideris still pinned at 3.0.8. - One
run --standaloneturn,plugins: ["<repo>/dist"]: a Claude-executedreadrendered, a proxiedshellran in opencode, the reply quoted both results. Exactly oneplugin readyblock, noTool result name changed(the 0.28.1 fix), no WARN except the Stripe MCP server needing auth. - Subagent dispatch:
taskreached opencode assubagent, thegeneralagent 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 throughexports["."]todist/index.js, printedplugin readyand served a turn, with and without aprovider.claude-codeblock.@0.28.1still failed withNpmInstallFailedErrorfrom this Mac, wherenpm viewlists 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
accountsconfigured the provider id isclaude-code, so-m claude-code-default/<model>fails withModel unavailablewhile the plugin has loaded correctly and the ready block listsproviders: ["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).
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: truedispatch answeredThe 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 nosession.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., andcancelled 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 secondtask_statusansweredAlready delivered to this conversation earlier ...without repeating the output. - The parent guard:
task_statusandtask_cancelon a session id that was not this conversation's child were both refused withis 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-doctorrendered its new Background subagents section. It readNot read yet this process, which is correct:opencode run --standaloneis a fresh process per invocation and the doctor branch is answered before a turn plans its proxy tools. The populated rendering is covered bytest/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.transportbreaks opencode 2's config load. With"interactive","auto"or"headless"there,opencode modelsfails withUnexpectedStatus: 500(measured on 2.1.4, 2.2.0 and 2.2.5;"http"loads).transportis opencode 2's own provider setting (http | websocket).providers.claude-code.settings.transportloads, but opencode logs it as a skipped malformed value and drops the block from its own view. Choose the transport withinteractive: true(what every earlier V2 probe here used), theplugintuple's options, orCLAUDE_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/connectmethod (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.
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.
doStreamgets noabortSignalat all on 2.1.4, on every call. A stop reaches the plugin only as a cancel of the stream it returned (stopOnCancel) or assession.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,resumeas a QUERY parameter, and only on the second Esc. Its command is enabled only while it reads the session asrunning, with the prompt focused and no overlay open. resume=truedelivers 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 newloading pluginwithin a second and the old setup is disposed, while every later turn still runs the first copy's language model. Beforesrc/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 parkedbashcall, 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.logrecords event streams and non-2xx answers only, so a successful interrupt leaves no line there.
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.startedandsucceeded/interrupted(reason: "user"), agreeing to the millisecond withGET /api/session/activethrough a 15 s permission hold and an 8 s tool run.session.statusandsession.idleare 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
executeruns 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.emitappeared on the bus asrpc.<id>.<event>; a sidebar half'sdata.listenreceived them andui.toast.showrendered them (TUI on 2.0.31; bus only on 2.0.22). Thecredentialdomain isactivateonly, so a stored MCP token cannot be read. setupruns 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
writewith 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 parkedsleep 30released the call and interrupted the CLI at once (v0.58.0 did nothing);/btwsent mid-turn landed its receipt and answer inside the running turn with no/btwmessage (v0.58.0 queued one); a warning reached the bus and, in a--standaloneTUI, rendered as aclaude-codetoast (v0.58.0 showed nothing). - Probe trap: the TUI without
--standalonestarted the background service (serve --service, reparented to init) under the scratch dirs;opencode service stopwith the same environment ended it.
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 -rover@opencode/plugin'sdistfinds three additive changes.SessionDomain'sPickgainedremoveandcompact;integration.connection.statuswas added; the TUI context gained amodelaccessor with variant selection. Nothing this plugin uses moved, andsession.activeis still not in thePick, so the shim's limits recorded above still hold.@opencode/schema'sconfig/mcpandmcpare byte-identical from 2.0.16 to 2.0.20 (its 2.0.21 and 2.0.22 are blocked here), so themcp.serversreading is current. - Passing live: a text turn (
V2TEXTOK, exactly oneplugin ready,opencode: 2.0.22); a Claude-executedread; a proxiedshell; the MCP bridge against a real local stdio server (cbm, the maintainer'scodebase-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 resultwhile 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-executedBashturn both ran over the PTY, the folder trust dialog accepted on the way. SoBun.Terminalexists in V2'sserve --stdioplugin process and the transport does not fall back to headless here (h #g196).runprints 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. --resumeacross a restart, measured 2026-10-05 (h #g197): everyrun --standaloneis a new plugin process, sorun --standalone -cis exactly an opencode restart. WithresumeAfterRestart(default on) the second run loggedresuming the claude session from before the restartand 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 noclaudeprocess acrossrun --standaloneinvocations, and a persistent V2 server is out of bounds here (opencode service startmay register a login item, andrun --serverwas never made to work). The--resumepath is host-agnostic, lives inbuildCliArgs, and was verified on opencode 1.18.34 by lettingidleProcessTimeoutMsevict the process between two prompts.
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"],cliPatha scratch fakeclaudethat answers--versionwith 2.1.288, emits a limited turn (rate_limit_event, a<synthetic>assistant frame witherror: "rate_limit"andis_api_error_message: true, then aresultwithsubtype: "success"andis_error: true) when reached through a wrapper, and plain text when reached as the bare binary. The form arrived atGET /api/session/{id}/formas aFormwithmetadata.kind: "question", onestringfield withdefaultandstopoptions and the reset time in its description. Answering it withPOST .../form/{formID}/reply {"answer":{"q0":"default"}}(204) wrote the tool result back as V1's own sentence,User has answered your questions: "<question>"="default"., sounwrapOpencodeQuestionResultneeded no V2 branch. The next spawn ran the bare fake withCLAUDE_CONFIG_DIRunset and--model claude-haiku-4-5with the@alphamarker 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 realclaudeon 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 thePlan approvalform,yesthrough the sameFormroute producedinteractive transport answering a plan approval {approved: true}, and the SAME TUI turn wrote the file and ended onend_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. Withpermissions: [{action: "write"|"edit", resource: "*", effect: "ask"}]in the config, a proxiedwritewas queued and the step drained, opencode raised a request atGET /api/session/{id}/permission, the call sat parked, andPOST .../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}/prompttakes{text}only and returns as soon as the message is recorded. The model is chosen separately withPOST /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. PollGET /api/session/activefor busy instead.- A provider's
packageis not only a label on 2.0.22. opencode npm-installs the name insideV2_PLUGIN_PACKAGE'saisdk:prefix when the model is first asked for, and calls that copy's provider factory beside the configured one. With a localdistplugin 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 sameplugin.log, a line the current source cannot produce. It serves nothing (thesdkhook replacesevent.sdk, and the turn ran on the local build) andplugin readystill appears once, becausesetup()runs only for the configured plugin. Read a V2 probe's log knowing two builds write to it.
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-defaultthen a turn onclaude-code-alpha/claude-haiku-4-5@alpha. The second spawn ran withCLAUDE_CONFIG_DIR=<scratch>/.claude-alphaand--resume <the default account's session id>, the transcript was in alpha's ownprojects/<encoded cwd>/at0600, 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 loggedcontinuing this conversation's claude session under the new model or effort instead of replaying itwithfromandaccountset. 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 resolvedaccountGroups: ["alpha=work"].subagentDispatch: "ask"(PASS after one fix). Atask_batchwith animplementorand adesignerraised the one-question form atGET /api/session/{id}/formas aFormwithmetadata.kind: "question";Customise…, then the per-type form (one field per agent type plus anAccountrow offeringdefault,alpha,Per type…), then the per-type account form, each answered 204 byPOST .../form/{formID}/reply {"answer":{"q0":…,"q1":…,"q2":…}}. The children then spawned asclaude-opus-5-5/CLAUDE_CODE_EFFORT_LEVEL=high/~/.claude-alphaandclaude-haiku-5-5/low/ the default dir.Same as last timereproduced both on a second dispatch, and still did after theservewas stopped and restarted on the same opencode session, from the store under the scratchXDG_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/modelandGET /api/provideranswer{data: []}for a provider a plugin registers, even while turns on it run fine, so a driver has to nameclaude-code-<account>/<model>itself.GET /api/session/{id}/formis{data: [Form]}whosefields[]carryoptions[].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 namingfrm_.
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 owntools/listreturned exactly["task","task_batch","task_status","task_cancel"]withTASK_BACKGROUND_NOTE_V2ending thetask` description. - A background dispatch and its push (PASS).
background: trueanswered in 133 ms withThe subagent is working in the background (sessionID: ses_...). You will be notified automatically when it finishes.The completion arrived in the parent as asyntheticmessage,<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 nosession.active); finished, the result once, thenAlready delivered to this conversation earlier ...without repeating it.task_cancel(PASS).Stopped.pluscancelled background subagent {...,"wasRunning":true}on a running child, and on an already finished oneCould not cancel background task ...: opencode did not accept the abort, so V2'ssession.interruptdoes answer{interrupted: false}andStopped.is gated on a true interrupt here.task_statusandtask_cancelnaming a second top-level session were both refused withis not a subagent of this conversation.subagentDispatch: "ask"over a background dispatch (PASS). The form arrived atGET /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=highandCLAUDE_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 readyes/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).
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.
- 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.tsdid 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.
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.