Skip to content

Port the OpenCode plugin to the opencode v2 plugin API - #27

Merged
winjer merged 3 commits into
mainfrom
port-opencode-plugin-v2
Nov 6, 2026
Merged

winjer merged 3 commits into
mainfrom
port-opencode-plugin-v2

Conversation

@winjer

@winjer winjer commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

User description

Why

opencode v2 rejects the v1 plugin shape — the code-trace plugin fails to load with:

Server plugin error
~/.config/opencode/plugins/code-trace.ts
Plugin must export a default definition with an id and an effect or setup function.

v1 plugin implementations do not run in v2, so this is a port, not a rename. The Rust side also needed the new message shape: without it the plugin loads but the binary silently emits degraded traces (no user text, no tool spans, no token usage).

What changed

plugin/opencode/ is now a v2 plugin directory:

  • index.ts (server part) — Plugin.define + ctx.event.subscribe instead of a returned event hook. session.created (root sessions) still runs --on-start so sessions are recorded (idempotent — the TUI part's own --on-start for the banner is harmless). Exports trigger on session.execution.succeeded/failed/interrupted; opencode v2 does not emit the v1-era session.idle (verified against v2.2.1 — it's kept in the subscription in case a release restores it; the cursor makes a double export a no-op). Because the server runs one plugin instance per location and every instance sees every session's events, exports are gated on the session's directory matching the instance's location — without the gate, N instances race on the cursor file and the same turn is traced N times (observed live while porting).
  • tui.ts (TUI part) — v2 has no server-side tui.showToast; the ENABLED/PAUSED banner toast now lives here. Headless runs show no toast but still record the session.

src/opencode.rs — normalizes opencode v2's flat messages ({type, text/content, model.id, tokens}, tool results inside each tool item's state) into the same Claude-format rows as before, emitting tool results as a user tool_result row. The v1 {info, parts} path is untouched; both shapes can be mixed. 10 new unit tests.

src/setup.rs — embeds and installs both parts as ~/.config/opencode/plugins/code-trace/ and removes the legacy single-file plugin on install (opencode loads it alongside the new directory and its load error masks the ported plugin). New install tests including legacy-removal.

README / AGENTS.md — install instructions and architecture notes updated.

Verification (against opencode v2.2.1, live)

  • Plugin loads: code-trace local {server: true, tui: true} active (the v1 file produced the load error above).
  • Headless opencode run session: recorded in the registry at creation, and exactly one Processed 1 turns per run in code_trace.log after the location gate.
  • Full cargo test (232 tests) and clippy pass.

