Repository navigation
feat(hook/opencode): support OpenCode V2, Desktop, and Windows (#3463, #3326) - #4187
Conversation
a151413 to
9995652
Compare
📊 Automated PR Analysis
SummaryRefactors the OpenCode RTK hook plugin to support both OpenCode 2.0's { id, setup } / execute.before API and the legacy 1.x tool.execute.before API, replaces the Bun-only zx Review Checklist
Linked issues: #3463, #3326, #2516, #1993 Analyzed automatically by wshm · This is an automated analysis, not a human review. |
Context & Comparison with other open OpenCode PRsThere are several open PRs addressing various OpenCode integration issues (#3463, #3330, #2819, #2705, #2566, #2153). This PR supersedes them by providing a single, zero-dependency, universal implementation that resolves all open failure modes at once:
Key advantages of this approach:
|
tomas-barros1
left a comment
There was a problem hiding this comment.
AI code review — solid fix; two hardening items + tests to address
Reviewed hooks/opencode/rtk.ts and the doc changes against the linked issues and the OpenCode V1/V2 plugin APIs. All four issues are addressed in substance, and the key claims verify:
- #3326 (Desktop /
$ is not a function) — eliminated: no Bun$, no zx;node:child_process.execFileruns in Electron/Node. - #2516 (missing default export) — fixed (
export default RtkOpenCodePlugin), and the old named export is kept so existing installs don't break. - #1993 (Windows /
which) — fixed viapath.delimiter+PATHEXTprobing + extra dirs (~/.cargo/bin,~/.local/bin, Homebrew);exts = [""]on POSIX keeps behavior sane.windowsHide: trueis a nice touch. - #3463 (V2 API) —
id/setup+ctx.tool.hook("execute.before", ...)matches the OpenCode V2 plugin docs, including mutatingevent.input.commandon the mutable event. - Exit code 3 — verified against
src/hooks/rewrite_cmd.rs: Allow→0, Ask→3, Default→3, Deny→2, Defer→1. Treating 3 as success is real and necessary. rtk initwiring —src/hooks/init.rsembeds this exact file (include_str!("../../hooks/opencode/rtk.ts")), so the fix lands inrtk init -g --opencodeon the next build. Worth a release note (existing installs must re-run init / upgrade).- Security: array argv to
execFile⇒ no shell interpolation; missing/unresponsive binary still passes through ("never block" preserved); zero dependencies is a real win for a file-based plugin.
Please address
- Timeout partial-stdout hazard (inline) — a child killed by
timeout: 3000can yield truncated stdout that this code would apply as the rewrite. Gate stdout on the error/exit code instead of ignoring it. - V1/V2 dual-shape verification (inline) — the hybrid (callable function with attached
id/setup) is clever, but you're shipping the only hook that doesn't prove it through the documented shape. One smoke test through the real V2 loader would settle it. - No tests — this is the only agent hook in
hooks/without a test (hooks/hermes/tests/test_rtk_rewrite_plugin.py,hooks/claude/test-rtk-rewrite.sh,hooks/copilot/test-rtk-rewrite.shall ship them). A zero-depnode:testsuite covering path resolution, exit-3 acceptance, timeout discard, tool-name filter, and never-block pass-through would close the "Tests present" gap flagged by the wshm bot and protect the exit-code protocol from regressions.
Nits
- (inline)
cachedRtkPathfreezes a failed lookup asnullfor the session;RTK_BINwith~/$HOMEisn't expanded. - The V2
setupwarns when the binary is missing but the V1 path stays silent — minor asymmetry. hooks/README.md'sexecFilesnippet omits thebash/shelltool-name filter the real code applies (illustrative, but easy to copy wrongly).- Missing trailing newline at EOF (inline).
No hard logic blockers found — this does what it claims. With the two inline items addressed and a small test file, this is ready to merge.
|
Thanks for the thorough review and great catches! All points have been addressed in the latest commit:
|
|
I tested the installed rtk.ts from this PR against OpenCode 2.0.16 (stable, opencode serve) and the plugin fails to load. The V2 loader rejects the hybrid shape: level=WARN message="failed to load plugin" target=~/.config/opencode/plugins/rtk.ts
cause="PluginModule.LoadError: Plugin must export a default definition with an id and an
effect or setup function. (cause: SchemaError(Expected object at [\"default\"]))"Root cause: the 2.0.16 plugin loader validates module.default against a schema that accepts only plain objects — { id, setup } or { id, effect } (verified by reading the loader code inside the compiled binary). A function with .id/.setup bolted on as properties is not an object to that guard, so validation fails before setup() is ever invoked. The V2 branch of the dual-shape therefore never activates — the hook is silently absent on all current 2.x releases. This is consistent with the official V1→V2 migration docs, which state that V2 plugins "default-export a definition with an id and setup(ctx)" and show the dual-support shape as an object that spreads Plugin.define({...}) and adds a server() method — not a callable function with attached properties. export default {
id: "rtk",
async setup(ctx) {
if (!resolveRtkPath()) {
console.warn("[rtk] rtk binary not found — plugin disabled")
return
}
await ctx?.tool?.hook("execute.before", async (event) => {
const input = event?.input
if (!input || typeof input !== "object") return
const rewritten = await tryRewriteCommand(event?.tool, input.command)
if (rewritten) input.command = rewritten
})
},
}Since 2.x is current, I'd suggest making the object definition the default export and dropping the callable-function path (or, if 1.x support must be kept, exporting the object above while leaving the V1 function as a named export for 1.x loaders — though per the docs, 1.x V1 object entrypoints are supported in 1.18.29+, so a plain object with both setup and server keys is the sanctioned dual-shape). This also addresses the smoke-test gap flagged in review: a test that feeds the default export through the actual 2.x loader schema (or a simple |
|
Thanks for testing this against Everything is now updated, hardened, and verified locally:
Ready for re-test! |
…up logic - Consolidate command mutation logic between V1 and V2 entrypoints into a shared helper - Unify missing binary warning between setup() and server() - Simplify expandHome and path discovery loops
Carries rtk-ai#4187 (OpenCode V2, Desktop, and Windows support) until it merges upstream. Drop this commit when syncing after the PR lands; the eventual upstream merge must be a no-op against these files.
|
This PR also addresses #3898. I originally opened #3899 for the same OpenCode 2.0 compatibility issue, but this PR now covers the problem more completely. I closed #3899 and further work on #3898 will be tracked here. If appropriate, please add Closes #3898 so the issue is closed when this PR is merged. |
Thanks for the support and for consolidating the efforts here! I've added |
|
I need this ! |
|
Thanks but is it gonna merge anytime soon? |
|
@pszymkowiak @FlorianBruniaux @aeppling @KuSh @TaKO8Ki Could you please take a look? |
|
+1 Please... |
# Conflicts: # docs/guide/getting-started/supported-agents.md # hooks/opencode/README.md # hooks/opencode/rtk.ts
…ape; harden the rtk shim Adds bin/opencode-plugin-guard (idempotent; --check dry run) plus canonical copies in opencode-plugins/: it restores a plugin only when the v2 default export is missing, strips the redundant openusage plugin entry, warns on canonical drift, and retires itself once both tools ship v2 upstream. Jobber entry added in site-djbclark (03:45, after brew-fast-upgrade/mac-dns-apply). rtk.ts now fails closed: it registers no rewrite when the effective config declares shell permission rules, because execute.before runs before permission evaluation and a rewrite can therefore move a command out from under a deny/ask rule (reproduced today; rtk-ai/rtk#4187 is the upstream fix).
clippy runs with -D warnings over --all-targets, so a function left alive only for a test fails the build. `too_old_opencode` absorbed `is_too_old` when it started taking the banner as a parameter and needed the parsed triple, and the test kept calling the old name. The test now calls `too_old_opencode` itself, which is what it should have been doing anyway: the old pair of assertions went through a helper that shared no code with the branch that actually runs. It also picks up the trimmed-output check while it is there, since that was the reason the function was split at all.
…init honest - A 2.x list rule whose action only names `bash` is no longer counted: OpenCode ignores it, and a counted allow outranked an ask it applies. - A legacy map key the two generations read differently (`shell` and `sh*` apply only on 2.x, `b*` only on 1.x) now stops the rewrite: rtk cannot tell which generation it is serving. Configs are read once per call. - Agent frontmatter keys are found quoted, after a byte-order mark, or in an unclosed block, and agent files in the singular `agent/` directory too. - Below the floor, init no longer prints the plugin path or an OpenCode restart hint for a plugin it did not write, and its message and the docs no longer claim the plugin cannot load from 1.3.4 on. - Tests and dry runs no longer spawn the developer's own `opencode --version`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
KuSh
left a comment
There was a problem hiding this comment.
Round 3 of 3 — APPROVED, follow-ups filed
Claim: hooks/opencode/rtk.ts loads and rewrites on OpenCode 2.x and 1.x, in Desktop (no Bun $), on Windows (no which), delegating to rtk hook opencode and judged against OpenCode's own rules.
Scope: accept if narrowed to "OpenCode 2.x and 1.x, with rtk resolved from PATH (PATHEXT on Windows)", with the floor rtk init enforces. (round 1, frozen)
Ran: real OpenCode driven by a mock model that issues one bash/shell tool call, with the plugin installed by each build's own rtk init -g --opencode: develop 27a659f56 + d222aa542 vs the same + fixup 4775f69e4, binaries verified to differ.
- OpenCode 2.0.26, 1.18.34, 1.18.28, 1.3.4, 1.3.3, 1.1.4.
- 14 permission rows, OpenCode alone vs each build: round 2's four arms; a
bashaction in the 2.x list; quoted, singular-dir and BOM agent files; legacyshell,sh*andb*keys on both generations. rtk initwith each OpenCode onPATH; plain and compound rewrites.- A second agent that had not seen this round's reasoning reran the before/after.
- Invariants: non-default targets, every decision. Savings: n/a, no filter changes.
Pins: 25 decisions in the fixup, 25 mutated, 0 survived. Your d222aa5 fix is pinned by version_floor_is_pinned.
Matrix: executed this round. Pin check: executed this round.
CI @4775f69e4: all green (12/12)
Blocks merge (0 open; all three from round 1 closed)
Round 2's two items are fixed by your two commits and the fixup below:
- Blocker 1: the four arms keep the prompt on 2.0.26.
- Blocker 2: below the floor nothing is written, and the message no longer claims a load failure it can't know about.
What the fixup changed
I pushed one commit, 4775f69e4, plus a merge of the current develop, instead of a fourth list. Every item was measured against OpenCode alone. On your head, each of the first three let the rewrite run rtk ls -la without the prompt OpenCode gives ls -la:
- A
bashaction in the 2.xpermissionslist is no longer counted. OpenCode 2.0.26 ignores it, so an allow there outranked ashellask it does apply. - Legacy keys the two generations read differently now stop the rewrite (
hook opencodeanswers{}). 1.18.34 appliesbashandb*and ignoresshellandsh*; 2.0.26 appliesbash(renamed toshell),shellandsh*and ignoresb*. rtk can't tell which generation it's serving, so either reading silences an ask on the other. This also covers thepermission.shellreading I asked for in round 2, which silenced abashask on 1.x. - Markdown agents: a quoted
"permissions":key, a byte-order mark, an unclosed frontmatter block, and the singular.opencode/agent/directory, which 2.0.26 loads, are all detected now. rtk initbelow the floor no longer prints the plugin path or "Restart … OpenCode" for a plugin it didn't write. That held in all four install modes (-g --opencode,--hook-only,--claude-md,--agent cursor), on both a first run and a re-run. The message and the docs now state the 1.18.29 floor and what init does below it, without claiming the plugin cannot load there.- Tests no longer spawn the developer's own
opencode --version. Five tests were red on a machine with an older OpenCode onPATH. The integration tests now put anopencodestub first onPATH, and unit tests never ask.
It was reviewed as if you had pushed it: three review passes on its diff, the 25-mutation pin check, and the independent before/after.
Filed as follow-ups
- #4521: on 2.x, judge rewrites against the rules OpenCode resolves (
ctx.agent.get) instead of rebuilding them from config files. That removes the two{}fallbacks above and covers session rules and$XDG_CONFIG_HOME. - #4518:
rtk hook check --agent opencodejudges differently from the plugin. It skips the markdown-agent and generation guards, so it can report a rewrite the plugin refuses. Diagnostic only. - #4519:
rtk init --opencode's version probe. A dry run previews an install that the real run refuses below the floor, andopencode --versionruns with no timeout. - #4520 (low priority): on 1.x, rtk misses global rules under
$XDG_CONFIG_HOME/opencodeand inconfig.json, both of which 1.18.34 reads. This was already the case on develop. - #4195: status comment updated (agent-scoped rules are judged on 2.x; 1.x stays root-only).
Checked and correct — no need to re-verify
- d222aa5:
is_too_oldis gone andversion_floor_is_pinnedgoes throughtoo_old_opencode, including the trimmed banner. I kept your version of that test over mine. - On 2.0.26 every round-2 arm gives OpenCode's own outcome:
- a global agent ask against a project allow;
- both agent spellings in one file;
- a markdown agent with rules;
action: "sh*";- a markdown agent without rules still rewrites.
ls -laandrtk ls && ls -laare rewritten in full on 2.0.26.- Init on 1.1.4, 1.3.3, 1.3.4 and 1.18.28 writes no file. On 2.0.26 it installs the plugin.
Your questions
- None open.
Next
Nothing: approving once CI is green on 4775f69e4.
Rounds: 3/3. Threads: 0 open, 2 resolved this round (blockers 1 and 2, fixed).
|
🎉 |
hooks/opencode/rtk.test.mjs was merged with rtk-ai#4187 but nothing executed it. The plugin is a TypeScript file shipped into the user's config directory, not a cargo artifact, so 'cargo test --all' cannot reach it and no other job claimed it. Ten tests covering PATH discovery, the 'hook opencode --help' probe, argv construction and the registered hooks ran nowhere. Added to the existing 'test' job rather than a new one so it runs on all three matrix platforms, which is the point: the plugin's failures were cross-platform by nature -- 'which' missing on Windows, no Bun shell on Desktop. Node 22.18+ strips the types without a loader, so no tsc step and no node_modules are needed, and the test mocks rtk rather than requiring a build. setup-node is pinned to v7, the major actions/checkout and setup-go already use here.
hooks/opencode/rtk.test.mjs was merged with rtk-ai#4187 but nothing executed it. The plugin is a TypeScript file shipped into the user's config directory, not a cargo artifact, so 'cargo test --all' cannot reach it and no other job claimed it. Ten tests covering PATH discovery, the 'hook opencode --help' probe, argv construction and the registered hooks ran nowhere. Added to the existing 'test' job rather than a new one so it runs on all three matrix platforms, which is the point: the plugin's failures were cross-platform by nature -- 'which' missing on Windows, no Bun shell on Desktop. Node 24 strips the types without a loader, so no tsc step and no node_modules are needed, and the test mocks rtk rather than requiring a build. setup-node is pinned to v7, the major actions/checkout and setup-go already use here.
hooks/opencode/rtk.test.mjs was merged with rtk-ai#4187 but nothing executed it. The plugin is a TypeScript file shipped into the user's config directory, not a cargo artifact, so 'cargo test --all' cannot reach it and no other job claimed it. Ten tests covering PATH discovery, the 'hook opencode --help' probe, argv construction and the registered hooks ran nowhere. Added to the existing 'test' job rather than a new one so it runs on all three matrix platforms, which is the point: the plugin's failures were cross-platform by nature -- 'which' missing on Windows, no Bun shell on Desktop. Node 24 strips the types without a loader, so no tsc step and no node_modules are needed, and the test mocks rtk rather than requiring a build. setup-node is pinned to v7, the major actions/checkout and setup-go already use here.
…Not for OpenCode 2" (#2295, witt-bit) The RTK tab blocked OpenCode 2 whatever rtk was installed: rtk's OpenCode plugin used to be written for OpenCode 1 only, which OpenCode 2 refuses ("Plugin must export a default definition with an id and an effect or setup function", rtk-ai/rtk#4311). rtk-ai/rtk#4187 (merged 10-12, first released in rtk 0.52.0, also in 1.0.0 and 1.0.1, the reporter's) writes one default object with OpenCode 2's id and setup() beside OpenCode 1's server(). Checked with gh: 0.52.0's and 1.0.1's hooks/opencode/rtk.ts are byte-identical, 0.51.0's is the old named export. - openCodeBlocked: with OpenCode 2, blocked only when rtk is older than 0.52 or doesn't say its version; the reason now says to update RTK. OpenCode 1 is unchanged with any rtk. - openCodeHas: under OpenCode 2, an old plugin (no setup()) left from before an rtk update counts as off once the rtk here is 0.52+, so switching it on runs rtk init, which writes the new one over it. With an older rtk it still counts as on, so it can be switched off. - GUI: the OpenCode row's tag is "Update RTK" with OpenCode 2 reasons (on: refuses this plugin, update or switch off; off: needs 0.52), in en, zh, zh-TW, ja, de; the "Not for OpenCode 2" strings are gone. - docs/subsystems/library.md says the same. What was run: - Real binaries in a sandbox HOME (throwaway test, not committed): rtk 1.0.1 and 0.51.0 (aarch64-apple-darwin release tarballs) with the real OpenCode 2.0.25 on PATH. rtk 1.0.1: row not blocked, SetRTK on wrote an 8425-byte plugin with setup(), off took it out. rtk 0.51.0: blocked "OpenCode 2.0.25 needs RTK 0.52 or newer, and this RTK is 0.51.0 …", SetRTK on refused, nothing written. - Real OpenCode 2.0.25 in a sandbox HOME (its own service, stopped after): rtk 1.0.1's plugin logs "loading plugin" with no error; 0.51.0's logs "failed to load plugin … Plugin must export a default definition with an id and an effect or setup function". - TestRTKOpenCode2 rewritten (fake rtk writes each version's real plugin shape). Broken by hand three ways, each a FAIL: old rtk.go (blocked: "RTK doesn't support OpenCode 2 yet …"), stale-plugin rule dropped ("OpenCode 1's plugin under OpenCode 2 is listed as on"), gate at 1.0 ("rtk 0.52.0 blocked for OpenCode 2"). - New GUI test library-rtk-opencode2.test.cjs: every language, 1100 and 420, on and off rows, Chromium and WebKit 21/21 each; red on the old client.js/i18n.js. gui-de, gui-ja, gui-zh-tw, i18n-keys and all library-*.test.cjs: 286/286 in Chromium and in WebKit. - gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/library; go test -tags nogui ./internal/library under a temp HOME with pinned caches, on the rebased head. Full suite: SUITE_LINE
Summary
Refactors
hooks/opencode/rtk.tsto be universally compatible with both OpenCode 2.0 and OpenCode 1.x, fixes compatibility with OpenCode Desktop, and resolves cross-platform path issues on Windows.Closes #3898, Closes #3463, Closes #3326, Closes #2516, Closes #1993.
Problem
{ id, setup }andctx.tool.hook("execute.before", event => ...), replacing the legacy V1 signature.rtk init --opencodeplugin silently does nothing on Desktop ($ is not a function) and on Windows (whichnot found) #3326): OpenCode Desktop runs in an Electron/Node environment where the Bun Shell$helper is undefined, throwingTypeError: $ is not a function.which rtk, which fails on Windows.rtk rewriteexits with status code3on success for advisory rewrites; standard Node child_process callbacks treat non-zero exits as errors, causing rewrites to be discarded.Solution
.idand.setupproperties (for OpenCode 2.0).$withnode:child_process.execFilewith zero external dependencies.stdoutregardless of whetherchild_processflags a non-zero exit code.rtkacrossRTK_BIN,PATH,~/.cargo/bin,~/.local/bin, Homebrew, and WindowsPATHEXT.rtkis missing or times out.Verification
execute.beforefires and mutatesevent.input.command.tool.execute.beforehook functions identically.rtkexits with code3on rewritten rules.