You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat: add opencode v2 plugin support (opencode2) #3463
OpenCode 2.0 (opencode2) ships a new plugin API that is not backward-compatible with v1. The existing hooks/opencode/rtk.ts uses the v1 Plugin async function signature and bun-shell $ helper, neither of which exist in the v2 context.
This PR adds a v2-native plugin at hooks/opencode/rtk-v2.ts and a new --opencode-v2 flag for rtk init.
Changes:
hooks/opencode/rtk-v2.ts — plugin using Plugin.define + ctx.tool.hook('execute.before', ...) with child_process.spawn (v2 doesn't provide $)
--opencode-v2 flag in CLI, mutually exclusive with --opencode
OPENCODE_V2_PLUGIN embedded via include_str! in installer
updated READMEs for both hooks/ and hooks/opencode/
Key difference from v1:rtk rewrite exits non-zero (code 3) even on success, so the v2 plugin uses spawn + stdout capture instead of relying on exit codes. The v1 plugin used .nothrow() from bun-shell which handled this transparently.
PR: umi008/opencode-v2-rtk into rtk-ai/rtk
Reacted by amnesia, Clément Chanchevrier, Mats Estensen, MoonVoid, J-Dagent, AjBoy, Andrew Tec, Valen, Andrew Koltyakov, ergo-coder and 33 more
Adds a v2-native OpenCode plugin (rtk-v2.ts) and --opencode-v2 CLI flag since OpenCode 2.0's plugin API is incompatible with the existing v1 hook; recommend merging as an additive feature.
📁 Relevant files
hooks/opencode/rtk-v2.ts
hooks/opencode/rtk.ts
hooks/opencode/README.md
hooks/README.md
Triaged automatically by wshm · This is an automated analysis, not a human review.
Confirming this is still broken on the current beta, with the exact loader error for reference.
Environment:
opencode2 v0.0.0-beta-19151 (V2 runs as opencode2, side by side with V1 opencode)
rtk 0.48.0
macOS (Darwin)
The V1 plugin at ~/.config/opencode/plugins/rtk.ts (installed with rtk init --opencode) fails on every server start. Log from ~/.local/share/opencode/log/opencode.log:
message="failed to load plugin" target=/Users/<user>/.config/opencode/plugins/rtk.ts cause="Cause([Fail(PluginModule.LoadError: Plugin must export a default definition with an id and an effect or setup function. (cause: SchemaError(Missing key\n at [\"default\"])))])" role=server
The proposed rtk-v2.ts approach in this issue matches the V2 API and fixes the load error on this build:
Two details from testing that support the choices in the PR:
V2 provides no $ bun-shell helper. A spawn-based rtk rewrite call is the right replacement.
V2 hook events carry the tool input on event (for example event.tool, event.input), not the V1 (input, output) signature.
One more data point: the third-party openrtk npm package (v0.1.0, martins/openrtk) hits the same V2 loader error and is unrelated to this repo. Its users need the same V2 shape or a V2 release.
How long do I have to wait for the update? I made a temporary fix, but it’s not working properly; I want an official solution
@4q4r this is an OSS project, "How long do I have to wait for the update" might not be appropriate.
Reacted by Andrew Koltyakov, Paulo Eduardo Rezende, Hélder Correia, AjBoy, J-Dagent, Spencer Brower, Eric Lee, Ole, Nikos Moumoulidis, Aitor Bermejo Ruiz and 7 more
How long do I have to wait for the update? I made a temporary fix, but it’s not working properly; I want an official solution
@4q4r this is an OSS project, "How long do I have to wait for the update" might not be appropriate.
But that's popular OSS and issue is old
Reacted by Spencer Brower, Ole, Nate, Manos Kasimatis, Abdullah, Nikos Moumoulidis, Iseppe, Sebastian Burmester, Aaditya Taparia, Matt Davey and 3 more
Verified against OpenCode 1.18.34 on macOS with rtk 0.51.0 — this approach works, and three details differ in ways worth folding in.
Environment
rtk 0.51.0 (brew), upstream hooks/opencode/rtk.ts byte-identical to what rtk init writes
OpenCode 1.18.34 — TUI/desktop/shared server runs the V2 loader (loading plugin ... role=server)
develop as of 2026-10-03 still contains only README.md + rtk.ts (1339 B) with a single named export — no v2 plugin merged yet
What works
Confirmed from the log, not just from output shape:
spawning process command=/bin/zsh args="[\"-c\",\"rtk ls -la src\"]" cwd=/Users/.../projects/ipa-bot
Bare git status and ls -la src both come back in rtk compact form. rtk gain went from 1.7K to 11.5K tokens saved once the hook fired. OpenCode hot-reloads the plugins directory, so the patch is live ~1s after the file lands — no restart needed.
The patch
+import { spawnSync } from "node:child_process"
import type { Plugin } from "@opencode-ai/plugin"
+const RTK_TIMEOUT_MS = 2000++/** Delegate one command to `rtk rewrite`. Returns undefined when no rule applies. */+function rewriteCommand(command: string): string | undefined {+ try {+ const result = spawnSync("rtk", ["rewrite", command], {+ encoding: "utf8",+ timeout: RTK_TIMEOUT_MS,+ maxBuffer: 1024 * 1024,+ })+ // exit 3 = rule applied (stdout holds the rewritten command)+ // exit 1 = no rule matched (stdout empty). Both non-fatal; only trust stdout.+ const rewritten = (result.stdout ?? "").trim()+ return rewritten && rewritten !== command ? rewritten : undefined+ } catch {+ return undefined // rtk missing or unusable — pass through unchanged+ }+}++async function setup(ctx) {+ await ctx.tool.hook("execute.before", async (event) => {+ const tool = String(event?.tool ?? "").toLowerCase()+ if (tool !== "bash" && tool !== "shell") return+ const input = event?.input+ if (!input || typeof input !== "object") return+ const command = input.command+ if (typeof command !== "string" || !command) return+ const rewritten = rewriteCommand(command)+ if (rewritten) event.input = { ...input, command: rewritten }+ })+}+
// ...existing RtkOpenCodePlugin (V1 `server()`) left untouched below...
-export const RtkOpenCodePlugin: Plugin = async ({ $ }) => {+export const RtkOpenCodePlugin: Plugin = async ({ $ }) => { // still exported for V1+export default { id: "rtk", setup, server: RtkOpenCodePlugin }
Three findings
1. A plain object works — @opencode/plugin is not required at runtime. Plugin.define({...}) needs a resolvable @opencode/plugin. ~/.config/opencode/plugins/ normally has no node_modules, and the generated file's only import is import type { Plugin } from "@opencode-ai/plugin", which TypeScript erases — so the module has no runtime dependency to resolve. A plain { id, setup } object is the more portable form here: @tarquinen/opencode-dcp ships exactly that and the V2 loader accepts it. It also sidesteps the @opencode/plugin vs @opencode-ai/plugin package-name split between the two APIs.
2. Dual export removes the need for a second --opencode-v2 flag.
The V2 loader reads id + setup() and ignores server(). The official docs' "Support V1" section documents keeping both in one default export:
So one file serves both the V1 opencode run CLI and the V2 server. That also overlaps with #4248 (one command shape for every agent).
3. Under V2, reassign event.input — do not mutate the nested field.
The V1 path mutates output.args.command in place. Under V2, event.input = { ...event.input, command: rewritten } is what takes effect; assigning into the existing nested object is not reliable. Easy trap when porting the v1 body verbatim.
Operational notes
The cd <workdir> && prefix OpenCode prepends when a workdir is set is handled correctly by rtk rewrite — e.g. cd /tmp && git status | head -3 becomes cd /tmp && rtk git status | head -3. No special-casing needed.
spawnSync from node:child_process does not show up in OpenCode's process log, because it bypasses the $ instrumentation. Don't use "count the rtk spawns in the log" to decide whether the plugin is live — it's always zero for the v2 path.
rtk rewrite exit codes, for reference: 3 = rule applied, 1 = no rule matched. Both non-fatal; read stdout, ignore the status.
The upgrade trap this would remove
rtk init -g --opencode overwrites ~/.config/opencode/plugins/rtk.ts from the embedded template with no prompt, so any hand-patch is silently lost on every rtk upgrade. Symptom is quiet: commands just run raw again. Shipping the v2 path upstream makes this moot.
Confirming this is still broken on current stable, plus a minimal working V2 port verified end-to-end.
Environment: OpenCode v2.0.27 + rtk 0.51.0 (Homebrew, latest stable). hooks/opencode/rtk.ts on develop is still the V1 template as of today, so rtk init -g --opencode produces a plugin OpenCode 2.x rejects at load time (Plugin must export a default definition with an id and an effect or setup function).
Working V2 port (loads cleanly under 2.0.27 and actually rewrites commands — verified live: a session shell call to grep was rewritten to rtk grep):
import{Plugin}from"@opencode/plugin"exportdefaultPlugin.define({id: "rtk",asyncsetup(ctx){if(!Bun.which("rtk")){console.warn("[rtk] rtk binary not found in PATH — plugin disabled")return}awaitctx.tool.hook("execute.before",async(event)=>{consttool=String(event.tool??"").toLowerCase()if(tool!=="bash"&&tool!=="shell")returnconstinput=event.inputas{command?: unknown}if(typeofinput.command!=="string"||!input.command)returntry{constproc=Bun.spawn(["rtk","rewrite",input.command],{stdout: "pipe",stderr: "ignore",})constrewritten=(awaitnewResponse(proc.stdout).text()).trim()if(rewritten&&rewritten!==input.command){input.command=rewritten}}catch{// pass through unchanged}})},})
Two notes from porting that may help whoever lands #4187:
No child_process needed. OpenCode's server runs plugins under Bun, so Bun.which / Bun.spawn work directly and the port stays dependency-free (the draft patch in this thread uses node:child_process + execFile; fine too, just heavier).
rtk rewrite exit code on 0.51.0 contradicts --help. Help text says "exits 0 and prints the rewritten command", but it actually exits 3 on success (1 with no output when there is no equivalent). Any wrapper that checks exit !== 0 will silently drop every rewrite — keying off stdout instead, as above. Confirms the exit-code observation in OpenCode V2: plugin fails to load (V1 plugin API) and rtk hook opencode is unreleased #4470 against the released 0.51.0.
@opencode/plugin resolution. For a global plugin at ~/.config/opencode/plugins/rtk.ts, the import only resolves if @opencode/plugin is installed in ~/.config/opencode (bun add @opencode/plugin@<matching server version>). Worth mentioning in the install flow so users don't hit Cannot find package '@opencode/plugin'.
Activity
pszymkowiak commentedon Aug 7, 2026
🔍 Automated Triage
featuremediumSummary
Adds a v2-native OpenCode plugin (rtk-v2.ts) and --opencode-v2 CLI flag since OpenCode 2.0's plugin API is incompatible with the existing v1 hook; recommend merging as an additive feature.
📁 Relevant files
hooks/opencode/rtk-v2.tshooks/opencode/rtk.tshooks/opencode/README.mdhooks/README.mdTriaged automatically by wshm · This is an automated analysis, not a human review.
munim commentedon Sep 5, 2026
Confirming this is still broken on the current beta, with the exact loader error for reference.
Environment:
opencode2 v0.0.0-beta-19151(V2 runs asopencode2, side by side with V1opencode)The V1 plugin at
~/.config/opencode/plugins/rtk.ts(installed withrtk init --opencode) fails on every server start. Log from~/.local/share/opencode/log/opencode.log:The proposed
rtk-v2.tsapproach in this issue matches the V2 API and fixes the load error on this build:Two details from testing that support the choices in the PR:
$bun-shell helper. A spawn-basedrtk rewritecall is the right replacement.event(for exampleevent.tool,event.input), not the V1(input, output)signature.One more data point: the third-party
openrtknpm package (v0.1.0,martins/openrtk) hits the same V2 loader error and is unrelated to this repo. Its users need the same V2 shape or a V2 release.sandeep-chaps commentedon Sep 15, 2026
When can we see this supported as our org is testing opencode v2 and plans to deploy it soon.
4q4r commentedon Sep 20, 2026
How long do I have to wait for the update? I made a temporary fix, but it’s not working properly; I want an official solution
generik0 commentedon Sep 21, 2026
@4q4r this is an OSS project, "How long do I have to wait for the update" might not be appropriate.
4q4r commentedon Sep 21, 2026
But that's popular OSS and issue is old
feat: ship Tersio's own OpenCode plugin, closing the last pending host
Move to OpenCode 2 and install Pi with mise (#29)
dylldev commentedon Oct 4, 2026
Verified against OpenCode 1.18.34 on macOS with rtk 0.51.0 — this approach works, and three details differ in ways worth folding in.
Environment
brew), upstreamhooks/opencode/rtk.tsbyte-identical to whatrtk initwritesloading plugin ... role=server)developas of 2026-10-03 still contains onlyREADME.md+rtk.ts(1339 B) with a single named export — no v2 plugin merged yetWhat works
Confirmed from the log, not just from output shape:
Bare
git statusandls -la srcboth come back in rtk compact form.rtk gainwent from 1.7K to 11.5K tokens saved once the hook fired. OpenCode hot-reloads the plugins directory, so the patch is live ~1s after the file lands — no restart needed.The patch
Three findings
1. A plain object works —
@opencode/pluginis not required at runtime.Plugin.define({...})needs a resolvable@opencode/plugin.~/.config/opencode/plugins/normally has nonode_modules, and the generated file's only import isimport type { Plugin } from "@opencode-ai/plugin", which TypeScript erases — so the module has no runtime dependency to resolve. A plain{ id, setup }object is the more portable form here:@tarquinen/opencode-dcpships exactly that and the V2 loader accepts it. It also sidesteps the@opencode/pluginvs@opencode-ai/pluginpackage-name split between the two APIs.2. Dual export removes the need for a second
--opencode-v2flag.The V2 loader reads
id+setup()and ignoresserver(). The official docs' "Support V1" section documents keeping both in one default export:So one file serves both the V1
opencode runCLI and the V2 server. That also overlaps with #4248 (one command shape for every agent).3. Under V2, reassign
event.input— do not mutate the nested field.The V1 path mutates
output.args.commandin place. Under V2,event.input = { ...event.input, command: rewritten }is what takes effect; assigning into the existing nested object is not reliable. Easy trap when porting the v1 body verbatim.Operational notes
cd <workdir> &&prefix OpenCode prepends when a workdir is set is handled correctly byrtk rewrite— e.g.cd /tmp && git status | head -3becomescd /tmp && rtk git status | head -3. No special-casing needed.spawnSyncfromnode:child_processdoes not show up in OpenCode's process log, because it bypasses the$instrumentation. Don't use "count thertkspawns in the log" to decide whether the plugin is live — it's always zero for the v2 path.rtk rewriteexit codes, for reference: 3 = rule applied, 1 = no rule matched. Both non-fatal; read stdout, ignore the status.The upgrade trap this would remove
rtk init -g --opencodeoverwrites~/.config/opencode/plugins/rtk.tsfrom the embedded template with no prompt, so any hand-patch is silently lost on every rtk upgrade. Symptom is quiet: commands just run raw again. Shipping the v2 path upstream makes this moot.feat(opencode): add an rtk plugin for the OpenCode v2 API
geekabhinav commentedon Oct 6, 2026
@dylankirkgirg Thanks! that works with OpenCode v2 and current RTK
rongxianyu commentedon Oct 12, 2026
Confirming this is still broken on current stable, plus a minimal working V2 port verified end-to-end.
Environment: OpenCode
v2.0.27+ rtk0.51.0(Homebrew, latest stable).hooks/opencode/rtk.tsondevelopis still the V1 template as of today, sortk init -g --opencodeproduces a plugin OpenCode 2.x rejects at load time (Plugin must export a default definition with an id and an effect or setup function).Working V2 port (loads cleanly under 2.0.27 and actually rewrites commands — verified live: a session shell call to
grepwas rewritten tortk grep):Two notes from porting that may help whoever lands #4187:
child_processneeded. OpenCode's server runs plugins under Bun, soBun.which/Bun.spawnwork directly and the port stays dependency-free (the draft patch in this thread usesnode:child_process+execFile; fine too, just heavier).rtk rewriteexit code on 0.51.0 contradicts--help. Help text says "exits 0 and prints the rewritten command", but it actually exits 3 on success (1 with no output when there is no equivalent). Any wrapper that checksexit !== 0will silently drop every rewrite — keying off stdout instead, as above. Confirms the exit-code observation in OpenCode V2: plugin fails to load (V1 plugin API) andrtk hook opencodeis unreleased #4470 against the released 0.51.0.@opencode/pluginresolution. For a global plugin at~/.config/opencode/plugins/rtk.ts, the import only resolves if@opencode/pluginis installed in~/.config/opencode(bun add @opencode/plugin@<matching server version>). Worth mentioning in the install flow so users don't hitCannot find package '@opencode/plugin'.Migration reference: https://opencode.ai/v2/docs/build/plugins/migrate-v1
Merge pull request #4187 from amnesiaof/fix/opencode-v2-compatibility