Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

opencode: model side calls, TUI recovery, and opencode 2.x support

Zaid Ahmed693091add3f3
diff --git a/plugin/README.md b/plugin/README.md
index 5d026e2..fbce512 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -286,25 +286,44 @@ from); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokene
## opencode
-**Experimental.** Written against the v1 plugin API (`@opencode-ai/plugin`) and run live on
-opencode 1.19.5 with `opencode run` (free `opencode/big-pickle` model): the plugin loads, each
-session is handed over and folded with real token usage, facts are learned over five sessions
-(`microskills=envfacts`), and the next session receives them through the system prompt. Not yet
-exercised: the interactive TUI (toasts, quitting), the loop guard's redirect, and the v2 plugin API.
-
-**1. Install.** Copy or link the plugin directory, and keep it next to `scripts/` and `lib/`:
+**1. Install.** One plugin file serves opencode 1.x (the `server` entry) and 2.x (the `setup`
+entry). Link it where opencode looks for plugins, keeping it next to `scripts/` and `lib/`:
```bash
mkdir -p ~/.config/opencode/plugins
ln -s /path/to/TokenEconomizer/plugin/opencode/tokeneconomizer.ts ~/.config/opencode/plugins/tokeneconomizer.ts
```
+(Per repository: `.opencode/plugins/`.) Python 3.10+ must be on `PATH`, or named by `TE_PYTHON`.
+
**2. Check it.** Run a session, then `~/.tokeneconomizer/bin/te --host opencode status` in the
-repository. opencode has no plugin slash commands here, so every command runs from a terminal.
-Tool pruning does not apply yet. The plugin hands a session over when opencode deletes it, when the process
-exits, and after the one turn of a headless `opencode run`, exporting it with `opencode export`. Model calls of the plugin's own
-(micro-skills' proposer, the loop guard's judge) are not wired up for opencode yet, so it learns
-from repeated failures only.
+repository. opencode has no plugin slash commands, so every command runs from a terminal. Tool
+pruning does not apply. Micro-skills is off by default: `te --host opencode config set
+microskills=on` (or `envfacts`, without model calls).
+
+**How it hands a session over.** On 1.x the plugin exports the session with `opencode export` at
+the end of every turn and sends the path; on 2.x, which has no export command, it records the
+session from its events and writes the same JSON. A headless `opencode run` is folded when its
+turn ends and a deleted session when it is deleted. Quitting the TUI gives a plugin no chance to
+say so: that session is folded by the next session's start, once its export has been quiet for
+10 minutes.
+
+**Model calls.** The proposer and the loop guard's judge run through `opencode run` on your
+default opencode model (`paid_model` names another): tools that change anything are denied,
+the session is deleted afterwards, and no other plugin runs (`--pure` on 1.x; `--standalone` on
+2.x). On 2.x a reply that used no tool carries no usage, so its cost is estimated.
+
+**Verified live,** on opencode 1.19.5 and 2.2.0 (Python 3.12), with a scripted local model
+endpoint and, on 1.19.5, the free `opencode/big-pickle` model:
+the plugin loads; sessions are folded with real usage and model; facts learned over five sessions
+reach the next session through the system prompt; the loop guard's judge ran, nudged a
+failing edit-and-test loop, and the redirect arrived in the model's next tool results; the
+still-stuck notice was printed (`opencode run`) and the first notice shown as a TUI toast
+(1.19.5); a session quit with Ctrl+D in the TUI was folded by the next start.
+
+**Not covered:** the 2.x TUI, and notices on 2.x, which go to the server's stderr rather than a
+toast. A `read`, `task` or `*` permission denial stalls opencode 1.19.5 at start-up, which is why
+the side call denies only `bash`, `edit`, `webfetch` and `websearch`.
## What to expect
diff --git a/plugin/opencode/tokeneconomizer.ts b/plugin/opencode/tokeneconomizer.ts
index 4c5d99c..14fafa2 100644
--- a/plugin/opencode/tokeneconomizer.ts
+++ b/plugin/opencode/tokeneconomizer.ts
@@ -14,12 +14,16 @@
* tool.execute.after -> PostToolUse the guard; a redirect is appended to the
* tool result the model reads next, a
* still-stuck notice is shown as a toast
- * event session.idle -> Stop closes the turn
- * event session.deleted, or the process exiting
- * -> SessionEnd hands the session, exported as JSON, to
- * a detached fold
+ * event session.idle -> Stop closes the turn; the session is exported as
+ * JSON and its path sent along
+ * event session.deleted, a headless run's end, or the process exiting
+ * -> SessionEnd hands the session to a detached fold; a
+ * TUI quit sends nothing, so the plugin's
+ * session-recovery folds it at the next start
+ * once its export has been quiet for 10 minutes
*
- * opencode calls every export of a plugin module as a plugin, so `TokenEconomizer` is the only one.
+ * The module's one export is the default object below: opencode 1.x reads its `server`, 2.x its
+ * `setup`, and 1.x would call a second export as another plugin.
*
* Like the hooks on the other agents it fails open: a dispatcher that is missing, slow or
* broken answers "no change". It does nothing under TE_SIDECALL=1 (the plugin's own side calls)
@@ -143,7 +147,7 @@ function exportSession(sessionID: string, cwd: string): string {
}
}
-export const TokenEconomizer: Plugin = async ({ client, directory }) => {
+const TokenEconomizer: Plugin = async ({ client, directory }) => {
const manuals = new Map<string, string>();
const prompts = new Map<string, number>();
const turns = new Map<string, string>();
@@ -204,7 +208,11 @@ export const TokenEconomizer: Plugin = async ({ client, directory }) => {
const id = props.sessionID;
if (!id) return;
if (!open.has(id)) await start(id);
- await hook({ ...base(id), hook_event_name: "Stop", prompt_id: turns.get(id) ?? "", stop_hook_active: false });
+ // The session is exported at the end of every turn and its path sent with `Stop`: the
+ // TUI gives a plugin no chance to hand a session over when it is quit, and a session
+ // whose export has gone quiet is folded by the next session's start.
+ const file = exportSession(id, directory);
+ await hook({ ...base(id, file), hook_event_name: "Stop", prompt_id: turns.get(id) ?? "", stop_hook_active: false });
// A headless run ends right after its one turn, so the session is handed over now.
if (mode() === "run") await end(id, "run");
} else if (event?.type === "session.deleted") {
@@ -261,3 +269,156 @@ export const TokenEconomizer: Plugin = async ({ client, directory }) => {
},
};
};
+
+/**
+ * opencode 2.x (`Plugin.define({ id, setup })`, `@opencode/plugin`); `setup` below, on the same
+ * default export as v1's `server`, so one file serves both. v2 has no `opencode export`, so this entry
+ * records the session itself from its events -- prompts, tool calls and results, each step's
+ * tokens and cost -- and writes the same JSON shape `trace/opencode.py` reads.
+ */
+const textOf = (content: any): string =>
+ typeof content === "string"
+ ? content
+ : Array.isArray(content)
+ ? content.map((c: any) => (typeof c === "string" ? c : c?.text ?? "")).filter(Boolean).join("\n")
+ : "";
+
+const setupV2 = async (ctx: any) => {
+ const directory: string = ctx.location?.directory ?? ctx.location?.path ?? process.cwd();
+ const open = new Set<string>();
+ const manuals = new Map<string, string>();
+ const prompts = new Map<string, number>();
+ const turns = new Map<string, string>();
+ const records = new Map<string, any[]>(); // sessionID -> messages, in the export's shape
+ const steps = new Map<string, any>(); // assistantMessageID -> assistant message
+ const names = new Map<string, string>(); // tool call id -> tool name
+
+ const base = (sessionID: string, transcript = "") => ({ session_id: sessionID, transcript_path: transcript, cwd: directory });
+ const notify = (text: unknown) => { if (typeof text === "string" && text) console.error(text); };
+
+ const writeExport = (sessionID: string): string => {
+ const file = join(stateRoot(), "opencode-sessions", `${sessionID}.json`);
+ try {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ writeFileSync(file, JSON.stringify({ info: { id: sessionID }, messages: records.get(sessionID) ?? [] }), { mode: 0o600 });
+ return file;
+ } catch {
+ return "";
+ }
+ };
+
+ const start = async (id: string) => {
+ if (open.has(id)) return;
+ open.add(id);
+ records.set(id, []);
+ prompts.set(id, 0);
+ const out = await hook({ ...base(id), hook_event_name: "SessionStart", source: "startup" });
+ manuals.set(id, out?.hookSpecificOutput?.additionalContext ?? "");
+ notify(out?.systemMessage);
+ };
+ const end = async (id: string, reason: string) => {
+ if (!open.delete(id)) return;
+ await hook({ ...base(id, writeExport(id)), hook_event_name: "SessionEnd", reason });
+ };
+ process.once("exit", () => {
+ for (const id of open) hookSync({ ...base(id, writeExport(id)), hook_event_name: "SessionEnd", reason: "exit" });
+ open.clear();
+ });
+
+ const assistant = (sessionID: string, messageID: string) => {
+ let m = steps.get(messageID);
+ if (!m) {
+ m = { info: { id: messageID, role: "assistant", path: { cwd: directory } }, parts: [] };
+ steps.set(messageID, m);
+ records.get(sessionID)?.push(m);
+ }
+ return m;
+ };
+ const toolPart = (m: any, callID: string) => m.parts.find((p: any) => p.callID === callID);
+
+ await ctx.session.hook("prompt", async (e: any) => {
+ const id: string = e.sessionID;
+ await start(id);
+ const n = (prompts.get(id) ?? 0) + 1;
+ prompts.set(id, n);
+ const turn = `${id}:${n}`;
+ turns.set(id, turn);
+ const text: string = e.prompt?.text ?? "";
+ records.get(id)?.push({ info: { id: String(e.messageID ?? turn), role: "user" }, parts: [{ type: "text", text }] });
+ const out = await hook({ ...base(id), hook_event_name: "UserPromptSubmit", prompt_id: turn, prompt: text });
+ const extra = out?.hookSpecificOutput?.additionalContext;
+ if (extra) manuals.set(id, manuals.get(id) ? `${manuals.get(id)}\n\n${extra}` : extra);
+ notify(out?.systemMessage);
+ });
+
+ await ctx.session.hook("context", (e: any) => {
+ const manual = manuals.get(e.sessionID);
+ if (manual && Array.isArray(e.system)) e.system.push({ type: "text", text: manual });
+ });
+
+ await ctx.tool.hook("execute.after", async (e: any) => {
+ const id: string = e.sessionID;
+ const ok = e.status === "completed";
+ const result = ok ? e.result : undefined;
+ const text = ok ? textOf(result?.content) || String(result?.output ?? "") : String(e.error?.message ?? e.error ?? "");
+ const exit = typeof result?.metadata?.exit === "number" ? result.metadata.exit : undefined;
+ const out = await hook({
+ ...base(id),
+ hook_event_name: "PostToolUse",
+ prompt_id: turns.get(id) ?? "",
+ tool_name: e.tool,
+ tool_use_id: e.id,
+ tool_input: e.input ?? {},
+ tool_response: { content: text, isError: !ok || (exit !== undefined && exit !== 0), exit_code: exit },
+ });
+ const nudge = out?.hookSpecificOutput?.additionalContext;
+ if (nudge && ok && result) {
+ if (typeof result.content === "string") result.content = `${result.content}\n\n${nudge}`;
+ else if (Array.isArray(result.content)) result.content = [...result.content, { type: "text", text: nudge }];
+ else result.content = nudge;
+ }
+ notify(out?.systemMessage);
+ });
+
+ (async () => {
+ try {
+ for await (const ev of ctx.event.subscribe()) {
+ const t: string = ev?.type;
+ const p = ev?.properties ?? ev?.data ?? ev;
+ if (!t?.startsWith("session.")) continue;
+ const id: string = p?.sessionID;
+ if (!id) continue;
+ if (t === "session.step.started") {
+ const m = assistant(id, p.assistantMessageID);
+ m.info.modelID = p.model?.id ?? p.model?.modelID ?? m.info.modelID;
+ } else if (t === "session.step.ended") {
+ const m = assistant(id, p.assistantMessageID);
+ m.info.cost = p.cost ?? 0;
+ m.info.tokens = p.tokens;
+ } else if (t === "session.tool.input.started") {
+ names.set(p.id, p.name);
+ } else if (t === "session.tool.called") {
+ const m = assistant(id, p.assistantMessageID);
+ m.parts.push({ type: "tool", callID: p.id, tool: names.get(p.id) ?? "", state: { status: "running", input: p.input ?? {} } });
+ } else if (t === "session.tool.success" || t === "session.tool.failed") {
+ const part = toolPart(assistant(id, p.assistantMessageID), p.id);
+ if (part) {
+ part.state = t === "session.tool.success"
+ ? { status: "completed", input: part.state.input, output: textOf(p.content), metadata: p.metadata ?? {} }
+ : { status: "error", input: part.state.input, error: String(p.error?.message ?? textOf(p.content) ?? "") };
+ }
+ } else if (/^session\.execution\.(succeeded|failed|interrupted)$/.test(t)) {
+ // A turn is over: export, and send the path with `Stop`.
+ await hook({ ...base(id, writeExport(id)), hook_event_name: "Stop", prompt_id: turns.get(id) ?? "", stop_hook_active: false });
+ if (mode() === "run") await end(id, "run");
+ } else if (t === "session.deleted") {
+ await end(id, "deleted");
+ }
+ }
+ } catch (e) {
+ }
+ })();
+};
+
+// One default export for both: v1 reads `server`, v2 reads `setup`.
+export default { id: "tokeneconomizer", server: TokenEconomizer, setup: setupV2 };
diff --git a/tests/test_live_core.py b/tests/test_live_core.py
index f5f5843..fc8cdfd 100644
--- a/tests/test_live_core.py
+++ b/tests/test_live_core.py
@@ -7,6 +7,7 @@ wraps exec-stream item fields in PascalCase `event_msg/item_completed` records.
"""
import json
import os
+import subprocess
import pytest
@@ -522,6 +523,56 @@ def test_the_opencode_host_reads_what_the_plugin_sends():
assert hosts.detect({}, hint="opencode").name == "opencode"
+def _run_events(sid="ses_x"):
+ ev = [{"type": "step_start", "sessionID": sid, "part": {"type": "step-start"}},
+ {"type": "text", "sessionID": sid, "part": {"type": "text", "text": "po"}},
+ {"type": "text", "sessionID": sid, "part": {"type": "text", "text": "ng"}},
+ {"type": "step_finish", "sessionID": sid, "part": {
+ "type": "step-finish", "cost": 0.5,
+ "tokens": {"input": 10, "output": 4, "reasoning": 1, "cache": {"read": 7, "write": 2}}}}]
+ return "\n".join(json.dumps(e) for e in ev) + "\nnot json\n"
+
+
+def test_an_opencode_run_reply_is_read_from_its_json_events():
+ text, usage, sid = trace.opencode_run_reply(_run_events())
+ assert (text, sid) == ("pong", "ses_x")
+ assert usage == {"input_tokens": 10, "cache_read_input_tokens": 7,
+ "cache_creation_input_tokens": 2, "output_tokens": 5, "cost_usd": 0.5}
+ assert trace.opencode_run_reply("") == ("", None, "")
+
+
+def test_the_opencode_side_call_denies_tools_and_deletes_its_session(monkeypatch):
+ from tokeneconomizer.plugin import sidecall
+ seen = []
+
+ def fake_run(cmd, **kw):
+ seen.append((cmd, kw))
+ out = _run_events() if "--format" in cmd else "--pure --standalone"
+ return subprocess.CompletedProcess(cmd, 0, out, "")
+
+ monkeypatch.setattr(sidecall.subprocess, "run", fake_run)
+ sidecall._OC_FLAGS.clear()
+ text, eff = sidecall.opencode_call("is it stuck?", model="p/m", cli="oc")
+ assert text == "pong" and eff
+ run = next(c for c, _ in seen if "--format" in c)
+ assert run[:2] == ["oc", "run"] and "--pure" in run and "--standalone" in run
+ assert run[-3:] == ["--model", "p/m", "is it stuck?"]
+ kw = next(k for c, k in seen if "--format" in c)
+ assert kw["env"]["TE_SIDECALL"] == "1"
+ perm = json.loads(kw["env"]["OPENCODE_CONFIG_CONTENT"])["permission"]
+ assert perm["bash"] == "deny" and perm["edit"] == "deny"
+ assert any(c[:3] == ["oc", "session", "delete"] and c[3] == "ses_x" for c, _ in seen)
+
+
+def test_the_opencode_side_call_adds_only_the_flags_its_cli_lists(monkeypatch):
+ from tokeneconomizer.plugin import sidecall
+ monkeypatch.setattr(sidecall.subprocess, "run", lambda cmd, **kw: subprocess.CompletedProcess(
+ cmd, 0, " --format json\n", ""))
+ sidecall._OC_FLAGS.clear()
+ assert sidecall.opencode_flags("oc") == []
+ assert sidecall.runner_for("opencode", type("C", (), {"paid_model": ""})()) is not None
+
+
# ---- the guard sees edits made through the shell ---------------------------------------------
from tokeneconomizer import loopguard as guard # noqa: E402
from tokeneconomizer.loopguard import turn # noqa: E402
diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.py
index f46dd0d..b6bb286 100644
--- a/tokeneconomizer/plugin/hosts.py
+++ b/tokeneconomizer/plugin/hosts.py
@@ -352,14 +352,16 @@ class OpenCode(Host):
"""opencode (anomalyco/opencode), through the plugin in `plugin/opencode/`.
opencode has no hook protocol of its own -- plugins are TypeScript functions on its hook and
- event bus -- so the plugin speaks THIS one on opencode's behalf, as the Pi extension does: it
+ event bus (1.x: hook functions; 2.x: `setup` and domain hooks) -- so the plugin speaks THIS
+ one on opencode's behalf, as the Pi extension does: it
calls the same dispatcher with a Claude-shaped payload per event and applies the answer with
opencode's own levers (a system-prompt entry, a message into the session, a toast). What it
sends:
* `prompt_id`, which it numbers itself, for the turn identity opencode does not stamp;
- * `transcript_path`, the session's export (`client.session.messages`) written as JSON when
- the session ends, since opencode's own database is not a format to read;
+ * `transcript_path`, the session's export as JSON, written at the end of every turn (from
+ `opencode export` on 1.x; recorded by the plugin from its events on 2.x, which has no
+ export), since opencode's own database is not a format to read;
* `tool_response = {content, isError, exit_code}`, with `exit_code` from the bash tool's
`metadata.exit` when it reports one;
* opencode's mode in `TE_OPENCODE_MODE`: `run` (headless, `opencode run`) or `tui`.
diff --git a/tokeneconomizer/plugin/sidecall.py b/tokeneconomizer/plugin/sidecall.py
index 3f6882e..1590941 100644
--- a/tokeneconomizer/plugin/sidecall.py
+++ b/tokeneconomizer/plugin/sidecall.py
@@ -26,6 +26,10 @@ so no extra API key is needed and the call is billed where the session is:
it runs on the person's own default provider and model, under whatever login Pi holds for
it (a subscription signed in with `/login`, or an API key).
+ * opencode: `opencode run --format json` in a throwaway directory, on the person's default
+ model, with `bash`, `edit`, `webfetch` and `websearch` denied, no other plugin (`--pure` on
+ 1.x, `--standalone` on 2.x) and its session deleted afterwards.
+
Every side call runs with `TE_SIDECALL=1`, which the plugin's hook entry point treats as "do
nothing": without it the nested agent would run this plugin's hooks and recurse. A call that
returns no reply -- a CLI that is not signed in, say -- leaves one line in the plugin's
@@ -201,6 +205,62 @@ def pi_call(prompt, model="", cli="pi", timeout=TIMEOUT_S):
return text, eff
+# A side call only answers, so what can change anything or reach out is denied. Its directory is
+# an empty throwaway one, which is why the read-only tools are left alone: opencode 1.19.5 stalls
+# at startup, with no output, when `read`, `task` or `*` is denied (it waits on a prompt nobody sees).
+OPENCODE_CONFIG = json.dumps({"permission": {"bash": "deny", "edit": "deny", "webfetch": "deny",
+ "websearch": "deny"},
+ "share": "disabled", "autoupdate": False})
+
+
+_OC_FLAGS = {}
+
+
+def opencode_flags(cli="opencode"):
+ """The flags a side call adds, by what this opencode's `run --help` lists: `--pure` (1.x: no
+ external plugins) and `--standalone` (2.x: a private server of its own, since plugins there
+ run in a shared background service that does not inherit `TE_SIDECALL`, and the nested
+ session would run this plugin's hooks)."""
+ if cli not in _OC_FLAGS:
+ try:
+ help_text = subprocess.run([cli, "run", "--help"], capture_output=True,
+ encoding="utf-8", errors="replace", timeout=30,
+ stdin=subprocess.DEVNULL).stdout
+ except (OSError, subprocess.SubprocessError):
+ help_text = ""
+ _OC_FLAGS[cli] = [f for f in ("--pure", "--standalone") if f in help_text]
+ return list(_OC_FLAGS[cli])
+
+
+def opencode_call(prompt, model="", cli="opencode", timeout=TIMEOUT_S):
+ """A side call through `opencode run`: no external plugins where the CLI can say so, every
+ tool that changes anything denied, in a throwaway directory, on the person's own default
+ model unless `model` names one. The session it creates is deleted afterwards, so it is not
+ in their history."""
+ model_args = ["--model", model] if model else []
+ env = dict(_env(), OPENCODE_CONFIG_CONTENT=OPENCODE_CONFIG)
+ with tempfile.TemporaryDirectory(prefix="te-side-") as cwd:
+ out = subprocess.run([cli, "run", *opencode_flags(cli), "--format", "json", *model_args,
+ prompt],
+ capture_output=True, encoding="utf-8", errors="replace",
+ timeout=timeout, env=env, cwd=cwd, stdin=subprocess.DEVNULL)
+ text, usage, sid = trace.opencode_run_reply(out.stdout)
+ if sid:
+ try:
+ subprocess.run([cli, "session", "delete", sid], capture_output=True, timeout=30,
+ env=env, cwd=cwd, stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ if not text:
+ _no_reply("opencode", out)
+ eff = None
+ if usage:
+ usage.pop("cost_usd", None)
+ usage["model"] = model or "opencode"
+ eff, _ = accounting.effective(usage)
+ return text, eff
+
+
# Everything the Copilot CLI offers (1.0.83 names), so the completion is offered nothing; a name
# the installed CLI does not know is ignored.
COPILOT_TOOLS = ("bash", "read_bash", "write_bash", "stop_bash", "list_bash", "view", "grep",
@@ -278,9 +338,7 @@ def runner_for(host_name, config):
if host_name == "pi":
return lambda prompt, _m="agent": pi_call(prompt, model=model)
if host_name == "opencode":
- # No model call yet: opencode's headless output is not read here, so micro-skills learns
- # from repeated failures alone and the loop guard's judge stays silent.
- return lambda prompt, _m="agent": ("", None)
+ return lambda prompt, _m="agent": opencode_call(prompt, model=model)
if host_name == "codex":
return lambda prompt, _m="agent": codex_call(prompt, model=model)
if host_name == "copilot":
diff --git a/tokeneconomizer/trace/__init__.py b/tokeneconomizer/trace/__init__.py
index 08632b0..595e9ae 100644
--- a/tokeneconomizer/trace/__init__.py
+++ b/tokeneconomizer/trace/__init__.py
@@ -23,8 +23,8 @@ from .codex import (codex_capability_trace, codex_exec_calls, codex_prompt_count
from .copilot import (copilot_event_calls, copilot_mcp_servers, copilot_prompt_count,
copilot_session_meta, copilot_session_usage, copilot_turns,
mcp_server_of)
-from .opencode import (opencode_prompt_count, opencode_session_info, opencode_session_to_claude,
- opencode_session_usage)
+from .opencode import (opencode_prompt_count, opencode_run_reply, opencode_session_info,
+ opencode_session_to_claude, opencode_session_usage)
from .pi import (pi_active_branch, pi_json_reply, pi_prompt_count, pi_session_header,
pi_session_to_claude, pi_session_usage)
@@ -39,7 +39,7 @@ __all__ = [
"codex_session_meta", "codex_session_usage", "rollout_item_to_exec",
"copilot_event_calls", "copilot_mcp_servers", "copilot_prompt_count", "copilot_session_meta",
"copilot_session_usage", "copilot_turns", "mcp_server_of",
- "opencode_prompt_count", "opencode_session_info", "opencode_session_to_claude",
+ "opencode_prompt_count", "opencode_run_reply", "opencode_session_info", "opencode_session_to_claude",
"opencode_session_usage",
"pi_active_branch", "pi_json_reply", "pi_prompt_count", "pi_session_header",
"pi_session_to_claude", "pi_session_usage",
diff --git a/tokeneconomizer/trace/opencode.py b/tokeneconomizer/trace/opencode.py
index c12f502..4bf8f79 100644
--- a/tokeneconomizer/trace/opencode.py
+++ b/tokeneconomizer/trace/opencode.py
@@ -143,3 +143,28 @@ def opencode_session_usage(path):
totals.update(requests=requests, cost_usd_vendor=round(cost, 6),
model=max(models, key=models.get) if models else None)
return totals
+
+
+def opencode_run_reply(stdout):
+ """(text, usage, session_id) of an `opencode run --format json` run: the reply text, the
+ usage of every finished step in ledger fields (with opencode's own cost as `cost_usd`), and
+ the session it created. `usage` is None when no step finished."""
+ text, usage, sid = [], None, ""
+ for line in (stdout or "").splitlines():
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ if not isinstance(ev, dict):
+ continue
+ sid = sid or str(ev.get("sessionID") or "")
+ part = ev.get("part") if isinstance(ev.get("part"), dict) else {}
+ if ev.get("type") == "text" and part.get("text"):
+ text.append(part["text"])
+ elif ev.get("type") == "step_finish":
+ u = _usage({"tokens": part.get("tokens"), "cost": part.get("cost")})
+ if u:
+ usage = usage or dict.fromkeys(u, 0)
+ for k, v in u.items():
+ usage[k] += v
+ return "".join(text).strip(), usage, sid