Skip to content

feat: add opencode v2 plugin support (opencode2) #3463

Closed

Description

@umi008

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

Activity

  1. pszymkowiak commented on Aug 7, 2026

    @pszymkowiak
    Collaborator

    wshm · Automated triage by AI

    🔍 Automated Triage

    ✨ Category feature
    🟡 Priority medium
    🎯 Confidence 88%

    Summary

    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.

  2. munim commented on Sep 5, 2026

    @munim

    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:

    export default Plugin.define({
      id: "rtk",
      async setup(ctx) {
        await ctx.tool.hook("execute.before", (event) => { /* rewrite bash commands */ })
      },
    })

    Two details from testing that support the choices in the PR:

    1. V2 provides no $ bun-shell helper. A spawn-based rtk rewrite call is the right replacement.
    2. 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.

  3. sandeep-chaps commented on Sep 15, 2026

    @sandeep-chaps

    When can we see this supported as our org is testing opencode v2 and plans to deploy it soon.

  4. 4q4r commented on Sep 20, 2026

    @4q4r

    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

  5. generik0 commented on Sep 21, 2026

    @generik0

    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.

  6. 4q4r commented on Sep 21, 2026

    @4q4r

    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

  7. dylldev commented on Oct 4, 2026

    @dylldev

    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:

    export default { ...Plugin.define({ id, setup }), async server() { /* v1 hooks */ } }

    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.

  8. geekabhinav commented on Oct 6, 2026

    @geekabhinav

    @dylankirkgirg Thanks! that works with OpenCode v2 and current RTK

  9. rongxianyu commented on Oct 12, 2026

    @rongxianyu

    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"
    
    export default Plugin.define({
      id: "rtk",
      async setup(ctx) {
        if (!Bun.which("rtk")) {
          console.warn("[rtk] rtk binary not found in PATH — plugin disabled")
          return
        }
    
        await ctx.tool.hook("execute.before", async (event) => {
          const tool = String(event.tool ?? "").toLowerCase()
          if (tool !== "bash" && tool !== "shell") return
    
          const input = event.input as { command?: unknown }
          if (typeof input.command !== "string" || !input.command) return
    
          try {
            const proc = Bun.spawn(["rtk", "rewrite", input.command], {
              stdout: "pipe",
              stderr: "ignore",
            })
            const rewritten = (await new Response(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:

    1. 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).
    2. 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.
    3. @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'.

    Migration reference: https://opencode.ai/v2/docs/build/plugins/migrate-v1

  10. added a commit that references this issue on Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions