Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

Add experimental opencode support: host adapter, session-export reader, plugin

Zaid Ahmedf060d2af8806
diff --git a/CLAUDE.md b/CLAUDE.md
index 23ae32b..b08d449 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -10,7 +10,7 @@ agent behavior, and `docs/ARCHITECTURE.md` for how the package fits together.
- `microskills/` — learn repository facts from finished sessions; render the injected block
- `toolprune/` — unused-tool evidence and the deny-list proposal; Codex capability packages
- `loopguard/` — the per-call failure-loop guard and its per-repository envelope
- - `trace/` — each agent's session-log format (Claude Code, Codex, Copilot CLI, Pi)
+ - `trace/` — each agent's session-log format (Claude Code, Codex, Copilot CLI, Pi, opencode)
- `plugin/` — the runtime: hook dispatch, per-repository state, settings, the `te` CLI
- `config.py`, `ledger.py`, `pricing.py`, `domain.py`, `stage.py` — shared by all three
- `plugin/` — the installable plugin directory: manifests per agent, hook files, launchers
diff --git a/plugin/README.md b/plugin/README.md
index fa1519f..7e06278 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,6 +1,6 @@
# TokenEconomizer plugin
-How to install and use TokenEconomizer in Claude Code, Codex, the GitHub Copilot CLI and Pi. What
+How to install and use TokenEconomizer in Claude Code, Codex, the GitHub Copilot CLI, Pi and (experimental) opencode. What
the plugin does and why is in the [main README](../README.md); its design and the verified
behaviour of each agent are in [`docs/PLUGIN.md`](../docs/PLUGIN.md).
@@ -284,6 +284,26 @@ after the loop guard's redirect gets a notice: press **Esc** to abort it, or Ctr
**Uninstall.** `pi remove git:github.com/microsoft/TokenEconomizer` (the source you installed
from); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokeneconomizer`.
+## opencode
+
+**Experimental; not yet verified against a running opencode.** The plugin is written against the
+v1 plugin API (`@opencode-ai/plugin`, opencode 1.19.x) and is tested only through the shared
+dispatcher and a recorded session export.
+
+**1. Install.** Copy or link the plugin directory, and keep 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
+```
+
+**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 or the
+process exits, and a headless `opencode run` after its one turn. 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.
+
## What to expect
The plugin works session by session: what it learns from a repository's earlier sessions is
@@ -364,6 +384,7 @@ How to run them:
| Codex | `$tokeneconomizer:<command>` (`status`, `microskills`, `toolprune`, `config`, `repos`) | `~/.tokeneconomizer/bin/te --host codex <command>` |
| Copilot CLI | `/tokeneconomizer:<command>` (interactive mode) | `~/.tokeneconomizer/bin/te --host copilot <command>` |
| Pi | `/te <command>` | `~/.tokeneconomizer/bin/te --host pi <command>` |
+| opencode | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host opencode <command>` |
`doctor` and `repomap` run from a terminal (or as `/te …` on Pi); there is no slash command or
Codex skill for them.
diff --git a/plugin/opencode/tokeneconomizer.ts b/plugin/opencode/tokeneconomizer.ts
new file mode 100644
index 0000000..e67eccf
--- /dev/null
+++ b/plugin/opencode/tokeneconomizer.ts
@@ -0,0 +1,249 @@
+/**
+ * TokenEconomizer for opencode (anomalyco/opencode).
+ *
+ * opencode has no hook protocol -- plugins are functions that return hooks -- so this plugin
+ * speaks the one the Claude Code, Codex and Pi integrations use, on opencode's behalf: every
+ * event below becomes one call of the shared dispatcher (`../scripts/te-hook --host opencode`,
+ * JSON in, JSON out), and the answer is applied with opencode's own levers. All of the
+ * mechanism logic lives in the dispatcher; this file only translates.
+ *
+ * event session.created -> SessionStart the learned manual, kept for the session
+ * chat.message -> UserPromptSubmit opens a prompt-turn
+ * experimental.chat.system.transform appends the manual to the system prompt,
+ * on every request of the session
+ * 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
+ *
+ * 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)
+ * or TE_DISABLE=1.
+ */
+import type { Plugin } from "@opencode-ai/plugin";
+import { spawn, spawnSync } from "node:child_process";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HERE = (() => {
+ try {
+ return dirname(fileURLToPath(import.meta.url));
+ } catch {
+ return __dirname;
+ }
+})();
+const SCRIPTS = join(HERE, "..", "scripts");
+const HOOK_TIMEOUT_MS = 60_000;
+
+const truthy = (v: string | undefined) => ["1", "true", "yes", "on"].includes((v ?? "").trim().toLowerCase());
+const disabled = () => truthy(process.env.TE_SIDECALL) || truthy(process.env.TE_DISABLE);
+
+/** `opencode run` is headless: one prompt, then the process ends. */
+const mode = () => (process.env.TE_OPENCODE_MODE ?? (process.argv.includes("run") ? "run" : "tui"));
+
+/** The program and arguments that run a launcher. The launchers are POSIX `sh`, which Windows
+ * cannot start; there the bootstrap they run is started with Python itself (`TE_PYTHON`, else
+ * `python`). */
+export function launch(
+ script: string,
+ args: string[],
+ platform: string = process.platform,
+): [string, string[]] {
+ if (platform !== "win32") return [join(SCRIPTS, script), args];
+ const kind = script === "te-hook" ? "hook" : "cli";
+ return [process.env.TE_PYTHON || "python", [join(SCRIPTS, "te_bootstrap.py"), kind, ...args]];
+}
+
+const childEnv = () => ({ ...process.env, PYTHONUTF8: "1", TE_OPENCODE_MODE: mode() });
+
+/** One dispatcher call; `{}` (no change) on any failure. */
+function hook(payload: Record<string, unknown>): Promise<any> {
+ if (disabled()) return Promise.resolve({});
+ return new Promise((done) => {
+ let out = "";
+ let child;
+ try {
+ const [program, argv] = launch("te-hook", ["--host", "opencode"]);
+ child = spawn(program, argv, { env: childEnv(), stdio: ["pipe", "pipe", "ignore"] });
+ } catch {
+ done({});
+ return;
+ }
+ const finish = () => {
+ clearTimeout(timer);
+ try {
+ done(JSON.parse(out.trim().split("\n").pop() || "{}") ?? {});
+ } catch {
+ done({});
+ }
+ };
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ done({});
+ }, HOOK_TIMEOUT_MS);
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (d: string) => (out += d));
+ child.on("error", () => {
+ clearTimeout(timer);
+ done({});
+ });
+ child.on("close", finish);
+ child.stdin.on("error", () => {});
+ child.stdin.end(JSON.stringify(payload));
+ });
+}
+
+/** The same call, blocking: for a process that is exiting and cannot wait on an event loop. */
+function hookSync(payload: Record<string, unknown>) {
+ if (disabled()) return;
+ try {
+ const [program, argv] = launch("te-hook", ["--host", "opencode"]);
+ spawnSync(program, argv, {
+ env: childEnv(),
+ input: JSON.stringify(payload),
+ timeout: HOOK_TIMEOUT_MS,
+ stdio: ["pipe", "ignore", "ignore"],
+ });
+ } catch {
+ /* fail open */
+ }
+}
+
+const stateRoot = () => resolve(process.env.TOKENECONOMIZER_HOME || join(homedir(), ".tokeneconomizer"));
+
+/** What the model said and did so far, as the JSON the fold reads (`trace/opencode.py`). */
+async function exportSession(client: any, sessionID: string): Promise<string> {
+ const file = join(stateRoot(), "opencode-sessions", `${sessionID}.json`);
+ try {
+ const res = await client.session.messages({ path: { id: sessionID } });
+ const messages = res?.data ?? res;
+ if (!Array.isArray(messages)) return "";
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ writeFileSync(file, JSON.stringify({ info: { id: sessionID }, messages }), { mode: 0o600 });
+ return file;
+ } catch {
+ return "";
+ }
+}
+
+export const TokenEconomizer: Plugin = async ({ client, directory }) => {
+ const manuals = new Map<string, string>();
+ const prompts = new Map<string, number>();
+ const turns = new Map<string, string>();
+ const open = new Set<string>();
+ let current = "";
+
+ const base = (sessionID: string, transcript = "") => ({
+ session_id: sessionID,
+ transcript_path: transcript,
+ cwd: directory,
+ });
+
+ const notify = async (text: unknown) => {
+ if (typeof text !== "string" || !text) return;
+ try {
+ if (mode() === "run") console.error(text);
+ else await client.tui.showToast({ body: { message: text, variant: "info" } });
+ } catch {
+ console.error(text);
+ }
+ };
+
+ const start = async (sessionID: string) => {
+ if (open.has(sessionID)) return;
+ open.add(sessionID);
+ prompts.set(sessionID, 0);
+ const out = await hook({ ...base(sessionID), hook_event_name: "SessionStart", source: "startup" });
+ manuals.set(sessionID, out?.hookSpecificOutput?.additionalContext ?? "");
+ await notify(out?.systemMessage);
+ };
+
+ const end = async (sessionID: string, reason: string) => {
+ if (!open.delete(sessionID)) return;
+ const file = await exportSession(client, sessionID);
+ await hook({ ...base(sessionID, file), hook_event_name: "SessionEnd", reason });
+ };
+
+ // Where the process ends without a `session.deleted` (quitting the TUI, `opencode run`
+ // finishing), the sessions still open are handed over, once, synchronously.
+ process.once("exit", () => {
+ for (const sessionID of open) {
+ hookSync({ ...base(sessionID), hook_event_name: "SessionEnd", reason: "exit" });
+ }
+ open.clear();
+ });
+
+ return {
+ event: async ({ event }: { event: any }) => {
+ const props = event?.properties ?? {};
+ if (event?.type === "session.created") {
+ const id = props.info?.id ?? props.sessionID;
+ if (id && !props.info?.parentID) await start(id);
+ } else if (event?.type === "session.idle") {
+ 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 });
+ // A headless run ends right after its one turn; export now, while the client is up.
+ if (mode() === "run") await end(id, "run");
+ } else if (event?.type === "session.deleted") {
+ const id = props.info?.id ?? props.sessionID;
+ if (id) await end(id, "deleted");
+ }
+ },
+
+ "chat.message": async (input: any, output: any) => {
+ const id: string = input?.sessionID;
+ if (!id) return;
+ current = id;
+ if (!open.has(id)) await start(id);
+ const n = (prompts.get(id) ?? 0) + 1;
+ prompts.set(id, n);
+ const turn = `${id}:${n}`;
+ turns.set(id, turn);
+ const prompt = (output?.parts ?? [])
+ .filter((p: any) => p?.type === "text")
+ .map((p: any) => p.text)
+ .join("\n");
+ const out = await hook({ ...base(id), hook_event_name: "UserPromptSubmit", prompt_id: turn, prompt });
+ // The repository map arrives on a session's first prompt; it joins the manual for the rest
+ // of the session, since the manual is added to every request.
+ const extra = out?.hookSpecificOutput?.additionalContext;
+ if (extra) manuals.set(id, manuals.get(id) ? `${manuals.get(id)}\n\n${extra}` : extra);
+ await notify(out?.systemMessage);
+ },
+
+ "experimental.chat.system.transform": async (input: any, output: any) => {
+ const manual = manuals.get(input?.sessionID ?? current);
+ if (manual) output.system.push(manual);
+ },
+
+ "tool.execute.after": async (input: any, output: any) => {
+ const id: string = input?.sessionID;
+ if (!id) return;
+ const meta = (output?.metadata ?? {}) as Record<string, unknown>;
+ const exit = typeof meta.exit === "number" ? meta.exit : undefined;
+ const text = String(output?.output ?? "");
+ const out = await hook({
+ ...base(id),
+ hook_event_name: "PostToolUse",
+ prompt_id: turns.get(id) ?? "",
+ tool_name: input.tool,
+ tool_use_id: input.callID,
+ tool_input: input.args ?? {},
+ tool_response: { content: text, isError: exit !== undefined && exit !== 0, exit_code: exit },
+ });
+ const nudge = out?.hookSpecificOutput?.additionalContext;
+ // The redirect rides on the result the model reads next: opencode has no mid-turn message.
+ if (nudge) output.output = `${text}\n\n${nudge}`;
+ await notify(out?.systemMessage);
+ },
+ };
+};
+
+export default TokenEconomizer;
diff --git a/tests/test_live_core.py b/tests/test_live_core.py
index b5d666e..f5f5843 100644
--- a/tests/test_live_core.py
+++ b/tests/test_live_core.py
@@ -460,6 +460,68 @@ def test_the_pi_host_reads_what_the_extension_sends():
assert hosts.detect({"turn_id": "t"}, hint="pi").name == "pi"
+# ---- opencode sessions -------------------------------------------------------------------
+def _opencode_export(path, cwd="/w/repo"):
+ """An opencode export: a prompt, a bash call that fails, an edit, a bash call that passes."""
+ tokens = {"input": 10, "output": 45, "reasoning": 5, "cache": {"read": 1000, "write": 100}}
+
+ def call(cid, tool, args, state):
+ return {"info": {"id": f"m-{cid}", "role": "assistant", "modelID": "gpt-5.6-sol",
+ "path": {"cwd": cwd, "root": cwd}, "cost": 0.002, "tokens": tokens},
+ "parts": [{"type": "tool", "callID": cid, "tool": tool,
+ "state": dict(state, input=args)}]}
+
+ msgs = [{"info": {"id": "u1", "role": "user"},
+ "parts": [{"type": "text", "text": "fix the bug"},
+ {"type": "text", "text": "(added by opencode)", "synthetic": True}]},
+ call("c1", "bash", {"command": "pytest -q"},
+ {"status": "error", "error": "bash: pytest: command not found"}),
+ call("c2", "edit", {"filePath": "pkg/a.py", "oldString": "x", "newString": "y"},
+ {"status": "completed", "output": "ok", "metadata": {}}),
+ call("c3", "bash", {"command": "python -m pytest -q"},
+ {"status": "completed", "output": "1 passed", "metadata": {"exit": 0}})]
+ with open(path, "w") as fh:
+ json.dump({"info": {"id": "oc-1"}, "messages": msgs}, fh)
+ return path
+
+
+def test_an_opencode_export_reads_through_the_trace_seam(tmp_path):
+ src = _opencode_export(str(tmp_path / "s.json"))
+ out = str(tmp_path / "t.jsonl")
+ assert trace.opencode_session_to_claude(src, out) == 3
+ assert trace.opencode_prompt_count(src) == 1 # opencode's own text is not a prompt
+ text = open(out).read()
+ assert "command not found" in text and "python -m pytest -q" in text
+ assert '"is_error": true' in text and "fix the bug" in text and "added by opencode" not in text
+
+
+def test_an_opencode_list_export_and_a_missing_file(tmp_path):
+ src = _opencode_export(str(tmp_path / "s.json"))
+ listed = str(tmp_path / "l.json")
+ json.dump(json.load(open(src))["messages"], open(listed, "w"))
+ assert trace.opencode_session_to_claude(listed, str(tmp_path / "t.jsonl")) == 3
+ assert trace.opencode_session_to_claude(str(tmp_path / "none.json"), str(tmp_path / "x")) is None
+
+
+def test_opencode_usage_counts_reasoning_as_output(tmp_path):
+ u = trace.opencode_session_usage(_opencode_export(str(tmp_path / "s.json")))
+ assert (u["input_tokens"], u["output_tokens"]) == (30, 150)
+ assert (u["cache_read_input_tokens"], u["cache_creation_input_tokens"]) == (3000, 300)
+ assert u["requests"] == 3 and u["model"] == "gpt-5.6-sol"
+ assert u["cost_usd_vendor"] == 0.006
+
+
+def test_the_opencode_host_reads_what_the_plugin_sends():
+ h = hosts.HOSTS["opencode"]()
+ name, args, text, code = h.tool_call({"tool_name": "bash", "tool_input": {"command": "go test"},
+ "tool_response": {"content": "FAIL", "isError": True,
+ "exit_code": 1}})
+ assert (name, args["command"], code) == ("bash", "go test", 1) and "FAIL" in text
+ assert h.headless({"TE_OPENCODE_MODE": "run"}) and not h.headless({"TE_OPENCODE_MODE": "tui"})
+ assert h.turn_key({"prompt_id": "s:1"}) == "s:1"
+ assert hosts.detect({}, hint="opencode").name == "opencode"
+
+
# ---- 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/.DS_Store b/tokeneconomizer/.DS_Store
new file mode 100644
index 0000000..7c67551
Binary files /dev/null and b/tokeneconomizer/.DS_Store differ
diff --git a/tokeneconomizer/plugin/cli.py b/tokeneconomizer/plugin/cli.py
index 20df253..f5a602b 100644
--- a/tokeneconomizer/plugin/cli.py
+++ b/tokeneconomizer/plugin/cli.py
@@ -625,8 +625,8 @@ def cmd_doctor(args):
ok = False
import shutil as _sh
# Only the agents installed here: a Codex-only machine has no Claude Code catalog to probe.
- agents = [h for h in ("claude", "codex", "copilot", "pi") if _sh.which(h)]
- print(f"agents {', '.join(agents) or 'none of claude, codex, copilot, pi on PATH'}")
+ agents = [h for h in ("claude", "codex", "copilot", "opencode", "pi") if _sh.which(h)]
+ print(f"agents {', '.join(agents) or 'none of claude, codex, copilot, opencode, pi on PATH'}")
for h in agents:
pause = sidecall.paused(h, root)
if pause:
diff --git a/tokeneconomizer/plugin/hook.py b/tokeneconomizer/plugin/hook.py
index dbc2b8b..9fc873c 100644
--- a/tokeneconomizer/plugin/hook.py
+++ b/tokeneconomizer/plugin/hook.py
@@ -1,6 +1,6 @@
"""The entry point every plugin hook executes: hook JSON on stdin, hook JSON on stdout.
- python -m tokeneconomizer.plugin.hook [--host claude|codex|copilot|pi]
+ python -m tokeneconomizer.plugin.hook [--host claude|codex|copilot|opencode|pi]
It never fails the agent. Whatever goes wrong -- unreadable input, a full disk, a bug -- the hook
prints `{}` (which changes nothing) and records the traceback in `<state root>/errors.log`. It
diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.py
index 34e9af7..f46dd0d 100644
--- a/tokeneconomizer/plugin/hosts.py
+++ b/tokeneconomizer/plugin/hosts.py
@@ -348,6 +348,45 @@ class Pi(Host):
return trace.pi_session_usage(transcript_path)
+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
+ 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;
+ * `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`.
+ """
+ name = "opencode"
+ prompt_context = True # the plugin appends it to the system prompt
+ interrupt = "Press Esc to interrupt it."
+ end_run = "Press Ctrl+C to end the run."
+
+ def turn_key(self, p):
+ return str(p.get("prompt_id") or "")
+
+ def headless(self, env, transcript=None):
+ return str(env.get("TE_OPENCODE_MODE", "")).strip() == "run"
+
+ def mechanism_trace(self, transcript_path, workdir):
+ out = os.path.join(workdir, "opencode_trace.jsonl")
+ n = trace.opencode_session_to_claude(transcript_path, out)
+ return out if n is not None else None
+
+ def prompt_count(self, transcript_path):
+ return trace.opencode_prompt_count(transcript_path)
+
+ def session_usage(self, transcript_path):
+ return trace.opencode_session_usage(transcript_path)
+
+
def copilot_home(env=None):
env = os.environ if env is None else env
return env.get("COPILOT_HOME") or os.path.join(os.path.expanduser("~"), ".copilot")
@@ -437,7 +476,8 @@ def _ancestor_args(limit=4):
return out
-HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "pi": Pi}
+HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "opencode": OpenCode,
+ "pi": Pi}
def default_host(env=None, recent=None):
diff --git a/tokeneconomizer/plugin/sidecall.py b/tokeneconomizer/plugin/sidecall.py
index e2f11f3..3f6882e 100644
--- a/tokeneconomizer/plugin/sidecall.py
+++ b/tokeneconomizer/plugin/sidecall.py
@@ -277,6 +277,10 @@ def runner_for(host_name, config):
model = config.paid_model
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)
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 002a77a..08632b0 100644
--- a/tokeneconomizer/trace/__init__.py
+++ b/tokeneconomizer/trace/__init__.py
@@ -6,7 +6,7 @@ here and nowhere else:
* `calls` -- `load_trajectory`: any agent's log as ordered `(name, args, result, ok)` calls;
`call_cwds`, `tool_usage`, `strip_rtk_prefix`;
* `catalog` -- the tool list a session loaded, from whichever source the agent publishes;
- * `claude`, `codex`, `copilot`, `pi` -- each agent's own session file: usage, metadata,
+ * `claude`, `codex`, `copilot`, `opencode`, `pi` -- each agent's own session file: usage, metadata,
prompt-turns, and the conversions that let the readers above handle it.
Stdlib only.
@@ -23,6 +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 .pi import (pi_active_branch, pi_json_reply, pi_prompt_count, pi_session_header,
pi_session_to_claude, pi_session_usage)
@@ -37,6 +39,8 @@ __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_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
new file mode 100644
index 0000000..c12f502
--- /dev/null
+++ b/tokeneconomizer/trace/opencode.py
@@ -0,0 +1,145 @@
+"""opencode (anomalyco/opencode): a session exported as JSON.
+
+opencode keeps its sessions in its own database, which is not a stable format to read. What it
+publishes is the export -- `opencode export <session>`, or `client.session.messages` from a
+plugin -- a list of `{info, parts}` messages, or `{info, messages}` around that list. The plugin
+writes that export beside the other state when a session ends, and this module reads the file.
+
+A user message's `parts` carry its `text` parts. An assistant message carries its `modelID`,
+`path.cwd`, `cost` and `tokens` ({input, output, reasoning, cache: {read, write}}), and a `tool`
+part per call: `{callID, tool, state}`, where `state` is `completed` (`input`, `output`,
+`metadata`) or `error` (`input`, `error`). `opencode_session_to_claude` writes the conversation as
+the Claude Code envelope the other readers already handle, so no mechanism needs an opencode
+branch.
+
+Usage, per opencode's own type: `input` excludes the cache fields and `output` excludes
+`reasoning`, so output tokens are the two together.
+"""
+import json
+import os
+
+
+def _load(path):
+ """(session info, messages) of an export file; ({}, []) when it cannot be read."""
+ try:
+ with open(path, encoding="utf-8") as fh:
+ data = json.load(fh)
+ except (OSError, ValueError):
+ return {}, []
+ if isinstance(data, list):
+ return {}, [m for m in data if isinstance(m, dict)]
+ if isinstance(data, dict):
+ msgs = data.get("messages")
+ return (data.get("info") if isinstance(data.get("info"), dict) else {},
+ [m for m in msgs if isinstance(m, dict)] if isinstance(msgs, list) else [])
+ return {}, []
+
+
+def _role(msg):
+ return (msg.get("info") or {}).get("role")
+
+
+def _text(msg):
+ """The text a user typed: `text` parts that opencode did not add itself."""
+ return "\n".join(p.get("text", "") for p in msg.get("parts") or []
+ if isinstance(p, dict) and p.get("type") == "text"
+ and not p.get("synthetic") and not p.get("ignored"))
+
+
+def opencode_session_info(path):
+ """The session's `info` ({id, directory, ...}), {} if the export does not carry it."""
+ return _load(path)[0]
+
+
+def opencode_prompt_count(path):
+ """How many prompts the conversation ran: user messages that hold text."""
+ return sum(1 for m in _load(path)[1] if _role(m) == "user" and _text(m).strip())
+
+
+def _usage(info):
+ t = info.get("tokens")
+ if not isinstance(t, dict):
+ return None
+ cache = t.get("cache") if isinstance(t.get("cache"), dict) else {}
+ return {"input_tokens": int(t.get("input") or 0),
+ "cache_read_input_tokens": int(cache.get("read") or 0),
+ "cache_creation_input_tokens": int(cache.get("write") or 0),
+ "output_tokens": int(t.get("output") or 0) + int(t.get("reasoning") or 0),
+ "cost_usd": float(info.get("cost") or 0)}
+
+
+def opencode_session_to_claude(path, out_path):
+ """Write an opencode export as Claude Code transcript lines.
+
+ Returns the number of tool calls written, or None when the file is missing or holds no
+ messages. A call still pending or running when the export was taken is written without a
+ result, as a session that ended mid-call."""
+ if not path or not os.path.exists(path):
+ return None
+ _, messages = _load(path)
+ if not messages:
+ return None
+ n = 0
+ with open(out_path, "w", encoding="utf-8") as out:
+ for m in messages:
+ info = m.get("info") or {}
+ if info.get("role") == "user":
+ text = _text(m)
+ if text.strip():
+ out.write(json.dumps({"type": "user", "message": {
+ "role": "user", "content": text}}) + "\n")
+ continue
+ if info.get("role") != "assistant":
+ continue
+ blocks, results = [], []
+ for p in m.get("parts") or []:
+ if not isinstance(p, dict):
+ continue
+ if p.get("type") == "text" and p.get("text"):
+ blocks.append({"type": "text", "text": p["text"]})
+ elif p.get("type") == "tool":
+ st = p.get("state") if isinstance(p.get("state"), dict) else {}
+ blocks.append({"type": "tool_use", "id": p.get("callID"),
+ "name": p.get("tool"), "input": st.get("input") or {}})
+ n += 1
+ if st.get("status") == "completed":
+ results.append((p.get("callID"), str(st.get("output") or ""), False))
+ elif st.get("status") == "error":
+ results.append((p.get("callID"), str(st.get("error") or ""), True))
+ cwd = (info.get("path") or {}).get("cwd")
+ msg = {"id": info.get("id"), "role": "assistant", "content": blocks,
+ "model": info.get("modelID")}
+ usage = _usage(info)
+ if usage:
+ msg["usage"] = {k: v for k, v in usage.items() if k != "cost_usd"}
+ out.write(json.dumps(dict({"type": "assistant", "message": msg},
+ **({"cwd": cwd} if isinstance(cwd, str) and cwd else {})))
+ + "\n")
+ for call_id, text, is_error in results:
+ out.write(json.dumps({"type": "user", "message": {"role": "user", "content": [{
+ "type": "tool_result", "tool_use_id": call_id, "content": text,
+ "is_error": is_error}]}}) + "\n")
+ return n
+
+
+def opencode_session_usage(path):
+ """Token breakdown of an opencode session, plus opencode's own cost estimate."""
+ totals = {"input_tokens": 0, "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0, "output_tokens": 0}
+ cost, requests, models = 0.0, 0, {}
+ for m in _load(path)[1]:
+ info = m.get("info") or {}
+ if info.get("role") != "assistant":
+ continue
+ u = _usage(info)
+ if not u:
+ continue
+ requests += 1
+ cost += u.pop("cost_usd")
+ for k in totals:
+ totals[k] += u[k]
+ if info.get("modelID"):
+ models[info["modelID"]] = models.get(info["modelID"], 0) + 1
+ totals.update(requests=requests, cost_usd_vendor=round(cost, 6),
+ model=max(models, key=models.get) if models else None)
+ return totals