The banner toast needs a quick manual check in a fresh TUI session (can't drive the TUI from a script).

Notes for reviewers

  • The cursor file (~/.local/share/code-trace/opencode_cursor.json) is unchanged, so upgrading mid-session keeps positions.
  • The installed 0.7.0 binary still emits degraded traces for v2 sessions (its get_role falls back to the top-level type), so nothing got worse while this PR waits — but the normalizer fix is needed for correct traces.
  • After merge: bump + release, then code-trace setup --install-opencode on each machine removes the legacy file and installs the directory (already deployed by hand on doug's machine).

PR Type

Enhancement, Bug fix


Description

  • Port OpenCode plugin to v2 API (server + TUI parts)

  • Normalize opencode v2 flat messages in src/opencode.rs

  • Install plugin directory and remove legacy v1 file

  • Wait briefly for Claude Code transcript at Stop hook


Diagram Walkthrough

flowchart LR
  V1["v1 single-file plugin"] -- "port" --> V2["v2 plugin dir (index.ts + tui.ts)"]
  V2 -- "emits flat messages" --> NORM["src/opencode.rs normalize_v2_message"]
  NORM -- "Claude-format rows" --> TURNS["turns::build_turns"]
  SETUP["src/setup.rs"] -- "installs dir, removes legacy" --> V2
  MAIN["src/main.rs"] -- "wait_for_transcript" --> STOP["Stop hook"]
Loading

File Walkthrough

Relevant files
Bug fix
1 files
main.rs
Wait briefly for transcript at Stop hook                                 
+78/-0   
Enhancement
4 files
opencode.rs
Normalize opencode v2 flat messages into rows                       
+307/-2 
setup.rs
Install plugin directory and remove legacy v1 file             
+110/-15
index.ts
Add v2 server plugin part                                                               
+232/-0 
tui.ts
Add v2 TUI plugin part for banner toast                                   
+113/-0 
Tests
1 files
install_test.rs
Update install tests for plugin directory                               
+36/-9   
Miscellaneous
1 files
code-trace.ts
Remove legacy v1 single-file plugin                                           
+0/-243 
Documentation
3 files
CLAUDE.md
Document opencode v2 plugin directory                                       
+1/-0     
README.md
Update OpenCode install and behavior docs                               
+8/-7     
README.md
Clarify default npmrc empty file                                                 
+2/-2     
Configuration changes
1 files
docker-compose.yml
Use committed empty npmrc default                                               
+6/-2     
Additional files
1 files
npmrc.empty [link]   

opencode v2 rejects the v1 plugin shape ("Plugin must export a default
definition with an id and an effect or setup function"), so the plugin
failed to load on any opencode v2 install. v1 plugin implementations do
not run in v2, so this is a port, not a rename:

plugin/opencode/ is now a v2 plugin directory:
- index.ts (server part) — Plugin.define + ctx.event.subscribe instead of
  a returned event hook. session.created (root sessions) still runs
  `--on-start` to record the session (idempotent, so the TUI part's own
  run for the banner is harmless). Exports now trigger on
  session.execution.succeeded/failed/interrupted: v2 does not emit the
  v1-era session.idle (kept in the subscription in case a release restores
  it; the cursor makes a double export a no-op). The server runs one
  plugin instance per location and every instance sees every session's
  events, so exports are gated on the session's directory matching the
  instance's location — otherwise N instances race on the cursor file and
  the same turn is traced N times (observed live while porting). Messages
  come from ctx.session.context (v2 flat shape) and the version from
  ctx.app. The cursor file is unchanged, so upgrading mid-session keeps
  its position.
- tui.ts (TUI part) — v2 has no server-side tui.showToast; the
  ENABLED/PAUSED banner toast now lives here (context.ui.toast.show on
  session.created, subagents skipped as before). Headless runs show no
  toast but still record the session via the server part.

src/opencode.rs: normalize opencode v2's flat messages ({type, text /
content, model.id, tokens}; tool results inside each tool item's state)
into the same Claude-format rows as the v1 shape, with tool results
emitted as a user tool_result row so turns::build_turns attaches them.
The v1 {info, parts} path is untouched; both shapes can be mixed.

src/setup.rs: embed and install both parts as
~/.config/opencode/plugins/code-trace/ and remove the legacy single-file
plugin on install — opencode loads it alongside the new directory and its
load error masks the ported plugin.

Verified end to end against opencode v2.2.1: plugin loads (server+tui
active), sessions are recorded, and a headless `opencode run` session
exports exactly one turn to the binary.
@isotoma-pr-agent

isotoma-pr-agent Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 3a4b92a)

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Cursor advanced before export

exportSession advances and persists the cursor (cursor[sessionId] = ...; saveCursor(cursor)) immediately after spawning the detached binary, without waiting for it to exit or confirming it succeeded. If the spawn succeeds but the binary fails (e.g. binary missing, non-zero exit, Langfuse error), the messages are permanently skipped because the cursor already moved past them. Since the child is detached and unref'd, there is no way to observe failure. Consider advancing the cursor only after the child exits successfully, or have the binary own the cursor.

try {
  const child = spawn(binPath, [], {
    stdio: ["pipe", "ignore", "ignore"],
    detached: true,
    shell: true,
  });

  child.stdin?.end(JSON.stringify(payload), "utf-8");
  child.unref();
} catch (err) {
  console.error(`code-trace: failed to spawn code-trace: ${err}`);
  return;
}

cursor[sessionId] = { lastIndex: allMessages.length, lastId };
saveCursor(cursor);
Race on cursor file

The location gate reduces but does not eliminate concurrent access: loadCursor/saveCursor do a read-modify-write of the whole opencode_cursor.json with no locking. Two sessions finishing near-simultaneously in the same location (or the TUI/server both touching state) can interleave and one write clobbers the other's cursor entry, causing re-export or skipped turns. The PR description notes N instances racing was observed live; the gate only addresses cross-location, not same-location concurrency.

async function exportSession(ctx: any, sessionId: string, cwd: string): Promise<void> {
  const cursor = loadCursor();
  const prev = cursor[sessionId];
  const startIndex = prev?.lastIndex ?? 0;

  let allMessages: any[];
  try {
    allMessages = await ctx.session.context({ sessionID: sessionId });
  } catch (err) {
    console.error(`code-trace: failed to fetch session messages: ${err}`);
    return;
  }

  if (allMessages.length <= startIndex) return;

  const newMessages = allMessages.slice(startIndex);
  if (newMessages.length === 0) return;

  const lastMsg = newMessages[newMessages.length - 1];
  const lastId = lastMsg?.id ?? String(startIndex + newMessages.length - 1);

  const payload = {
    source: "opencode",
    sessionId,
    cwd,
    messages: newMessages,
    agentVersion: ctx.app.version,
  };

  const binPath = process.env.CODE_TRACE_BIN ?? "code-trace";

  try {
    const child = spawn(binPath, [], {
      stdio: ["pipe", "ignore", "ignore"],
      detached: true,
      shell: true,
    });

    child.stdin?.end(JSON.stringify(payload), "utf-8");
    child.unref();
  } catch (err) {
    console.error(`code-trace: failed to spawn code-trace: ${err}`);
    return;
  }

  cursor[sessionId] = { lastIndex: allMessages.length, lastId };
  saveCursor(cursor);
shell:true with env bin

spawn(binPath, [...], { shell: true }) runs the binary path through a shell. binPath comes from process.env.CODE_TRACE_BIN, so a value containing shell metacharacters would be interpreted by the shell. This is a local env var, so impact is limited, but shell: true is unnecessary here and also changes argument quoting behavior. Prefer shell: false (or execFile) since no shell features are needed.

const child = spawn(binPath, ["--on-start"], {
  stdio: ["pipe", "ignore", "ignore"],
  shell: true,
});

@isotoma-pr-agent

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fall back to instance directory

If ctx.session.get fails or returns no location.directory, cwd stays undefined and
the cwd !== ctx.location.directory check silently skips the export, dropping traces.
Fall back to ctx.location.directory so a transient lookup failure doesn't lose the
export.

plugin/opencode/index.ts [214-222]

 let cwd: string | undefined;
 try {
   const info = await ctx.session.get({ sessionID: sessionId });
   cwd = info?.location?.directory;
 } catch {
   // session lookup is best-effort
 }
+cwd = cwd ?? ctx.location.directory;
 if (cwd !== ctx.location.directory) continue;
-await exportSession(ctx, sessionId, cwd!);
+await exportSession(ctx, sessionId, cwd);
Suggestion importance[1-10]: 7

__

Why: The fallback to ctx.location.directory is logically sound: if ctx.session.get fails, cwd stays undefined and the location gate silently drops the export. This is a plausible trace-loss bug, though the impact is moderate since it only triggers on lookup failure.

Medium
Handle stdin and spawn errors

With detached: true and unref(), the parent may exit before the child reads stdin,
and child.stdin.end() can fail with EPIPE/ECONNRESET (an unhandled error event on
the stream crashes the process). Attach an error handler to child.stdin and the
child before writing.

plugin/opencode/index.ts [150-157]

 const child = spawn(binPath, [], {
   stdio: ["pipe", "ignore", "ignore"],
   detached: true,
   shell: true,
 });
 
+child.on("error", (err) => {
+  console.error(`code-trace: failed to spawn code-trace: ${err}`);
+});
+child.stdin?.on("error", (err) => {
+  console.error(`code-trace: failed to write payload: ${err}`);
+});
 child.stdin?.end(JSON.stringify(payload), "utf-8");
 child.unref();
Suggestion importance[1-10]: 6

__

Why: Adding an error handler on child.stdin and the child is a reasonable robustness improvement, since an unhandled stream error event can crash the process. However, this is defensive error handling rather than a critical bug, and the spawn call is already wrapped in a try/catch.

Low
Avoid unhandled promise rejection

Throwing inside the detached void (async () => {...})() IIFE produces an unhandled
promise rejection, which can crash the opencode server process. Log the error
instead of rethrowing.

plugin/opencode/index.ts [224-227]

 } catch (err) {
   // AbortError is the normal shutdown path (cleanup aborts the stream).
-  if ((err as Error).name !== "AbortError") throw err;
+  if ((err as Error).name !== "AbortError") {
+    console.error(`code-trace: event stream error: ${err}`);
+  }
 }
Suggestion importance[1-10]: 6

__

Why: Rethrowing inside the detached void (async () => {...})() IIFE does produce an unhandled rejection that could crash the server. Logging instead is a valid robustness fix, but it is defensive error handling rather than a core functionality issue.

Low

docker compose's bake integration refuses to read /dev/null without an
explicit fs.read allowance, so CI has failed at `docker compose up` with
"additional privileges requested: pass --allow=fs.read=/dev/null" on
every PR since November (first seen on the dependabot rustls bump —
nothing to do with the PRs themselves). Default the secret to a
committed empty file instead: equivalent for npm, no privilege needed.
Claude Code fires Stop hooks concurrently with writing the session
transcript: the file can be missing when the hook starts and appear a few
hundred milliseconds later. Observed with claude-code 2.1.198 in the
Track 1 harness, where config-file-mode Stop hooks lost the race every
time (scenario b) and env-mode hooks lost it intermittently — the hook
bailed at the transcript existence check and the turn was never traced.

Poll for up to 2s before giving up, before the state lock so concurrent
invocations are not queued behind the wait. All 5 harness scenarios pass
again locally (4/4 config-mode runs emit after the fix).
@isotoma-pr-agent

Copy link
Copy Markdown

Persistent review updated to latest commit 3a4b92a

@winjer

winjer commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Two extra commits after the first CI run (the harness job was failing for reasons unrelated to the port):

harness: default the npmrc build secret to a committed empty file — the harness job has been broken on every PR since early November: docker compose's bake integration refuses to read /dev/null (the default for the optional npmrc build secret) without an explicit fs.read allowance, so docker compose up died in 4s with "additional privileges requested: pass --allow=fs.read=/dev/null". First seen on the dependabot rustls bump, which touches nothing. The secret now defaults to a committed empty file — equivalent for npm, no privilege needed.

claude-code: wait for the transcript to appear in the Stop hook — once the harness could actually run again it exposed a real product bug, not a flake: Claude Code fires Stop hooks concurrently with writing the session transcript, so the file can be missing at hook start and appear a few hundred ms later (claude-code 2.1.198). Config-file-mode hooks lost the race every time (scenario b: 4/4), env-mode hooks intermittently — the binary bailed at the transcript existence check and the turn was never traced. Fixed by polling for up to 2s before giving up (before the state lock, so concurrent invocations don't queue behind the wait). All 5 harness scenarios pass locally now, plus 4/4 config-mode runs emitting; two new unit tests cover the wait.

Both verified locally in the container harness before pushing; test and harness are green on this branch.

@winjer
winjer merged commit a8a734a into main Nov 6, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant