Skip to content

feat(opencode): support opencode v2 (dual-key plugin registration) - #1045

Merged
rullerzhou-afk merged 6 commits into
rullerzhou-afk:mainfrom
xiaoshidefeng:feat/opencode-v2-support
Sep 26, 2026
Merged

rullerzhou-afk merged 6 commits into
rullerzhou-afk:mainfrom
xiaoshidefeng:feat/opencode-v2-support

Conversation

@xiaoshidefeng

@xiaoshidefeng xiaoshidefeng commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #1039. OpenCode 2.x (npm @opencode/cli) broke the integration in four independent ways: the config key renamed plugin → plugins, the plugin API requires a { id, setup } definition (our v1 function entry fails the loader schema), events moved to ctx.event.subscribe() with a fully replaced vocabulary, and the permission system gained a native evaluate hook. The v1 entry is simply inert on v2 — that is the report in #1039.

This PR carries v2 alongside v1 with zero changes to the proven v1 contract:

  • Dual-key registration, no version detection. The installer keeps the v1 entry under plugin and registers a new v2 entry under plugins; both point into the same managed generation. Verified on real machines in both directions: opencode 2.0.15 tolerates the legacy plugin key (the v1 entry only logs a loader warning), and opencode 1.18.32 silently drops an unknown plugins key. v1-only, v2-only, and both-installed hosts all work.
  • v2 runtime (createOpencodeFamilyPluginV2 in the shared core + a 5th bundle file opencode-plugin-v2/index.mjs): zero-import { id, setup } entry, event translation for the new vocabulary, per-event cwd from the envelope, titles from session.renamed, context usage from session.usage.updated, unknown events ignored.
  • Permission via the native evaluate hook. The hook blocks on a long POST to Clawd's /permission; the decision is the response body { decision: allow | always | deny }. Every Clawd-stays-out gate answers 204 so the native ask UI takes over. The v1 reverse bridge stays for v1 hosts; v2 has no bridge. "Always allow" is a per-session in-plugin rule (v2 exposes no persistence API).
  • Known v2 degradations, documented: the plugin runs in opencode's shared service, so process-tree fields are omitted (terminal focus degrades) and installs need opencode service restart.

Verification

  • Real-machine (macOS arm64, opencode 2.0.15, GLM glm-5.3-flash): dual-key install into one generation, live session state flow (SessionStart → thinking → working → attention) accepted by a running Clawd, real shell-ask reaching the evaluate hook, and the fail-closed leg demonstrated end-to-end (old Clawd build answers a plain ACK → plugin logs unsupported-decision → no-decision → native prompt). Evidence: docs/investigations/opencode-v2-e1-evidence.md.
  • New tests (all green): v2 permission round-trips over the real route handler (10), v2 runtime/event-mapping/evaluate matrix (13), v2 registration planner + installer dual-key flows (6), doctor v2 verdicts (2 new). Existing opencode suites (managed-generation [BUG] opencode ≥ 1.18.x 会静默忽略注册在不可写目录(默认安装即 C:\Program Files\...)下的插件,导致 OpenCode 接管失效 #1026, jsonc 无法监听到opencode 桌面端的会话 #825, hardening, family-core, bridge, doctor) all pass unchanged in behavior.
  • Full npm test: 10981 pass; the 20 failures are pre-existing on this machine (theme/notifier/slack areas, verified identical on the clean base commit) and unrelated to this change.
  • Pending, recorded in docs/project/release-process.md: bubble Allow/Always/Deny round-trip against a packaged build carrying the v2 branch, and the Windows real-machine matrix.

Test plan

OpenCode 2.x (npm @opencode/cli) renamed the config key plugin -> plugins,
requires a { id, setup } plugin definition, replaced the event hook with
ctx.event.subscribe(), runs plugins in a shared background service, and
ships a native permission evaluate hook. The v1 function entry fails the
v2 loader schema, which is why Clawd stopped recognizing opencode after a
v2 upgrade (rullerzhou-afk#1039).

- Add createOpencodeFamilyPluginV2 in the shared family core: zero-import
  { id, setup } definition, event-subscription translation for the v2
  vocabulary (session.step/tool/execution.*, session.renamed,
  session.usage.updated), per-event cwd from the envelope location, and a
  blocking evaluate hook whose decision is the /permission response body
  ({ decision: allow | always | deny }). 204/timeout/any error leaves the
  effect untouched so the native ask UI wins. No reverse bridge on v2.
- Materialize opencode-plugin-v2/index.mjs as a fifth bundle file and
  register it under the plugins key (new opencode-family-v2-registration
  module); the v1 plugin-key entry is untouched. Dual-key coexistence is
  verified in both directions: v2 tolerates the legacy plugin key, and
  v1 1.18.32 silently drops an unknown plugins key - no host-version
  detection anywhere. inspectGeneration accepts the historical four-file
  set as a legal owned-stale shape so old generations migrate.
- Server: new opencode-v2 sub-branch in the permission route holds the
  connection and answers the decision JSON; every Clawd-stays-out gate
  (DND, agent disabled, sub-gate, bubbles-off without remote) answers
  204 no-decision. resolvePermissionEntry and the dismiss sweep write the
  decision / release the await for v2 entries.
- Doctor: the managed inspector factors the v2 key into the verdict -
  a healthy v1 entry with a missing v2 entry is a repairable legacy-path,
  never ok.
- Known v2 degradations (documented): plugin runs in the shared service,
  so process-tree fields are omitted (terminal focus degrades) and
  Always-allow is a per-session in-plugin rule; opencode service restart
  is needed after install/repair.

Real-machine evidence (macOS, opencode 2.0.15 + GLM): docs/investigations/
opencode-v2-e1-evidence.md.
Full Allow / Deny / family-Always / always-hit matrix verified against a
live source-run Clawd carrying the v2 branch (opencode 2.0.15 + GLM):
sequential and parallel asks, auto-tools automation interop, and the
fail-closed fallback against a Clawd without the v2 branch. Only the
Windows matrix and a packaged-asar spot check remain pending.
E1 probe evidence (loader schema, plugins-key tolerance both directions,
evaluate-hook blocking semantics, service process model, full event
vocabulary) plus the E2 live bubble-decision matrix against a Clawd
instance running the v2 branch. Referenced by PR rullerzhou-afk#1045; docs/** is
gitignored for new files so this one is force-added like its siblings.
@rullerzhou-afk

Copy link
Copy Markdown
Owner

Thanks a lot for this, @xiaoshidefeng! It's a really thorough port: the dual-key design, the E1/E2 real-machine evidence, the new tests and green CI on all three platforms are all excellent. We gave it two independent reviews on our side, and the overall quality is high.

There is one problem that would stop some users' opencode from starting at all, though, so we can't merge it just yet. None of the changes below are an obligation: if you'd rather not take them on, just say so and we'll push the fixes to your branch and merge it, keeping your commits and authorship.

Two changes needed before merge

1. Writing the top-level plugins key unconditionally breaks opencode 1.18.15 and earlier

opencode 1.18.15 and older reject unknown top-level config keys. Upstream packages/opencode/src/config/parse.ts has a topLevelExtraKeys check in v1.14.30 through v1.18.15, and earlier 1.x releases use zod .strict() (we spot-checked tags across 1.0 → 1.18.15). Unknown fields have only been ignored since v1.18.16 (anomalyco/opencode#41312, merged 2026-08-08). The 1.18.32 used for verification in this PR is just past that change, which is why it didn't show up.

We reproduced it with opencode 1.18.3 in an isolated directory. After writing the config with this PR's registerOpencodePlugin, both opencode debug config and opencode run exit with:

Error: Configuration is invalid at …/opencode.json
↳ Unrecognized key: plugins

Removing the plugins key makes it work again. Since Clawd's startup sync runs register for every user who has opencode installed and enabled, the net effect is "upgrade Clawd → older opencode no longer starts". If the user deletes the key by hand, it comes back on the next launch, and Doctor still reports everything as healthy.

To reproduce (everything points at a temp directory, so your real config isn't touched; we ran a locally installed 1.18.3 binary, and the npx form below should be equivalent):

d=$(mktemp -d); mkdir -p "$d/config/opencode"
printf '{"$schema":"https://opencode.ai/config.json","plugin":[],"plugins":["/tmp/x/opencode-plugin-v2"]}\n' > "$d/config/opencode/opencode.json"
XDG_CONFIG_HOME="$d/config" XDG_DATA_HOME="$d/data" XDG_STATE_HOME="$d/state" XDG_CACHE_HOME="$d/cache" npx -y [email protected] debug config

A possible direction (just a suggestion, implement it however you prefer): only write the plugins entry when an opencode v2 host is actually detected on the machine, for example when opencode --version on PATH reports major version 2 or later, or @opencode/cli is installed. That keeps v1-only machines exactly as they are today. Doctor then shouldn't require the v2 entry when there's no v2 host. The AGENTS.md sentence saying that v1 1.18.32 silently drops the unknown plugins key, so no host-version detection is needed, should also note that this only holds for 1.18.16 and later.

2. v2 shell commands bypass the destructive-action reminder

The v2 plugin sends the command as tool_input.resource, but src/permission-reminder.js only reads the command from command / CommandLine / Command / cmd / script. So preparePermissionReminder("shell", { resource: "rm -rf ~/x" }) returns null, while the same command under command is held for the user. In practice, when a user has both permission automation and the destructive-action reminder turned on, a v2 rm -rf gets auto-approved, and the bubble doesn't show the destructive-action hint either. Suggestion: in the v2 adapter, map a single shell resource to command (keeping the raw resource for display), and add a test covering v2 together with the reminder.

Everything else: we'll take care of it after merging

The truncation above 16 resources, Doctor throwing on duplicate plugins keys, headless handling for v2 child sessions, a migration test for the legacy four-file generation, decision parsing on non-200 responses, cleanup when setup runs again, the Doctor default log list, and the "Always allow" tooltip wording under v2: we'll follow up on all of these ourselves after merging, so there's no need for you to touch them.

Thanks again!

opencode <= 1.18.15 rejects unknown top-level config keys
(Unrecognized key: plugins), so the unconditional dual-key write from
rullerzhou-afk#1039 broke every older host on the next Clawd startup sync — the
silent drop verified on 1.18.32 only holds from 1.18.16
(anomalyco/opencode#41312).

Add hooks/opencode-host-detect.js (opencode --version tri-state:
v2/v1/unknown, login-shell PATH fallback for GUI launches, win32 via
where, CLAWD_OPENCODE_HOST escape hatch) and gate the managed register
on it: a v2 host registers the key as before, a v1 host never writes it
and sweeps proven-owned leftovers so a v2->v1 downgrade self-heals, an
unknown host never touches the key. unregister keeps sweeping both keys
unconditionally. Doctor no longer demands the v2 entry without a v2
host and reports a leftover entry on a 1.x host as a repairable
broken-path.

Note the probe side effect: running opencode --version makes the host
create its config dir, so tests pin the verdict explicitly.
…inder

The v2 plugin sends a single shell command as tool_input.resource
(buildV2PermissionBody), but the destructive-action reminder only scans
command-carrying fields — so under permission automation a v2
rm -rf was auto-approved and the bubble showed no hint.

Alias a lone shell resource to command for the detail/reminder view
(mapOpencodeV2ShellResource, gated on the same SHELL_TOOLS set the
reminder uses); the raw resource stays in place for display and the
stored tool_input keeps the original payload. Multi-resource requests
and non-shell tools are intentionally left unmapped.
@xiaoshidefeng

xiaoshidefeng commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

两个问题都已修复并推送到分支(899c5718、f8a2f0aa):

1. plugins 键改为按宿主探测条件写入。 新增 hooks/opencode-host-detect.js:opencode --version 三态判定(v2 / v1 / unknown;posix 走 login shell 解析 PATH,解决 macOS GUI 启动时 PATH 受限的问题;win32 走 where;另有 CLAWD_OPENCODE_HOST 环境变量可钉死结论)。managed register 按三态分支:v2 宿主照常注册;v1 宿主不写键,并清扫已存在的 Clawd-owned 残留条目,让 v2→v1 降级在下次启动同步 / Repair 时自愈;unknown 完全不碰该键。uninstall 保持无条件清扫两个键。Doctor 在无 v2 宿主时不再要求 v2 条目;v1 宿主 + 残留条目改为可修复的 broken-path。AGENTS.md 已改为"静默丢弃仅 1.18.16+ 成立"。

两点补充说明:(a) 探测本身有副作用——运行 opencode --version 会让宿主创建自己的 config 目录,所以"目录不存在 = 未安装"的跳过检查与探测有交互,测试里都显式钉死探测结论;(b) 探测失败时刻意既不写也不删,这样探测瞬时失败的 v2 机器会保留已有注册不受影响。

2. v2 shell 命令已接入破坏性操作提醒。 v2 分支把单条 shell resource 别名为 command(用与提醒同一份 SHELL_TOOLS 集合做门控;原 resource 保留供展示,存储的 tool_input 不动;多 resource 与非 shell 工具不映射)。已在真实 2.0.15 宿主上验证:auto-tools 下以 resource 形态到达的 git push --force 现在会弹气泡,而不是被自动放行。

全量测试通过,并用隔离 XDG 目录对 1.18.3 复核了带键 / 不带键两种形态。感谢指出 1.18.15 的边界——我们差点直接跨过去了。

补充:两项修复我已在 macOS 真机(opencode 2.0.15)上测试通过——权限气泡正常弹出、破坏性命令不再被自动放行、状态动画均正常。

@rullerzhou-afk
rullerzhou-afk merged commit f6aca11 into rullerzhou-afk:main Sep 26, 2026
9 checks passed
@rullerzhou-afk

Copy link
Copy Markdown
Owner

已合并,感谢 @xiaoshidefeng 的贡献!也谢谢你跟进修复和真机验证,辛苦啦!

gzx19990101 added a commit to gzx19990101/clawd-on-desk that referenced this pull request Sep 26, 2026
The migration had activated a second V2 implementation next to the
opencode-plugin-v2 entry from rullerzhou-afk#1045 (dual-key registration visits both
config keys), and its content-hashed shared factory let an orphan managed
copy borrow another installation's ownership gate. This revision ports
the fixes into the existing V2 entry instead:

- The v1 entry keeps its function export (the v2 loader rejects it), so
  exactly one Clawd implementation is V2-valid: the rullerzhou-afk#1045
  opencode-plugin-v2 / createOpencodeFamilyPluginV2 pair, extended here.
- No factory sharing across copies at all: every loaded copy runs its own
  gate at its own import.meta.url before any side effect, so an orphan
  managed generation stays inert while a live copy runs (regression:
  cross-copy/cross-target load).
- Turn-start reporting: session.text.started joins step/reasoning
  started, so consecutive text-only turns each report thinking and their
  own Stop (regression: two no-tool rounds).
- Context usage now comes from session.step.ended tokens (per-request =
  context occupancy) with the model tracked from session.step.started or
  the created default, and the limit resolved from the ctx.model registry
  with a re-push when it lands. session.usage.updated carries cumulative
  billing totals and previously pinned the percentage at 100%
  (regression: used 15 / limit 100000 from the review).
- Recovered children: a bounded ctx.session.get hydration restores parent
  identity, title, cwd and model for sessions that predate the load
  without inventing a lifecycle; child completion routes to SessionEnd
  and reports carry headless (regression).
- Identity hydration is bounded, non-blocking and never retried after a
  failure, so one hung lookup cannot stall other sessions' events
  (regression: pending lookup alongside another session).
- session.execution.interrupted is a cancellation: StopFailure clears
  active state, yields the interrupted badge, and never increments
  completed turns (regression).
- Subscription failures are caught around the whole loop and classified:
  dispose aborts log as intentional, everything else stays visible, and
  nothing becomes an unhandled rejection (regression: throwing iterator).
- Tool lifecycle events stay exempt from state compaction but deliver
  once per (call, phase) identity, so recap counts each call exactly
  once; session.tool.failed gets the v2.0.15 name with tool.error kept
  as an alias.
52mzd pushed a commit to 52mzd/clawd-on-desk-trellis that referenced this pull request Sep 27, 2026
Re-export of the local Trellis integration line onto the fork's export
branch, now including upstream main through fa9bcaa (PR rullerzhou-afk#1053):

- upstream: OpenCode V2 support, WSL PID fix, cursor delivery fix,
  idle mirror theme, juggling pose (rullerzhou-afk#1045 rullerzhou-afk#1053 rullerzhou-afk#1055 rullerzhou-afk#1056 rullerzhou-afk#1050 rullerzhou-afk#1022)
- fork: HUD trellis detail row now follows the light/dark theme (#fix)
- version: v1.1.0-trellis.1.1 kept in package.json (no post-tag revert);
  the release-version-contract test now reads the version dynamically and
  skips the draft smoke checklist for pre-release versions, so the fork
  version no longer cascades into contract assertion updates
- README.ko-KR.md merges the fork declaration block with upstream
  wording polish (f8c3e69)

Private workflow state (.trellis/, .pi/) remains intentionally absent.
52mzd added a commit to 52mzd/clawd-on-desk-trellis that referenced this pull request Sep 27, 2026
Re-export of the local Trellis integration line onto the fork's export
branch, now including upstream main through fa9bcaa (PR rullerzhou-afk#1053):

- upstream: OpenCode V2 support, WSL PID fix, cursor delivery fix,
  idle mirror theme, juggling pose (rullerzhou-afk#1045 rullerzhou-afk#1053 rullerzhou-afk#1055 rullerzhou-afk#1056 rullerzhou-afk#1050 rullerzhou-afk#1022)
- fork: HUD trellis detail row now follows the light/dark theme
- version: v1.1.0-trellis.1.1 kept in package.json (no post-tag revert);
  the release-version-contract test now reads the version dynamically and
  skips the draft smoke checklist for pre-release versions, so the fork
  version no longer cascades into contract assertion updates
- README.ko-KR.md merges the fork declaration block with upstream
  wording polish (f8c3e69)
- retained fork contributor registrations (52mzd in verify overrides and
  Settings About; 52mzd / hanzhe-one in README tables)

Private workflow state (.trellis/, .pi/) remains intentionally absent.
rullerzhou-afk added a commit that referenced this pull request Sep 27, 2026
@rullerzhou-afk

Copy link
Copy Markdown
Owner

Quick follow-up on the items we said we'd handle after merging: they're all done now.

  • Headless handling for v2 child sessions was already covered by feat(opencode): OpenCode V2 plugin API support (and fixes found migrating live) #1053.
  • The other seven landed in fix(opencode): v2 follow-ups promised in #1045 #1067, just merged:
    • resources are forwarded verbatim instead of being cut at 16;
    • a duplicate top-level plugins key no longer makes Doctor throw, and install/uninstall stop before writing anything;
    • only a 200 response counts as a decision;
    • the evaluate hook is registered and disposed the way opencode v2.0.15's Promise<Registration> API expects, so reloads stay clean;
    • Doctor collects opencode-plugin-v2.log;
    • the Always tooltip no longer tells v2 users that restarting opencode revokes the rule;
    • the legacy four-file generation migration now has a real test.

We also ran the branch end to end against opencode 2.0.18: Allow / Deny / Always, the destructive-command hint, and an external_directory + edit pair from a single tool call. Nothing needed from you. Thanks again for the port, it made all of this easy to build on!

Link-Start pushed a commit to Link-Start/clawd-on-desk-rullerzhou-afk that referenced this pull request Sep 28, 2026
Follow-ups to rullerzhou-afk#1045 in the opencode v2 plugin runtime.

Resources: buildV2PermissionBody kept only the first 16 resources and
clipped object resources to 4,096 characters, yet an Allow decides the
whole ask. Resources are now forwarded verbatim. The existing 512 KiB body
budget is the only boundary; an ask over it is left to opencode's native
prompt.

Decisions: only a 200 with the Clawd identity header and a valid JSON body
is a decision. A 403 or 500 whose body held {"decision":"allow"} used to
be honoured.

Reload: opencode v2.0.15 returns Promise<Registration> from
ctx.permission.hook() (packages/plugin/src/promise/registration.ts). The
plugin only recognised a synchronous function, so it never unregistered,
and each setup's cleanup read the shared dispose slot, so a cleanup that
ran after a newer setup tore down the newer subscription and its identity
recovery. Now each setup's cleanup disposes only its own instance; local
teardown runs synchronously before the registration is disposed, and that
dispose is bounded to 2 s; reload retires the previous generation without
waiting for it; the event subscription never waits on hook registration;
and a retired generation's evaluate callback returns without forwarding,
because the host calls every registered hook in turn on one shared event
(packages/core/src/plugin/hooks.ts).

Every ask is still forwarded on its own: several asks of one tool call
share source.id (external_directory, then edit), so it is not an ask
identity.
Link-Start pushed a commit to Link-Start/clawd-on-desk-rullerzhou-afk that referenced this pull request Sep 30, 2026
opencode v2 sends a compound shell command (a && b, a | b, a ; b) as
tool_input.resources. Only a single resource was aliased to command, so
the destructive-action reminder and the irreversible badge never saw
multi-resource commands. When every resource is a string, the route and
the bubble renderer now join them with newlines into command; the raw
payload is kept, and detection rules are unchanged. This only adds holds
under automation, never removes one.

Also renames four existing tests in the same file from "upstream rullerzhou-afk#1045
review" to "PR rullerzhou-afk#1045 follow-up".
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.

希望增加对 opencode-v2 的适配

2 participants