Repository navigation
feat(opencode): support opencode v2 (dual-key plugin registration) - #1045
Conversation
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.
|
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 merge1. Writing the top-level opencode 1.18.15 and older reject unknown top-level config keys. Upstream We reproduced it with opencode 1.18.3 in an isolated directory. After writing the config with this PR's Removing the 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 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 configA possible direction (just a suggestion, implement it however you prefer): only write the 2. v2 shell commands bypass the destructive-action reminder The v2 plugin sends the command as Everything else: we'll take care of it after mergingThe truncation above 16 resources, Doctor throwing on duplicate 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.
|
两个问题都已修复并推送到分支(899c5718、f8a2f0aa): 1. 两点补充说明:(a) 探测本身有副作用——运行 2. v2 shell 命令已接入破坏性操作提醒。 v2 分支把单条 shell 全量测试通过,并用隔离 XDG 目录对 1.18.3 复核了带键 / 不带键两种形态。感谢指出 1.18.15 的边界——我们差点直接跨过去了。 补充:两项修复我已在 macOS 真机(opencode 2.0.15)上测试通过——权限气泡正常弹出、破坏性命令不再被自动放行、状态动画均正常。 |
|
已合并,感谢 @xiaoshidefeng 的贡献!也谢谢你跟进修复和真机验证,辛苦啦! |
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.
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.
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.
fix(opencode): v2 follow-ups promised in #1045
|
Quick follow-up on the items we said we'd handle after merging: they're all done now.
We also ran the branch end to end against opencode 2.0.18: Allow / Deny / Always, the destructive-command hint, and an |
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.
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".
Summary
Fixes #1039. OpenCode 2.x (npm
@opencode/cli) broke the integration in four independent ways: the config key renamedplugin→plugins, the plugin API requires a{ id, setup }definition (our v1 function entry fails the loader schema), events moved toctx.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:
pluginand registers a new v2 entry underplugins; both point into the same managed generation. Verified on real machines in both directions: opencode 2.0.15 tolerates the legacypluginkey (the v1 entry only logs a loader warning), and opencode 1.18.32 silently drops an unknownpluginskey. v1-only, v2-only, and both-installed hosts all work.createOpencodeFamilyPluginV2in the shared core + a 5th bundle fileopencode-plugin-v2/index.mjs): zero-import{ id, setup }entry, event translation for the new vocabulary, per-event cwd from the envelope, titles fromsession.renamed, context usage fromsession.usage.updated, unknown events ignored./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).opencode service restart.Verification
unsupported-decision→ no-decision → native prompt). Evidence:docs/investigations/opencode-v2-e1-evidence.md.C:\Program Files\...)下的插件,导致 OpenCode 接管失效 #1026, jsonc 无法监听到opencode 桌面端的会话 #825, hardening, family-core, bridge, doctor) all pass unchanged in behavior.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.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
node --test test/opencode-v2-permission.test.js test/opencode-family-v2.test.js test/opencode-v2-registration.test.jsC:\Program Files\...)下的插件,导致 OpenCode 接管失效 #1026 / 无法监听到opencode 桌面端的会话 #825 / hardening / doctor / bridge / core)npm test(no new failures vs base)