Skip to content

feat(opencode): support OpenCode 2 alongside OpenCode 1 - #211

Merged
bilersan merged 11 commits into
ActiveMemory:mainfrom
omergk28:feat/opencode-v2-compat
Dec 4, 2026
Merged

bilersan merged 11 commits into
ActiveMemory:mainfrom
omergk28:feat/opencode-v2-compat

Conversation

@omergk28

@omergk28 omergk28 commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

feat(opencode): support OpenCode 2 alongside OpenCode 1

Branch: feat/opencode-v2-compat → main
Commits: 8a6ff9d5, a2086d3d, f9fef40b; first review round 9bfcc462, 2f94a1b1, 9dfab21a; second review round 1638b31d, ca6ac3f8, 7b20045e, f346e89d · Spec: specs/opencode-v2-compat.md

Closes #210

What

OpenCode 2 refuses to load OpenCode 1 plugins, so a stock ctx setup opencode --write left OpenCode 2 with no lifecycle hooks. Setup now picks an OpenCode generation and deploys the matching plugin. OpenCode 1 behavior is unchanged.

OpenCode 1 OpenCode 2
Plugin existing plugin, untouched new plugin-v2/index.ts, same deploy path
MCP entry mcp.ctx, "enabled": true the same entry; OpenCode 2 reads it too
Context across compaction re-added on every compaction written once per session as an instruction entry; no compaction hook
Skills, AGENTS.md same same

Choosing the generation, in order: CTX_OPENCODE_MAJOR (1 or 2); opencode --version; an OpenCode 2 plugin an earlier run deployed in the project; OpenCode 1. Setup prints which one and how, so a fallback never reads as a detection, and when opencode --version itself failed it prints that error first.

Why two plugins and not one dual-export plugin: OpenCode 1.x only accepts the object entrypoint from 1.18.29, so a shared file would break every older 1.x install.

The OpenCode 2 plugin

  • Compaction. The 1.x plugin re-runs ctx system bootstrap on every compaction and hopes the summary keeps it. OpenCode 2 has session instruction entries, which it keeps across compaction and forks itself. The plugin writes the bootstrap output once per session under the key ctx and runs nothing when a session compacts. Cost: about 200 tokens stand in the session's instructions on every request; that part of the prompt is stable, so caching providers bill it at the cached rate.
  • Session start uses the prompt hook, not session.created. Two OpenCode 2 behaviors, both observed live, rule the event out: the event stream is server-wide (project A's plugin receives project B's sessions), and plugins load lazily, so the first session after a load never delivers the event.
  • Hook calls carry the hook-JSON envelope on stdin, the same shape the Pi extension sends. Without it ctx system post-commit does nothing.
  • post-commit runs only when the shell call exited 0. OpenCode 2 reports a non-zero shell exit as a completed tool call, so the plugin reads result.output.exitCode.

MCP config. One shape for both generations: the legacy mcp.ctx entry. Both read the same global file, and OpenCode 1 before 1.18.24 rejects the whole config once OpenCode 2's mcp.servers container exists (confirmed live on 1.18.18; 1.18.33 accepts it), so setup never creates it. If the user already has mcp.servers.ctx, setup removes it and says so: mcp.ctx serves both generations, and OpenCode 1.18.24+ logs a conflict for the pair on every config load even when the two agree. A container left empty by the removal goes too. A rewrite keeps the file's permissions.

Gate. tools/typecheck/opencode-v2 and a new CI job typecheck the plugin against a pinned @opencode/plugin 2.4.3, next to the existing OpenCode 1 gate.

Verification

  • make audit passes: lint, all skill-tree sync checks, full test suite.
  • New Go tests: version parsing and resolution (including preview stamps and a version printed before an error), the keep-existing fallback, the line setup prints for each way of choosing, plugin upgrade in place, the MCP merge (no native container, a duplicate native ctx entry removed and reported, an emptied container removed, other servers preserved, a legacy server named servers, file mode kept), the probe-error line, session-id fallback, and the prune matcher.
  • Live, OpenCode 2.4.3, with a logging ctx shim recording each call's cwd, arguments and stdin:
    • setup detected 2.x and wrote mcp.ctx; OpenCode 2 loaded the plugin (ID ctx), connected MCP and loaded all 50 skills; OpenCode 1.18.18 connected from the same config file
    • first session after a service restart: one system bootstrap, the ctx instruction entry listed by the API
    • one session with a failing git commit, a file write, then a successful commit: no call for the failed commit, check-task-completion after the write, post-commit with the commit command in its envelope, both checks on idle
    • compaction: no ctx call; the entry was still listed and the model quoted its context_dir line without a tool
    • a session in a second project caused no ctx call from the first project and got no entry
    • after another restart, re-writing the same value added no "instructions updated" notice
    • ctx hook pause run from the agent's shell wrote its marker under the real session id; a subagent caused no bootstrap, warm-up or idle check of its own
  • Live, OpenCode 1.18.18: setup detected 1.x, wrote the same mcp.ctx entry, deployed the 1.x plugin; OpenCode 1 connected the MCP server. A config holding only mcp.servers.ctx made it fail with "Configuration is invalid".
  • Live, OpenCode 1.18.33 (installed for the second review round): a config holding only mcp.servers.ctx loads and resolves to mcp.ctx; mcp.ctx beside mcp.servers.ctx logs "configuration compatibility diagnostic"; the config setup leaves after removing the duplicate loads with no diagnostic.
  • Live, Windows 11, OpenCode 2.4.3: bilersan's run, in the conversation below. It covers detection, the MCP entry, every hook, pause, subagents, and console windows with and without windowsHide.
  • Not verified live: preview-build version stamps, backgrounded shell calls, pwsh 7 as the agent's shell on Windows.

Details and re-verification notes are in the spec's Verification section.

Notes

  • Reviewed before opening. Two independent review passes ran over the change. The first found three real bugs that live testing then confirmed, all fixed here: cross-project session.created delivery, post-commit firing after a failed commit, and the missing hook envelope.
  • Known limit: the post-commit gate uses the whole shell call's exit code, so git commit && git push with a failing push is skipped although a commit happened. Documented in the spec.
  • Review round (bilersan): the MCP shape was reworked as above; also preview-build stamps, windowsHide, the plugin-based keep fallback, file-mode preservation, subagent skipping, the pause session-id fallback, and prune for OpenCode 2 session ids. Three items became tasks: OpenCode's config-directory resolution, running ctx by absolute path (now fix(opencode,pi): run ctx by absolute path from the tool plugins #213), and the Claude Code plugin warning in bootstrap output.
  • Second review round (bilersan): the duplicate native entry is removed instead of synced; the "OpenCode 1 rejects mcp.servers" statement is narrowed to releases before 1.18.24 everywhere it appeared; the probe error is printed when detection fails; the config-directory task records what OpenCode 1 honors; a task was added for the shortened session id in hook log lines.
  • Not in this PR: the OpenCode 1 plugin still sends no hook envelope (existing open task in TASKS.md); hook nudges are still not surfaced to the agent in OpenCode (new task added); JSONC tolerance in opencode.json (existing task).
  • The docs commit also removes a shell.env row from the hook table: the plugin never registered that hook.
  • The third commit carries two .context captures left over from the mirror-sync session (the JSONC learning and task, and a closed rebase task); the commit body says so.

OpenCode 2 refuses to load OpenCode 1 plugins and nests MCP servers
under mcp.servers, so a stock `ctx setup opencode` left OpenCode 2
with no lifecycle hooks and a legacy-shaped MCP entry. Setup now
chooses a generation and deploys the matching plugin and MCP shape.

A single dual-export plugin was the alternative, but OpenCode 1.x
only accepts that entrypoint from 1.18.29, so it would break older
1.x installs.

Changes:
- setup picks the generation from CTX_OPENCODE_MAJOR, then
  `opencode --version`, then an OpenCode 2 setup an earlier run left
  in the global config, then OpenCode 1, and prints which and how
- second embedded plugin (plugin-v2) for the OpenCode 2 plugin API,
  deployed to the same .opencode/plugins/ctx.ts so a re-run migrates
  in place
- the OpenCode 2 plugin stores `ctx system bootstrap` output once per
  session as a session instruction entry instead of re-injecting it
  on every compaction; OpenCode 2 keeps the entry across compaction
  and forks, so the plugin has no compaction hook
- once-per-session work hangs off the prompt hook: OpenCode 2's
  event stream is server-wide and plugins load lazily, so
  session.created reaches the wrong project or not at all
- hook subcommands get the hook-JSON envelope on stdin, and
  post-commit runs only when the shell call exited 0
- MCP merge writes mcp.servers.ctx for OpenCode 2 and mcp.ctx for
  OpenCode 1, each removing ctx's entry in the other shape; other
  servers are untouched and OpenCode 1 output is unchanged
- tools/typecheck/opencode-v2 and a CI job typecheck the new plugin
  against a pinned @opencode/plugin

Closes ActiveMemory#210

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Users need to know that setup deploys per OpenCode generation, how
it chooses, and what to do after upgrading OpenCode.

Changes:
- docs/home/opencode.md: new "OpenCode 1 and OpenCode 2" section,
  per-generation hook table, compaction explained for both, upgrade
  and refresh steps (per-project plugin, OpenCode 2 service restart),
  two troubleshooting rows
- the hook table no longer lists a shell.env hook the plugin never
  registered
- docs/operations/integrations.md: "How It Works" covers both
  generations
- docs/cli/setup.md and docs/cli/index.md: detection order, the
  setup report lines, and CTX_OPENCODE_MAJOR
- site/ regenerated

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Record what the port decided and what OpenCode 2 taught us, so the
next session does not rediscover it.

Changes:
- decisions: per-major deploy for OpenCode setup; a session
  instruction entry on the first prompt instead of a compaction hook
- learnings: OpenCode 2's session.created is server-wide and missed
  after a lazy plugin load; a non-zero shell exit arrives as a
  completed tool call
- task: surface hook nudges to the agent in the OpenCode 2 plugin
- two captures left uncommitted by the OpenCode mirror-sync session:
  the JSONC learning and its task (the spec lists JSONC tolerance as
  tracked separately; this is that tracking), and the closed
  rebase-after-ActiveMemory#160 task

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Comment thread internal/cli/setup/core/opencode/mcp.go Resolved
Comment thread internal/cli/setup/core/opencode/mcp.go Resolved
Comment thread internal/cli/setup/core/opencode/mcp.go Resolved
Comment thread internal/cli/setup/core/opencode/mcp.go Resolved
… review

Review of ActiveMemory#211 showed the OpenCode 2 MCP shape breaks OpenCode 1:
both versions read the same global config, and OpenCode 1.18.18
rejects the whole file ("Configuration is invalid") once mcp.servers
exists. Setup now writes the legacy mcp.ctx entry for both, which
OpenCode 2 also reads, and never creates the native container.

Changes:
- MCP merge is one function again; an mcp.servers.ctx entry the user
  already has is kept in sync so OpenCode 2 sees no conflict, and a
  legacy server named "servers" is never written into
- rewriting the global config keeps its file mode (it can hold
  tokens)
- the kept-OpenCode-2 fallback reads the deployed plugin, not the
  MCP config, which can fail to merge independently
- a preview build stamp (0.0.0-<channel>-<build>) reads as not
  detected instead of as OpenCode 1; probe output is parsed even
  when the probe reports an error
- plugin: windowsHide on every ctx call; subagent sessions are
  skipped by the prompt and idle hooks; header documents the
  project-root launch requirement and the backgrounded-commit limit
- `ctx hook pause` and resume fall back to OPENCODE_SESSION_ID, so a
  pause run from a skill lands on the session id the plugin's hooks
  use
- prune recognizes OpenCode 2 session ids, so their state files do
  not accumulate

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Follow the review changes: the MCP entry no longer differs between
OpenCode 1 and 2, so there is nothing to migrate, and a machine can
run both side by side.

Changes:
- docs/home/opencode.md: comparison table and upgrade steps updated;
  new note that OpenCode must be started from the project root
- docs/operations/integrations.md, docs/cli/setup.md: detection
  wording and the setup report lines
- site/ regenerated

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Changes:
- learning: OpenCode 1 rejects any config holding mcp.servers
- decision on per-major deploy amended: one MCP shape for both
- tasks from the ActiveMemory#211 review left out of scope: OpenCode's config
  directory resolution, running ctx by absolute path from plugins,
  the Claude Code plugin warning in bootstrap output

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
…tion failed

Second review round on the OpenCode 2 port.

MCP: when the config already held a ctx entry in OpenCode 2's
mcp.servers container, setup kept it in sync with the legacy mcp.ctx
entry. OpenCode 1.18.24 and later compare the raw objects and log a
conflict for that pair on every config load, even when both name the
same command. Setup now removes the native ctx entry, removes the
container if that leaves it empty, and prints that it did. mcp.ctx
alone serves both generations.

The claim that OpenCode 1 rejects a config containing mcp.servers is
narrowed to releases before 1.18.24, which added a compatibility
layer. Reproduced on 1.18.33; 1.18.18 still rejects.

Detection: when `opencode --version` fails and a fallback decides,
setup prints the probe's error before the fallback line.

Also drops the KeyDisabled constant, unused once nothing writes the
native shape.

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Narrow the "OpenCode 1 rejects mcp.servers" statement to releases
before 1.18.24, describe the removal of a duplicate ctx entry, and
show the line setup prints when `opencode --version` fails.
Regenerated site/.

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
Correct the mcp.servers learning and decision to the versions they
hold for, record what OpenCode 1 honors for its config directory in
the open task, and add a task for the shortened session id in hook
log lines.

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
@bilersan

bilersan commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Windows live check of this PR on OpenCode 2.4.3.

Setup. Windows 11; OpenCode 2.4.3 from npm (@opencode/cli@2.4.3, which gives opencode.exe and an npm opencode.cmd shim); OpenCode's config, data and state in scratch directories; a free opencode/* model; a logging ctx.exe first on the service's PATH that records each call (args, cwd, stdin, OPENCODE_SESSION_ID, console-window facts) and then runs the real binary. The plugin and session checks ran at 9dfab21; the plugin file is unchanged at 7b20045. The setup checks were re-run at 7b20045.

Check Result
Detection OpenCode 2.x detected: deploying the OpenCode 2 plugin, through opencode.exe alone and through the opencode.cmd shim alone. Without opencode on PATH (7b20045): opencode --version gave no version: exec: "opencode": executable file not found in %PATH%, then "keeping the OpenCode 2 plugin already deployed", or "assuming 1.x" in a fresh project. CTX_OPENCODE_MAJOR=2 gives "selected by CTX_OPENCODE_MAJOR".
MCP entry (7b20045) Only mcp.ctx = {type: local, command: [<abs>\ctx.exe, mcp, serve], enabled: true}. With ctx's own mcp.servers.ctx beside it: ○ removed the duplicate mcp.servers.ctx entry, and the emptied container is gone.
OpenCode 2 reads it opencode plugin list: ctx local ...\.opencode\plugins\ctx.ts. opencode mcp list: ✓ ctx connected; log mcp connected server=ctx tools=15. No warning or diagnostic about the entry, also at DEBUG.
Legacy + native pair Same command in both: no normalization diagnostic at DEBUG. Different native command: kind=conflict action="retained native value over legacy value", the native entry wins, and it is logged at DEBUG only. That fits removing the duplicate in 1638b31.
Session start First prompt: system bootstrap, then agent --budget 4000, cwd = project root. Later prompts in the session repeat neither. The ctx instruction entry is on the session.
Idle system check-persistence and system check-task-completion after every turn, stdin {"session_id":"ses_…","tool_input":{"command":""}}.
/ctx-pause OPENCODE_SESSION_ID in the agent's shell equals the envelope's id. ctx hook pause creates .context/state/ctx-paused-<that id> (not -unknown); ctx hook resume removes it.
Commits A successful git commit calls system post-commit with the command in the envelope. A git commit that exits 1 (nothing staged) calls nothing.
Edits A write call gives system check-task-completion.
Subagent The child session gets no bootstrap, no agent, no idle checks and no instruction entry. Its write still gave check-task-completion with the child's id.
Started from a subdirectory As documented: system bootstrap exits 1 (no .context/), no entry; the idle checks run there and do nothing. The MCP server fails there too (mcp connect failed ... no .context/ at $PWD).

