diff --git a/CLAUDE.md b/CLAUDE.md index 7f70e4c..cda52ec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,6 +20,7 @@ This project sends Claude Code and OpenCode session traces to Langfuse for obser - `src/tags.rs` — gathers env tags (repo, org, branch, user, host, os, agent version) - `src/state.rs` — persisted cursor state per session - `src/log.rs` — logging to `~/.local/share/code-trace/` +- `plugin/opencode/` — opencode v2 plugin (server part `index.ts`, TUI part `tui.ts`); embedded into the binary by `src/setup.rs` - `plugin/pi-agent/code-trace.ts` — pi extension ## State location diff --git a/README.md b/README.md index 280ba25..85c47dd 100644 --- a/README.md +++ b/README.md @@ -120,14 +120,15 @@ The install script does this automatically. If not, add to `~/.claude/settings.j #### OpenCode -Copy `plugin/opencode/code-trace.ts` to your OpenCode plugins directory: +Copy the `plugin/opencode` plugin directory into your OpenCode plugins directory (opencode v2 auto-loads plugin directories; the server part is `index.ts` and the TUI part is `tui.ts`): ```bash mkdir -p ~/.config/opencode/plugins/ -cp plugin/opencode/code-trace.ts ~/.config/opencode/plugins/code-trace.ts +cp -r plugin/opencode ~/.config/opencode/plugins/code-trace +rm -f ~/.config/opencode/plugins/code-trace.ts # v1 single-file plugin, if present ``` -Or use the install script with `--opencode` (see above). +Or use the install script with `--opencode` (see above), which installs the directory and removes the v1 file. #### Pi @@ -214,7 +215,7 @@ How each agent surfaces that reminder to the **user** (never to the model): } ``` -- **OpenCode** — the plugin hooks the `session.created` event (root sessions only) and spawns `code-trace --on-start` with an OpenCode-shaped payload. The binary replies with a structured JSON `{ "codeTrace": { "level", "message" } }`, and the plugin renders it as a TUI toast (`warning` when tracing is ENABLED, `info` otherwise). Subagent (Task tool) sessions are filtered out so a delegation doesn't pop a banner. In headless `opencode run` (no TUI) the toast is a no-op. +- **OpenCode** — the plugin (server part) hooks the `session.created` event (root sessions only) and spawns `code-trace --on-start` with an OpenCode-shaped payload, recording the session so the privacy CLI can act on it. The binary replies with a structured JSON `{ "codeTrace": { "level", "message" } }`; the plugin's TUI part renders it as a toast (`warning` when tracing is ENABLED, `info` otherwise). Subagent (Task tool) sessions are filtered out so a delegation doesn't pop a banner. In headless `opencode run` (no TUI) the toast is a no-op, but the session is still recorded. ### Purge @@ -240,11 +241,11 @@ Caveats: deleting the transcript removes the session from Claude Code's `--resum ### OpenCode -1. The OpenCode plugin shows the tracing reminder as a TUI toast when a root session is created (`session.created`) +1. The OpenCode plugin's TUI part shows the tracing reminder as a toast when a root session is created (`session.created`); the server part also runs `--on-start` so the session is recorded even headless 2. The plugin hooks into the `session.idle` event after each assistant response 3. It fetches new messages since the last processed message (tracked per-session in `~/.local/share/code-trace/opencode_cursor.json`) -4. Messages are assembled into turns and piped to the `code-trace` binary over stdin -5. The binary forks — the parent returns immediately, while the child sends the batch to the Langfuse API via HTTP and logs the result +4. Messages (opencode's flat v2 shape) are piped to the `code-trace` binary over stdin +5. The binary normalizes them into turns and forks — the parent returns immediately, while the child sends the batch to the Langfuse API via HTTP and logs the result ### Pi diff --git a/harness/README.md b/harness/README.md index 2b3997c..01dd518 100644 --- a/harness/README.md +++ b/harness/README.md @@ -36,8 +36,8 @@ NPMRC_FILE="$HOME/.npmrc" docker compose -f harness/docker-compose.yml up --buil --exit-code-from runner --abort-on-container-exit ``` -Leave `NPMRC_FILE` unset (the default) where the registry is directly reachable, -such as CI. +Leave `NPMRC_FILE` unset (the default, an empty committed file — `harness/npmrc.empty`) +where the registry is directly reachable, such as CI. ## Run scenarios without Docker diff --git a/harness/docker-compose.yml b/harness/docker-compose.yml index b602069..704c586 100644 --- a/harness/docker-compose.yml +++ b/harness/docker-compose.yml @@ -39,8 +39,12 @@ services: # Optional npm credentials for the image build. NPMRC_FILE points at an ~/.npmrc # to route `npm install` through a private registry on restricted networks; -# unset it (the default empty file) for environments with direct registry +# unset it (the default, an empty file) for environments with direct registry # access, such as CI. Consumed as a BuildKit build secret — see harness/Dockerfile. +# The default is a committed empty file rather than /dev/null: compose's bake +# integration refuses to read /dev/null without an explicit fs.read allowance, +# which broke CI ("additional privileges requested: pass +# --allow=fs.read=/dev/null"). An empty .npmrc is equivalent for npm. secrets: npmrc: - file: ${NPMRC_FILE:-/dev/null} + file: ${NPMRC_FILE:-./npmrc.empty} diff --git a/harness/npmrc.empty b/harness/npmrc.empty new file mode 100644 index 0000000..e69de29 diff --git a/plugin/opencode/code-trace.ts b/plugin/opencode/code-trace.ts deleted file mode 100644 index 0ba4bde..0000000 --- a/plugin/opencode/code-trace.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { spawn } from "node:child_process"; -import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs"; -import { join, dirname } from "node:path"; - -// How long to wait for `--on-start` to print its reminder. The binary takes the -// blocking state flock, so in the worst case (another code-trace process wedged -// on the lock) it must time out rather than stall the plugin's event loop. -const ON_START_TIMEOUT_MS = 3000; - -interface CursorEntry { - lastIndex: number; - lastId: string; -} - -interface CursorStore { - [sessionId: string]: CursorEntry; -} - -function getCursorPath(): string { - const home = process.env.HOME ?? process.env.USERPROFILE ?? "~"; - return join(home, ".local", "share", "code-trace", "opencode_cursor.json"); -} - -function ensureDir(path: string): void { - const dir = dirname(path); - if (!existsSync(dir)) { - mkdirSync(dir, { recursive: true }); - } -} - -function loadCursor(): CursorStore { - const path = getCursorPath(); - try { - if (existsSync(path)) { - return JSON.parse(readFileSync(path, "utf-8")); - } - } catch { - // ignore - } - return {}; -} - -function saveCursor(store: CursorStore): void { - const path = getCursorPath(); - ensureDir(path); - writeFileSync(path, JSON.stringify(store, null, 2)); -} - -function getOpencodeVersion(): string | undefined { - try { - const { execSync } = require("node:child_process"); - const result = execSync("opencode --version", { encoding: "utf-8", timeout: 5000 }); - return result.trim() || undefined; - } catch { - return undefined; - } -} - -/// Run `code-trace --on-start` with an opencode-shaped payload and resolve to -/// its stdout (trimmed), or `null` if the binary is missing, times out, errors, -/// or prints nothing (tracing not configured). The output is a JSON -/// `{ codeTrace: { level, message } }` object; the caller parses it. -function runOnStart(sessionId: string, cwd: string): Promise { - const binPath = process.env.CODE_TRACE_BIN ?? "code-trace"; - const payload = JSON.stringify({ - source: "opencode", - sessionId, - cwd, - }); - - return new Promise((resolve) => { - const child = spawn(binPath, ["--on-start"], { - stdio: ["pipe", "pipe", "pipe"], - shell: true, - }); - - let stdout = ""; - const timer = setTimeout(() => { - child.kill("SIGKILL"); - resolve(null); - }, ON_START_TIMEOUT_MS); - - child.on("error", () => { - clearTimeout(timer); - resolve(null); - }); - - child.stdout?.on("data", (chunk: Buffer) => { - if (stdout.length < 16 * 1024) stdout += chunk.toString("utf-8"); - }); - - child.on("close", (code) => { - clearTimeout(timer); - const trimmed = stdout.trim(); - resolve(code === 0 && trimmed ? trimmed : null); - }); - - child.stdin?.end(payload, "utf-8"); - }); -} - -type CodeTraceNote = { codeTrace?: { level?: string; message?: string } }; - -/// Render the `--on-start` reminder as a TUI toast. No-ops when tracing is not -/// configured (no note) or when no TUI is attached (headless `opencode run`). -async function showBanner(ctx: any, sessionId: string, cwd: string): Promise { - const out = await runOnStart(sessionId, cwd); - if (!out) return; - - let note: CodeTraceNote; - try { - note = JSON.parse(out); - } catch { - await ctx.client.app.log({ - body: { - service: "code-trace", - level: "warn", - message: `unparseable --on-start output: ${out}`, - }, - }); - return; - } - - const message = note.codeTrace?.message; - if (!message) return; - const level = note.codeTrace?.level; - - try { - await ctx.client.tui.showToast({ - body: { - title: "code-trace", - message, - variant: level === "warning" ? "warning" : "info", - }, - }); - } catch (err) { - await ctx.client.app.log({ - body: { - service: "code-trace", - level: "error", - message: `Failed to show tracing banner: ${err}`, - }, - }); - } -} - -async function CodeTracePlugin(ctx: any) { - return { - event: async (input: any) => { - const event = input.event ?? input; - - // Surface the tracing reminder (ENABLED / PAUSED / inactive) to the USER - // as a TUI toast when a root session is created. Subagent sessions fire - // `session.created` too but carry a `parentID` — skip those so a Task - // delegation doesn't pop a banner each time. Resumed sessions fire no - // `session.created`; they fall through to the first idle below. - if (event.type === "session.created") { - const info = event.properties?.info; - const sessionId = info?.id ?? event.properties?.sessionID; - if (!sessionId || info?.parentID) return; - await showBanner(ctx, sessionId, ctx.directory); - return; - } - - if (event.type !== "session.idle") return; - - const sessionId = event.sessionID ?? event.properties?.sessionID; - if (!sessionId) { - await ctx.client.app.log({ - body: { - service: "code-trace", - level: "warn", - message: `session.idle event missing sessionID, keys: ${Object.keys(event).join(",")}`, - }, - }); - return; - } - - const cursor = loadCursor(); - const prev = cursor[sessionId]; - const startIndex = prev?.lastIndex ?? 0; - - let messagesResponse; - try { - messagesResponse = await ctx.client.session.messages({ path: { id: sessionId } }); - } catch (err) { - await ctx.client.app.log({ - body: { - service: "code-trace", - level: "error", - message: `Failed to fetch session messages: ${err}`, - }, - }); - return; - } - - const allMessages = messagesResponse.data; - if (allMessages.length <= startIndex) return; - - const newMessages = allMessages.slice(startIndex); - if (newMessages.length === 0) return; - - const lastMsg = newMessages[newMessages.length - 1]; - const lastId = lastMsg?.info?.id ?? String(startIndex + newMessages.length - 1); - const agentVersion = getOpencodeVersion(); - - const payload = { - source: "opencode", - sessionId, - cwd: ctx.directory, - messages: newMessages, - agentVersion, - }; - - 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) { - await ctx.client.app.log({ - body: { - service: "code-trace", - level: "error", - message: `Failed to spawn code-trace: ${err}`, - }, - }); - return; - } - - cursor[sessionId] = { lastIndex: allMessages.length, lastId }; - saveCursor(cursor); - }, - }; -} - -export default { id: "code-trace", server: CodeTracePlugin }; diff --git a/plugin/opencode/index.ts b/plugin/opencode/index.ts new file mode 100644 index 0000000..3fbd313 --- /dev/null +++ b/plugin/opencode/index.ts @@ -0,0 +1,232 @@ +/** + * code-trace OpenCode plugin — server part (opencode v2 plugin API). + * + * Spawns the code-trace binary from the opencode server: + * + * - `session.created` (root sessions only): runs `code-trace --on-start`, + * which records the session in code-trace's registry. That record is what + * `code-trace pause` and the sessions list operate on, so it must happen + * even headless (`opencode run`), where the TUI part is not loaded. The + * registry write is idempotent, so the TUI part (tui.ts) running + * `--on-start` again for its banner is harmless. + * + * - `session.execution.succeeded` / `failed` / `interrupted`: pipes the + * messages added since the last export to the binary's stdin for + * Langfuse ingestion. (v1 used `session.idle`, which opencode v2 does + * not emit.) + * + * This is the v2 port of the v1 single-file plugin: `Plugin.define` with an + * `ctx.event.subscribe` stream instead of a returned `event` hook, messages + * from `ctx.session.context` instead of `ctx.client.session.messages`, and + * the version from `ctx.app` instead of shelling out to `opencode --version`. + * The on-disk cursor (`~/.local/share/code-trace/opencode_cursor.json`) is + * unchanged, so upgrading the plugin mid-session keeps the cursor position. + * + * The messages are sent in opencode's native (v2 flat) shape; the binary's + * normalizer (`src/opencode.rs`) understands it. + */ + +import { spawn } from "node:child_process"; +import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { Plugin } from "@opencode/plugin"; + +// How long to wait for `--on-start` to finish. The binary takes the blocking +// state flock, so in the worst case (another code-trace process wedged on the +// lock) it must time out rather than stall the plugin's event loop. +const ON_START_TIMEOUT_MS = 3000; + +interface CursorEntry { + lastIndex: number; + lastId: string; +} + +interface CursorStore { + [sessionId: string]: CursorEntry; +} + +function getCursorPath(): string { + const home = process.env.HOME ?? process.env.USERPROFILE ?? "~"; + return join(home, ".local", "share", "code-trace", "opencode_cursor.json"); +} + +function ensureDir(path: string): void { + const dir = dirname(path); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } +} + +function loadCursor(): CursorStore { + const path = getCursorPath(); + try { + if (existsSync(path)) { + return JSON.parse(readFileSync(path, "utf-8")); + } + } catch { + // ignore + } + return {}; +} + +function saveCursor(store: CursorStore): void { + const path = getCursorPath(); + ensureDir(path); + writeFileSync(path, JSON.stringify(store, null, 2)); +} + +/// Run `code-trace --on-start` with an opencode-shaped payload and resolve +/// once the binary exits (its stdout is not needed here — the TUI part shows +/// the reminder). Resolves even when the binary is missing, times out, or +/// errors: recording a session is best-effort. +function runOnStart(sessionId: string, cwd: string): Promise { + const binPath = process.env.CODE_TRACE_BIN ?? "code-trace"; + const payload = JSON.stringify({ + source: "opencode", + sessionId, + cwd, + }); + + return new Promise((resolve) => { + const child = spawn(binPath, ["--on-start"], { + stdio: ["pipe", "ignore", "ignore"], + shell: true, + }); + + const timer = setTimeout(() => { + child.kill("SIGKILL"); + resolve(); + }, ON_START_TIMEOUT_MS); + + child.on("error", () => { + clearTimeout(timer); + resolve(); + }); + + child.on("close", () => { + clearTimeout(timer); + resolve(); + }); + + child.stdin?.end(payload, "utf-8"); + }); +} + +/// Fetch the session's messages, send the ones past the cursor to code-trace, +/// and advance the cursor. Errors are reported on the server process's stderr +/// and swallowed: a failed export must not disturb the session. +async function exportSession(ctx: any, sessionId: string, cwd: string): Promise { + 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); +} + +export default Plugin.define({ + id: "code-trace", + setup(ctx: any) { + const controller = new AbortController(); + + void (async () => { + try { + for await (const event of ctx.event.subscribe({ + types: [ + "session.created", + // A run finishing (successfully, failed, or interrupted) is the + // v2 signal that new messages may need exporting. v1 used + // session.idle, which opencode v2 does not emit; it is kept in + // the list in case a release restores it — the cursor makes a + // double export a no-op. + "session.execution.succeeded", + "session.execution.failed", + "session.execution.interrupted", + "session.idle", + ], + signal: controller.signal, + })) { + // Record root sessions at creation (subagent sessions carry a + // parentID and are skipped — same filter as the v1 banner). Resumed + // sessions fire no session.created; they fall through to the + // execution events. Not location-gated: recording is idempotent, + // and the session's own location instance may not be subscribed + // yet when the very first session in a fresh directory is created. + if (event.type === "session.created") { + const info = event.data ?? {}; + if (!info.sessionID || info.parentID) continue; + const cwd = info.location?.directory ?? ctx.location.directory; + await runOnStart(info.sessionID, cwd); + continue; + } + + // Execution finished: export everything added since the last + // export. The server runs one plugin instance per location, and + // every instance receives every session's events, so exports are + // gated on the session belonging to this instance's location — + // otherwise N instances race on the cursor file and the same turn + // is traced N times. + const sessionId = event.data?.sessionID; + if (!sessionId) { + console.error(`code-trace: ${event.type} event missing sessionID`); + continue; + } + let cwd: string | undefined; + try { + const info = await ctx.session.get({ sessionID: sessionId }); + cwd = info?.location?.directory; + } catch { + // session lookup is best-effort + } + if (cwd !== ctx.location.directory) continue; + await exportSession(ctx, sessionId, cwd!); + } + } catch (err) { + // AbortError is the normal shutdown path (cleanup aborts the stream). + if ((err as Error).name !== "AbortError") throw err; + } + })(); + + return () => controller.abort(); + }, +}); diff --git a/plugin/opencode/tui.ts b/plugin/opencode/tui.ts new file mode 100644 index 0000000..1cb31b6 --- /dev/null +++ b/plugin/opencode/tui.ts @@ -0,0 +1,113 @@ +/** + * code-trace OpenCode plugin — TUI part (opencode v2 plugin API). + * + * Shows the code-trace tracing reminder (ENABLED / PAUSED / inactive) as a + * toast when a root session is created. The v1 plugin did this from the + * server part via `client.tui.showToast`, which no longer exists in v2; the + * v2 TUI part owns toasts (`context.ui.toast.show`). + * + * This runs `code-trace --on-start` itself and parses the JSON + * `{ codeTrace: { level, message } }` reply. The server part (index.ts) runs + * the same command to record the session; the registry write is idempotent, + * so running it twice is harmless. Only this part needs the output. + * + * Subagent sessions fire `session.created` too but carry a `parentID` — + * skip those so a Task delegation doesn't pop a banner each time. + */ + +import { spawn } from "node:child_process"; +import { Plugin } from "@opencode/plugin/tui"; + +// How long to wait for `--on-start` to print its reminder. The binary takes +// the blocking state flock, so in the worst case (another code-trace process +// wedged on the lock) it must time out rather than stall the TUI. +const ON_START_TIMEOUT_MS = 3000; + +type CodeTraceNote = { codeTrace?: { level?: string; message?: string } }; + +/// Run `code-trace --on-start` with an opencode-shaped payload and resolve to +/// its stdout (trimmed), or `null` if the binary is missing, times out, +/// errors, or prints nothing (tracing not configured). +function runOnStart(sessionId: string, cwd: string): Promise { + const binPath = process.env.CODE_TRACE_BIN ?? "code-trace"; + const payload = JSON.stringify({ + source: "opencode", + sessionId, + cwd, + }); + + return new Promise((resolve) => { + const child = spawn(binPath, ["--on-start"], { + stdio: ["pipe", "pipe", "pipe"], + shell: true, + }); + + let stdout = ""; + const timer = setTimeout(() => { + child.kill("SIGKILL"); + resolve(null); + }, ON_START_TIMEOUT_MS); + + child.on("error", () => { + clearTimeout(timer); + resolve(null); + }); + + child.stdout?.on("data", (chunk: Buffer) => { + if (stdout.length < 16 * 1024) stdout += chunk.toString("utf-8"); + }); + + child.on("close", (code) => { + clearTimeout(timer); + const trimmed = stdout.trim(); + resolve(code === 0 && trimmed ? trimmed : null); + }); + + child.stdin?.end(payload, "utf-8"); + }); +} + +/// Fetch the reminder and render it as a toast. No-ops when tracing is not +/// configured (no note) or the output is unparseable. +async function showBanner(context: any, sessionId: string, cwd: string): Promise { + const out = await runOnStart(sessionId, cwd); + if (!out) return; + + let note: CodeTraceNote; + try { + note = JSON.parse(out); + } catch { + console.error(`code-trace: unparseable --on-start output: ${out}`); + return; + } + + const message = note.codeTrace?.message; + if (!message) return; + const level = note.codeTrace?.level; + + try { + context.ui.toast.show({ + title: "code-trace", + message, + variant: level === "warning" ? "warning" : "info", + }); + } catch (err) { + console.error(`code-trace: failed to show tracing banner: ${err}`); + } +} + +export default Plugin.define({ + id: "code-trace.tui", + setup(context: any) { + const stop = context.data.on("session.created", (event: any) => { + const info = event.data ?? {}; + if (!info.sessionID || info.parentID) return; + const cwd = + info.location?.directory ?? + context.location?.directory ?? + context.data.location.default().directory; + void showBanner(context, info.sessionID, cwd); + }); + return stop; + }, +}); diff --git a/src/main.rs b/src/main.rs index 6aa7477..db29c3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,33 @@ use code_trace::{cli, config, emit, langfuse, log, opencode, payload, pi_agent, setup, state, tags, transcript, turns}; use std::time::Instant; +/// How long a Stop hook waits for the session transcript to appear before +/// giving up. Claude Code writes the transcript concurrently with firing +/// Stop hooks, so the file can be missing at hook start (observed with +/// claude-code 2.1.198); two seconds covers the write without approaching +/// Claude Code's hook timeout. +const TRANSCRIPT_WAIT_MS: u64 = 2000; + +/// Block until `path` exists or the wait budget runs out. No-op when the +/// file is already there. Returns true when the file exists on return. +fn wait_for_transcript(path: &std::path::Path) -> bool { + if path.exists() { + return true; + } + log::debug(&format!( + "transcript {} not present at hook start; waiting up to {TRANSCRIPT_WAIT_MS}ms", + path.display() + )); + let start = Instant::now(); + while start.elapsed().as_millis() < TRANSCRIPT_WAIT_MS as u128 { + std::thread::sleep(std::time::Duration::from_millis(25)); + if path.exists() { + return true; + } + } + false +} + /// Turns to skip when a session is seen for the first time (no cursor yet): /// everything before the turn that fired this hook predates code-trace /// seeing the session — pre-install/pre-enable history is never emitted. @@ -59,6 +86,16 @@ fn run() -> i32 { let cwd = input.cwd().map(String::from); + // Claude Code fires Stop hooks concurrently with writing the session + // transcript: the file may not exist yet when the hook starts and can + // appear a few hundred milliseconds later (observed with claude-code + // 2.1.198 in the Track 1 harness, where config-file-mode hooks lost the + // race every time). Poll briefly rather than drop the turn — before the + // state lock, so concurrent invocations are not queued behind the wait. + if let Some(transcript_path) = input.transcript_path() { + wait_for_transcript(transcript_path); + } + // Optional restriction (on by default): only trace sessions whose working // directory is inside a git repository. Early-return style — no session // recorded, no cursor advanced; first-contact-skip handles a later move @@ -322,3 +359,44 @@ fn main() { }; std::process::exit(code); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wait_for_transcript_returns_immediately_when_file_exists() { + let dir = std::env::temp_dir().join(format!("code-trace-wait-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.jsonl"); + std::fs::write(&path, "x").unwrap(); + let start = Instant::now(); + assert!(wait_for_transcript(&path)); + assert!(start.elapsed().as_millis() < 100, "existing file must not wait"); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn wait_for_transcript_picks_up_file_appearing_mid_wait() { + let dir = std::env::temp_dir().join(format!("code-trace-wait2-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("late.jsonl"); + let _ = std::fs::remove_file(&path); + + // Simulate Claude Code writing the transcript mid-wait. + let p = path.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(100)); + std::fs::write(&p, "x").ok(); + }); + + let start = Instant::now(); + assert!(wait_for_transcript(&path)); + // It must not have burned the whole budget — the file appeared at ~100ms. + assert!( + start.elapsed().as_millis() < TRANSCRIPT_WAIT_MS as u128, + "wait must end when the file appears, not after the full budget" + ); + std::fs::remove_dir_all(&dir).ok(); + } +} diff --git a/src/opencode.rs b/src/opencode.rs index 72a4809..9b4e159 100644 --- a/src/opencode.rs +++ b/src/opencode.rs @@ -7,6 +7,14 @@ pub fn normalize_opencode_messages(messages: Vec) -> Vec { let mut pending_assistant_idx: Option = None; for msg in messages { + // opencode v2's plugin sends flat messages ({type, text/content, + // model, tokens}); v1 sent {info, parts}. Both normalize to the same + // Claude-format rows. + if is_v2_flat(&msg) { + normalize_v2_message(msg, &mut result); + continue; + } + let role = get_opencode_role(&msg); let parts = get_opencode_parts(&msg); @@ -197,12 +205,138 @@ fn get_opencode_parts(msg: &Value) -> Vec { .unwrap_or_default() } -/// Pull token usage out of an OpenCode assistant info block and translate it +/// opencode v2 flat message: role at the top level (`type`), no `info`/`parts` +/// wrapper. The v1 shape always has `info`; the normalized output rows are +/// never fed back through this function. +fn is_v2_flat(msg: &Value) -> bool { + (msg.get("info").is_none() && msg.get("parts").is_none()) + && matches!( + msg.get("type").and_then(|v| v.as_str()), + Some("user") | Some("assistant") + ) +} + +/// Normalize one opencode v2 flat message. User messages carry `text`; +/// assistant messages carry `content` items (`text`, `tool`, `reasoning`), +/// with each tool's result inside the tool item's `state` (`content` when +/// completed, `error` when failed). Emits the same Claude-format rows as the +/// v1 path: a user row, an assistant row, and — when the assistant called +/// tools — a user tool_result row so turns::build_turns attaches the outputs +/// to the pending turn. Anything else (synthetic, system, shell, skill, +/// compaction rows) is not part of a turn and is skipped. +fn normalize_v2_message(msg: Value, result: &mut Vec) { + let msg_type = msg.get("type").and_then(|v| v.as_str()); + match msg_type { + Some("user") => { + let text = msg.get("text").and_then(|v| v.as_str()).unwrap_or(""); + if text.is_empty() { + return; + } + result.push(json!({ + "type": "user", + "message": { "role": "user", "content": [{ "type": "text", "text": text }] }, + })); + } + Some("assistant") => { + let id = msg + .get("id") + .and_then(|v| v.as_str()) + .map(String::from) + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + // v2 model ref: {id, providerID, variant} + let model = msg + .get("model") + .and_then(|m| m.get("id")) + .and_then(|v| v.as_str()) + .unwrap_or("opencode"); + + let mut content_parts: Vec = Vec::new(); + let mut tool_results: Vec = Vec::new(); + let items = msg + .get("content") + .and_then(|v| v.as_array()) + .map(|a| a.as_slice()) + .unwrap_or(&[]); + for item in items { + let item_type = item.get("type").and_then(|v| v.as_str()); + match item_type { + Some("text") => { + let text = item.get("text").and_then(|v| v.as_str()).unwrap_or(""); + content_parts.push(json!({ "type": "text", "text": text })); + } + Some("tool") => { + let tool_id = item.get("id").and_then(|v| v.as_str()).unwrap_or(""); + let tool_name = item.get("name").and_then(|v| v.as_str()).unwrap_or("unknown"); + let input = item + .get("state") + .and_then(|s| s.get("input")) + .cloned() + .unwrap_or(json!({})); + content_parts.push(json!({ + "type": "tool_use", + "id": tool_id, + "name": tool_name, + "input": input, + })); + // v2 carries the result inside the tool item's state. + if let Some(state) = item.get("state") { + let status = state.get("status").and_then(|v| v.as_str()); + let content = match status { + Some("completed") => state.get("content").cloned(), + Some("error") => state + .get("error") + .cloned() + .or_else(|| state.get("content").cloned()), + _ => None, // pending/running: nothing exported yet + }; + if let Some(content) = content { + tool_results.push(json!({ + "type": "tool_result", + "tool_use_id": tool_id, + "content": content, + })); + } + } + } + _ => {} // reasoning and future item types: nothing to emit + } + } + + // v2 carries token usage at the top level (`tokens`); the legacy + // extractor already reads `.tokens`, so pass the message. + let usage = extract_opencode_usage(&msg); + let mut message = serde_json::Map::new(); + message.insert("id".to_string(), json!(id)); + message.insert("role".to_string(), json!("assistant")); + message.insert("model".to_string(), json!(model)); + message.insert("content".to_string(), json!(content_parts)); + if let Some(u) = usage { + message.insert("usage".to_string(), u); + } + result.push(json!({ + "type": "assistant", + "message": Value::Object(message), + })); + + if !tool_results.is_empty() { + result.push(json!({ + "type": "user", + "message": { "role": "user", "content": tool_results }, + })); + } + } + _ => {} + } +} + +/// Pull token usage out of an OpenCode assistant message and translate it /// to the `message.usage` shape `transcript::get_usage` consumes. Returns /// None when no tokens block is present, so emit.rs omits usageDetails /// rather than pricing the generation at $0. /// -/// Handles both v2 (`info.tokens`) and v1 (`info.metadata.assistant.tokens`). +/// Handles the flat opencode v2 message (`tokens` at the top level, passed +/// as the whole message), the intermediate shape (`info.tokens`), and v1 +/// (`info.metadata.assistant.tokens`). fn extract_opencode_usage(info: &Value) -> Option { let tokens = info .get("tokens") @@ -369,4 +503,175 @@ mod tests { assert_eq!(tool_results[0]["tool_use_id"], "tu1"); assert_eq!(tool_results[0]["content"], "file1.txt"); } + + // --- opencode v2 flat messages ({type, text/content, model, tokens}) --- + + #[test] + fn v2_normalizes_user_message_text() { + let msgs = vec![json!({ + "id": "msg1", "type": "user", "text": "Hello", + "time": { "created": 1 } + })]; + let normalized = normalize_opencode_messages(msgs); + assert_eq!(normalized.len(), 1); + assert_eq!(normalized[0]["type"], "user"); + assert_eq!(normalized[0]["message"]["role"], "user"); + assert_eq!(normalized[0]["message"]["content"][0]["text"], "Hello"); + } + + #[test] + fn v2_skips_empty_user_message() { + let msgs = vec![json!({ "id": "msg1", "type": "user", "text": "" })]; + let normalized = normalize_opencode_messages(msgs); + assert!(normalized.is_empty()); + } + + #[test] + fn v2_normalizes_assistant_text_and_model() { + let msgs = vec![json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude-opus-4-1", "providerID": "anthropic" }, + "content": [{ "type": "text", "text": "hi" }] + })]; + let normalized = normalize_opencode_messages(msgs); + assert_eq!(normalized.len(), 1); + assert_eq!(normalized[0]["type"], "assistant"); + assert_eq!(normalized[0]["message"]["model"], "claude-opus-4-1"); + assert_eq!(normalized[0]["message"]["content"][0]["text"], "hi"); + } + + #[test] + fn v2_skips_reasoning_items() { + let msgs = vec![json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude" }, + "content": [ + { "type": "reasoning", "text": "thinking..." }, + { "type": "text", "text": "hi" } + ] + })]; + let normalized = normalize_opencode_messages(msgs); + let content = normalized[0]["message"]["content"].as_array().unwrap(); + assert_eq!(content.len(), 1); + assert_eq!(content[0]["type"], "text"); + } + + #[test] + fn v2_tool_item_becomes_tool_use_and_result_row() { + let msgs = vec![json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude" }, + "content": [ + { "type": "text", "text": "Let me check" }, + { + "type": "tool", "id": "toolu_1", "name": "read", + "state": { + "status": "completed", + "input": { "path": "/tmp/x" }, + "content": [{ "type": "text", "text": "file contents" }] + } + } + ] + })]; + let normalized = normalize_opencode_messages(msgs); + assert_eq!(normalized.len(), 2); + + let assistant = &normalized[0]; + let content = assistant["message"]["content"].as_array().unwrap(); + assert_eq!(content[1]["type"], "tool_use"); + assert_eq!(content[1]["id"], "toolu_1"); + assert_eq!(content[1]["name"], "read"); + assert_eq!(content[1]["input"]["path"], "/tmp/x"); + + // The result rides in a user tool_result row after the assistant. + let result_row = &normalized[1]; + assert_eq!(result_row["type"], "user"); + let tr = &result_row["message"]["content"][0]; + assert_eq!(tr["type"], "tool_result"); + assert_eq!(tr["tool_use_id"], "toolu_1"); + assert_eq!(tr["content"][0]["text"], "file contents"); + } + + #[test] + fn v2_failed_tool_exports_error_as_result() { + let msgs = vec![json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude" }, + "content": [{ + "type": "tool", "id": "toolu_1", "name": "bash", + "state": { "status": "error", "input": {}, "error": "boom" } + }] + })]; + let normalized = normalize_opencode_messages(msgs); + assert_eq!(normalized.len(), 2); + let tr = &normalized[1]["message"]["content"][0]; + assert_eq!(tr["tool_use_id"], "toolu_1"); + assert_eq!(tr["content"], "boom"); + } + + #[test] + fn v2_running_tool_exports_no_result_yet() { + let msgs = vec![json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude" }, + "content": [{ + "type": "tool", "id": "toolu_1", "name": "bash", + "state": { "status": "running", "input": {} } + }] + })]; + let normalized = normalize_opencode_messages(msgs); + // assistant row only, no tool_result row + assert_eq!(normalized.len(), 1); + } + + #[test] + fn v2_extracts_top_level_tokens_into_usage() { + let msgs = vec![json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude" }, + "content": [{ "type": "text", "text": "hi" }], + "tokens": { "input": 100, "output": 50, "reasoning": 7, "cache": { "read": 10, "write": 20 } } + })]; + let normalized = normalize_opencode_messages(msgs); + let usage = &normalized[0]["message"]["usage"]; + assert_eq!(usage["input_tokens"], 100); + assert_eq!(usage["output_tokens"], 50); + assert_eq!(usage["cache_read_input_tokens"], 10); + assert_eq!(usage["cache_creation_input_tokens"], 20); + assert_eq!(usage["reasoning_tokens"], 7); + } + + #[test] + fn v2_non_turn_message_types_pass_through_untouched() { + // Like the v1 path, messages that are neither user nor assistant + // (system, compaction, synthetic, ...) are passed through raw; + // turns::build_turns ignores them. + let msgs = vec![ + json!({ "id": "m1", "type": "system", "text": "system note" }), + json!({ "id": "m2", "type": "compaction", "summary": "summarized" }), + ]; + let normalized = normalize_opencode_messages(msgs); + assert_eq!(normalized.len(), 2); + assert_eq!(normalized[0]["type"], "system"); + assert_eq!(normalized[1]["type"], "compaction"); + } + + #[test] + fn v2_and_v1_messages_can_be_mixed() { + let msgs = vec![ + json!({ + "info": { "id": "msg1", "role": "user" }, + "parts": [{ "type": "text", "text": "legacy" }] + }), + json!({ + "id": "msg2", "type": "assistant", + "model": { "id": "claude" }, + "content": [{ "type": "text", "text": "flat" }] + }), + ]; + let normalized = normalize_opencode_messages(msgs); + assert_eq!(normalized.len(), 2); + assert_eq!(normalized[0]["message"]["content"][0]["text"], "legacy"); + assert_eq!(normalized[1]["message"]["content"][0]["text"], "flat"); + } } diff --git a/src/setup.rs b/src/setup.rs index 7fb389f..41156cb 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -209,11 +209,23 @@ fn with_appended_user_id(existing: &str, email: &str) -> String { // The agent plugin/extension sources are baked into the binary, so plugin // install works even under `curl | bash`, where there is no local checkout to -// copy from. -const OPENCODE_PLUGIN: &str = include_str!("../plugin/opencode/code-trace.ts"); +// copy from. The opencode plugin is an opencode v2 plugin *directory*: the +// server part (index.ts) plus the TUI part (tui.ts) that shows the tracing +// banner as a toast. +const OPENCODE_PLUGIN_SERVER: &str = include_str!("../plugin/opencode/index.ts"); +const OPENCODE_PLUGIN_TUI: &str = include_str!("../plugin/opencode/tui.ts"); const PI_EXTENSION: &str = include_str!("../plugin/pi-agent/code-trace.ts"); -fn opencode_plugin_path(home: &Path) -> PathBuf { +/// The opencode v2 plugin directory, auto-loaded by opencode at startup. +fn opencode_plugin_dir(home: &Path) -> PathBuf { + home.join(".config/opencode/plugins/code-trace") +} + +/// The v1 single-file plugin this installer used to write. Removed on +/// install: opencode still loads it alongside the new directory, and the v1 +/// export shape fails on opencode v2 with "Plugin must export a default +/// definition with an id and an effect or setup function". +fn opencode_legacy_plugin_path(home: &Path) -> PathBuf { home.join(".config/opencode/plugins/code-trace.ts") } @@ -407,6 +419,56 @@ fn install_if_detected( } } +/// Install the opencode plugin directory (server + TUI parts) and remove the +/// legacy v1 single-file plugin. Same detection/consent rules as +/// install_if_detected; returns a process exit code (0 = success/skipped). +fn install_opencode_plugin(force: bool, detected: bool, home: &Path) -> i32 { + if !force && !detected { + return 0; + } + + if detected { + println!(); + println!("OpenCode detected — installing the code-trace plugin."); + println!(" {}", opencode_plugin_dir(home).display()); + } + + let dir = opencode_plugin_dir(home); + let mut failed = false; + for (name, contents) in [ + ("index.ts", OPENCODE_PLUGIN_SERVER), + ("tui.ts", OPENCODE_PLUGIN_TUI), + ] { + if let Err(msg) = install_plugin(&dir.join(name), contents) { + eprintln!("{msg}"); + failed = true; + } + } + + // A leftover v1 plugin file fails to load on opencode v2 and its error + // masks the ported plugin, so remove it even if the fresh install + // failed partway. + let legacy = opencode_legacy_plugin_path(home); + if legacy.is_file() { + match std::fs::remove_file(&legacy) { + Ok(()) => println!("Removed legacy OpenCode plugin {}", legacy.display()), + Err(e) => { + eprintln!("could not remove {}: {e}", legacy.display()); + failed = true; + } + } + } + + if !failed { + println!("Installed OpenCode plugin to {}", dir.display()); + } + if failed { + 1 + } else { + 0 + } +} + /// `code-trace setup` entry point. `args` is everything after `setup`. pub fn run(args: &[String]) -> i32 { let mut register = false; @@ -493,14 +555,7 @@ pub fn run(args: &[String]) -> i32 { } if install_opencode || offer_opencode { - code |= install_if_detected( - install_opencode, - opencode_detected(&home), - &opencode_plugin_path(&home), - OPENCODE_PLUGIN, - "OpenCode detected — installing the code-trace plugin.", - "Installed OpenCode plugin to", - ); + code |= install_opencode_plugin(install_opencode, opencode_detected(&home), &home); } if install_pi || offer_pi { @@ -808,16 +863,22 @@ mod tests { #[test] fn embedded_plugin_sources_are_present() { - assert!(!OPENCODE_PLUGIN.is_empty()); + assert!(!OPENCODE_PLUGIN_SERVER.is_empty()); + assert!(!OPENCODE_PLUGIN_TUI.is_empty()); assert!(!PI_EXTENSION.is_empty()); - assert!(OPENCODE_PLUGIN.contains("code-trace")); + assert!(OPENCODE_PLUGIN_SERVER.contains("code-trace")); + assert!(OPENCODE_PLUGIN_TUI.contains("code-trace")); assert!(PI_EXTENSION.contains("code-trace")); } #[test] fn plugin_paths_are_under_home() { assert_eq!( - opencode_plugin_path(Path::new("/home/x")), + opencode_plugin_dir(Path::new("/home/x")), + Path::new("/home/x/.config/opencode/plugins/code-trace") + ); + assert_eq!( + opencode_legacy_plugin_path(Path::new("/home/x")), Path::new("/home/x/.config/opencode/plugins/code-trace.ts") ); assert_eq!( @@ -845,8 +906,42 @@ mod tests { #[test] fn install_plugin_creates_parents_and_writes_contents() { let home = temp_home("install"); - let target = home.join(".config/opencode/plugins/code-trace.ts"); + let target = home.join(".config/opencode/plugins/code-trace/index.ts"); install_plugin(&target, "hello world").unwrap(); assert_eq!(std::fs::read_to_string(&target).unwrap(), "hello world"); } + + #[test] + fn install_opencode_plugin_writes_both_parts_and_removes_legacy_file() { + let home = temp_home("install-oc"); + // Simulate a v1-era install: the legacy single-file plugin exists. + let legacy = opencode_legacy_plugin_path(&home); + install_plugin(&legacy, "// v1 plugin").unwrap(); + assert!(legacy.is_file()); + + // force = true, so detection is not required. + assert_eq!(install_opencode_plugin(true, false, &home), 0); + + let dir = opencode_plugin_dir(&home); + assert!(dir.join("index.ts").is_file()); + assert!(dir.join("tui.ts").is_file()); + assert_eq!( + std::fs::read_to_string(dir.join("index.ts")).unwrap(), + OPENCODE_PLUGIN_SERVER + ); + assert_eq!( + std::fs::read_to_string(dir.join("tui.ts")).unwrap(), + OPENCODE_PLUGIN_TUI + ); + // The v1 file must be gone or opencode v2 keeps reporting the load + // error for it. + assert!(!legacy.exists()); + } + + #[test] + fn install_opencode_plugin_skips_when_not_detected_and_not_forced() { + let home = temp_home("install-oc-skip"); + assert_eq!(install_opencode_plugin(false, false, &home), 0); + assert!(!opencode_plugin_dir(&home).join("index.ts").exists()); + } } diff --git a/tests/install_test.rs b/tests/install_test.rs index e3ac18f..55e6691 100644 --- a/tests/install_test.rs +++ b/tests/install_test.rs @@ -278,14 +278,34 @@ fn repo_file(rel: &str) -> String { fn install_opencode_writes_embedded_plugin() { let home = scratch("oc-install"); assert!(setup_with_home(&home, &["--install-opencode"]).status.success()); - let installed = home.join(".config/opencode/plugins/code-trace.ts"); + let dir = home.join(".config/opencode/plugins/code-trace"); assert_eq!( - std::fs::read_to_string(&installed).unwrap(), - repo_file("plugin/opencode/code-trace.ts"), - "installed plugin must match the repo source embedded in the binary" + std::fs::read_to_string(dir.join("index.ts")).unwrap(), + repo_file("plugin/opencode/index.ts"), + "installed server part must match the repo source embedded in the binary" + ); + assert_eq!( + std::fs::read_to_string(dir.join("tui.ts")).unwrap(), + repo_file("plugin/opencode/tui.ts"), + "installed TUI part must match the repo source embedded in the binary" ); } +#[test] +fn install_opencode_removes_legacy_v1_plugin_file() { + // A v1-era install left the single-file plugin behind; opencode v2 + // refuses to load it and reports the error, so setup must remove it. + let home = scratch("oc-install-legacy"); + let legacy = home.join(".config/opencode/plugins/code-trace.ts"); + std::fs::create_dir_all(legacy.parent().unwrap()).unwrap(); + std::fs::write(&legacy, "// v1 plugin").unwrap(); + assert!(setup_with_home(&home, &["--install-opencode"]).status.success()); + assert!(!legacy.exists(), "legacy v1 plugin file must be removed"); + assert!(home + .join(".config/opencode/plugins/code-trace/index.ts") + .exists()); +} + #[test] fn install_pi_writes_embedded_extension() { let home = scratch("pi-install"); @@ -302,7 +322,9 @@ fn offer_opencode_skips_when_not_detected() { let home = scratch("oc-offer-absent"); assert!(setup_with_home(&home, &["--offer-opencode"]).status.success()); assert!( - !home.join(".config/opencode/plugins/code-trace.ts").exists(), + !home + .join(".config/opencode/plugins/code-trace/index.ts") + .exists(), "must not install when OpenCode is not detected (no prompt)" ); } @@ -316,13 +338,18 @@ fn offer_opencode_installs_when_detected_without_prompt() { let home = scratch("oc-offer-present"); std::fs::create_dir_all(home.join(".config/opencode")).unwrap(); assert!(setup_with_home(&home, &["--offer-opencode"]).status.success()); - let installed = home.join(".config/opencode/plugins/code-trace.ts"); - assert!(installed.exists(), "must install when OpenCode is detected"); + let dir = home.join(".config/opencode/plugins/code-trace"); + assert!(dir.join("index.ts").exists(), "must install when OpenCode is detected"); assert_eq!( - std::fs::read_to_string(&installed).unwrap(), - repo_file("plugin/opencode/code-trace.ts"), + std::fs::read_to_string(dir.join("index.ts")).unwrap(), + repo_file("plugin/opencode/index.ts"), "installed plugin must match the embedded source" ); + assert_eq!( + std::fs::read_to_string(dir.join("tui.ts")).unwrap(), + repo_file("plugin/opencode/tui.ts"), + "installed TUI part must match the embedded source" + ); } #[test]