Console windows (windowsHide). The same prompt with each plugin, service restarted in between. Windows Terminal is the default terminal on that machine.

f9fef40 (no windowsHide) 9dfab21 (windowsHide: true)
GetConsoleWindow in the 4 plugin calls non-zero, 4 of 4 0, 4 of 4 (and 0 in all 32 plugin calls of the longer session run)
Console PseudoConsoleWindow owned by a visible Windows Terminal window, a new one per call none
Seen from outside each call starts OpenConsole.exe and a visible Terminal window for about a second no window events, no OpenConsole.exe

So the Windows console item can come off the spec's "Not verified live" list. Still not run on Windows: pwsh 7 as the agent's shell (Windows PowerShell 5.1 was used), a shell call moved to the background, and preview version stamps.

PATH, for #213. The plugin's calls resolve ctx on the service's PATH, while the agent's shell runs with the environment of the client that sent the prompt. In one run ctx was only on the service's PATH: every hook worked, but ctx hook pause from the agent's shell failed with "The term 'ctx' is not recognized". #213 covers the plugin side; the shell side only needs ctx on the user's PATH, as for any other agent.

Nothing blocking from the Windows side.

The reviewer ran the port on Windows 11 with OpenCode 2.4.3,
including the console-window behavior with and without windowsHide.
Move that item out of "Not verified live" and list what is still
unverified.

Spec: specs/opencode-v2-compat.md
Signed-off-by: Omer Kocaoglu <omergk28@gmail.com>
@omergk28

omergk28 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the Windows run; that closes the largest gap in what I could verify here. f346e89 records it in the spec's Verification section and takes the console-window item off the "Not verified live" list, which now reads: preview version stamps, a shell call moved to the background, and pwsh 7 as the agent's shell.

On the PATH note: #213's docs now say that the agent's own shell is separate from the plugin's lookup and still needs ctx on the user's PATH.

The second-round changes are in 1638b31, ca6ac3f and 7b20045; replies are on the individual threads.

… polish docs

Keep session.ReadID strictly stdin-scoped so hook-envelope callers such as
the unknown-subcommand relay do not fire webhook/event-log relays on manual
shell typos when OpenCode 2 exports OPENCODE_SESSION_ID. Introduce
session.ResolveID for interactive pause/resume commands instead.

Also drop failed subagent lookups from the OpenCode 2 plugin's children
cache so transient errors retry, align pluginV2Deployed naming and test
hermeticity, and refresh stale docstrings and command help text.

Spec: specs/opencode-v2-compat.md
Signed-off-by: Ersan Bilik <ersanbilik@gmail.com>

@bilersan bilersan left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final pass looks solid — thank you @omergk28 for the thorough Round 1, Round 2, and Windows live-verification work!

I pushed one small follow-up commit (2b0a41a7) before approving to address the last few polish items from the final audit:

  • Scoped the OPENCODE_SESSION_ID fallback to a new session.ResolveID helper used by ctx hook pause / ctx hook resume, keeping session.ReadID strictly stdin-only so hook-envelope callers (like the unknown-subcommand relay) don't fire on manual shell typos when OPENCODE_SESSION_ID is exported in OpenCode 2's shell.
  • Evicted failed ctx.session.get lookups from plugin-v2/index.ts's children map so transient service errors aren't cached for the lifetime of the session.
  • Renamed deployedPluginIsV2 -> pluginV2Deployed, isolated TestResolveMajor with withTempProjectDir, added negative SDK-import assertions, and refreshed the remaining stale docstrings/help text (InfoOpenCodeVersionKept, prune, pause/resume, opencode/doc.go, config/hook/hook.go, and specs/opencode-v2-compat.md).

All 15 review threads are resolved and all 9 CI checks are green on 2b0a41a7. LGTM!

@bilersan
bilersan merged commit 49740e7 into ActiveMemory:main Dec 4, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ctx setup opencode does not work on OpenCode 2: plugin fails to load, MCP entry uses the legacy shape

2 participants