Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(agent): report token usage from the agent CLIs

Shahriarcabb86188ae4
diff --git a/docs/internals/agent-runs.md b/docs/internals/agent-runs.md
index 0c0debb..d9ea622 100644
--- a/docs/internals/agent-runs.md
+++ b/docs/internals/agent-runs.md
@@ -60,7 +60,7 @@ sequenceDiagram
D-->>M: result
M-->>K: tool result
K-->>D: stream-json deltas
- D-->>S: run events (text, tool, toolResult, approval, done)
+ D-->>S: run events (text, tool, toolResult, approval, usage, done)
```
**The loop closes on itself.** The daemon spawns the agent CLI, which spawns *another*
diff --git a/src/daemon/agent/runners/claude.ts b/src/daemon/agent/runners/claude.ts
index 3376bf9..0a09275 100644
--- a/src/daemon/agent/runners/claude.ts
+++ b/src/daemon/agent/runners/claude.ts
@@ -4,7 +4,7 @@ import { join } from 'node:path';
import { stateDir } from '../../lockfile';
import { log } from '../../log';
import { effortOf, parseJsonLine } from './util';
-import type { JsonContext, Plan, Runner, StreamContext, StreamReader } from './types';
+import type { JsonContext, Plan, Runner, StreamContext, StreamReader, StreamSink } from './types';
export const MCP_SERVER_NAME = 'browsentic';
@@ -43,6 +43,13 @@ const ONE_SHOT_DENIED = [...BUILTIN_DENIED, ...WEB_TOOLS];
const OLD_CLAUDE = /unknown option|unrecognized option/i;
+interface UsageLine {
+ input_tokens?: number;
+ cache_creation_input_tokens?: number;
+ cache_read_input_tokens?: number;
+ output_tokens?: number;
+}
+
type StreamLine =
| { type: 'system'; subtype?: string; session_id?: string; tools?: string[] }
| {
@@ -54,7 +61,15 @@ type StreamLine =
content_block?: { type?: string; id?: string; name?: string };
};
}
- | { type: 'result'; is_error?: boolean; subtype?: string; stop_reason?: string | null; result?: string };
+ | { type: 'assistant'; parent_tool_use_id?: string | null; message?: { usage?: UsageLine } }
+ | {
+ type: 'result';
+ is_error?: boolean;
+ subtype?: string;
+ stop_reason?: string | null;
+ result?: string;
+ usage?: UsageLine;
+ };
export const claudeRunner: Runner = {
kind: 'claude',
@@ -99,6 +114,21 @@ export const claudeRunner: Runner = {
},
reader(): StreamReader {
+ let generated = 0;
+
+ const report = (usage: UsageLine | undefined, sink: StreamSink) => {
+ if (!usage) return;
+ generated += usage.output_tokens ?? 0;
+ sink.usage({
+ contextTokens:
+ (usage.input_tokens ?? 0) +
+ (usage.cache_read_input_tokens ?? 0) +
+ (usage.cache_creation_input_tokens ?? 0) +
+ (usage.output_tokens ?? 0),
+ outputTokens: generated,
+ });
+ };
+
return (line, sink) => {
const message = parseJsonLine<StreamLine>(line);
if (!message) return;
@@ -125,10 +155,15 @@ export const claudeRunner: Runner = {
return;
}
+ case 'assistant':
+ if (!message.parent_tool_use_id) report(message.message?.usage, sink);
+ return;
+
case 'result':
if (message.is_error) {
return sink.fail('AGENT_FAILED', message.result || message.subtype || 'Claude Code reported an error');
}
+ if (!generated) report(message.usage, sink);
return sink.done(message.stop_reason || 'end_turn');
}
};
diff --git a/src/daemon/agent/runners/codex.ts b/src/daemon/agent/runners/codex.ts
index 0dfc49c..1232ce2 100644
--- a/src/daemon/agent/runners/codex.ts
+++ b/src/daemon/agent/runners/codex.ts
@@ -21,10 +21,19 @@ interface Item {
command?: string;
}
+/** Codex counts cached input inside `input_tokens`; it is a subset, not an addition. */
+interface TokenCounts {
+ input_tokens?: number;
+ cached_input_tokens?: number;
+ output_tokens?: number;
+ total_tokens?: number;
+}
+
interface TypedEvent {
type?: string;
thread_id?: string;
item?: Item;
+ usage?: TokenCounts;
error?: { message?: string };
message?: string;
}
@@ -37,6 +46,7 @@ interface LegacyEvent {
session_id?: string;
query?: string;
error?: string;
+ info?: { total_token_usage?: TokenCounts; last_token_usage?: TokenCounts };
};
}
@@ -114,6 +124,17 @@ export const codexRunner: Runner = {
return finish(msg.message, sink);
case 'web_search_begin':
return sink.tool(randomUUID(), WEB_TOOL);
+ case 'token_count': {
+ const last = msg.info?.last_token_usage ?? msg.info?.total_token_usage;
+ const total = msg.info?.total_token_usage ?? last;
+ if (last) {
+ sink.usage({
+ contextTokens: (last.input_tokens ?? 0) + (last.output_tokens ?? 0),
+ outputTokens: total?.output_tokens ?? 0,
+ });
+ }
+ return;
+ }
case 'task_complete':
return sink.done('end_turn');
case 'error':
@@ -141,8 +162,16 @@ export const codexRunner: Runner = {
return;
}
- case 'turn.completed':
+ case 'turn.completed': {
+ const usage = frame.usage;
+ if (usage) {
+ sink.usage({
+ contextTokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),
+ outputTokens: usage.output_tokens ?? 0,
+ });
+ }
return sink.done('end_turn');
+ }
case 'turn.failed':
return sink.fail('AGENT_FAILED', frame.error?.message || 'Codex could not finish the turn');
diff --git a/src/daemon/agent/runners/drive.ts b/src/daemon/agent/runners/drive.ts
index ba26bc9..b867ea1 100644
--- a/src/daemon/agent/runners/drive.ts
+++ b/src/daemon/agent/runners/drive.ts
@@ -124,6 +124,7 @@ export function runStream(
session: (id) => {
if (id) sessionId = id;
},
+ usage: (usage) => emit({ kind: 'usage', usage }),
done: (stopReason) =>
settle(() => {
flush();
diff --git a/src/daemon/agent/runners/types.ts b/src/daemon/agent/runners/types.ts
index f1402a8..84f7d4b 100644
--- a/src/daemon/agent/runners/types.ts
+++ b/src/daemon/agent/runners/types.ts
@@ -1,3 +1,4 @@
+import type { TokenUsage } from '@/lib/actions/protocol';
import type { AgentKind, AgentProblem } from '@/lib/agents/catalog';
import type { AgentSettings } from '../config';
@@ -48,6 +49,8 @@ export interface StreamSink {
/** A tool the daemon cannot see itself — web search and the like. MCP calls report themselves. */
tool(toolId: string, name: string): void;
session(id: string): void;
+ /** Token counts this CLI reported, normalized to the shared shape. Optional — not every CLI reports them. */
+ usage(usage: TokenUsage): void;
done(stopReason: string): void;
fail(code: string, message: string): void;
}
diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.ts
index 440d722..99ddfa4 100644
--- a/src/lib/actions/protocol.ts
+++ b/src/lib/actions/protocol.ts
@@ -10,7 +10,7 @@ import type { SiteMapDraft } from '@/lib/skills/site-map';
export const ACTION_CHANNEL = 'browsentic/action';
export const BRIDGE_CHANNEL = 'browsentic/bridge';
-export const SOCKET_PROTOCOL_VERSION = 15;
+export const SOCKET_PROTOCOL_VERSION = 16;
export const EXTERNAL_RUN_ID = 'external';
@@ -56,9 +56,18 @@ export type RunEvent =
| { kind: 'approval'; toolId: string; action: string; input: unknown; site?: string }
| { kind: 'toolResult'; toolId: string; ok: boolean; summary: string }
| { kind: 'session'; agent: AgentKind; agentSessionId: string | null }
+ | { kind: 'usage'; usage: TokenUsage }
| { kind: 'done'; stopReason: string }
| { kind: 'error'; code: string; message: string };
+/** Token counts as the agent CLI reported them, normalized by its runner. */
+export interface TokenUsage {
+ /** Tokens occupying the model's context window after its last call — prompt, cache and reply together. */
+ contextTokens: number;
+ /** Tokens the model generated over the run that reported this. */
+ outputTokens: number;
+}
+
/** Which secret the extension is about to prove it holds. The secret itself never crosses the wire. */
export type SocketAuth = { kind: 'pair' } | { kind: 'session' };
diff --git a/src/lib/bridge/run-items.ts b/src/lib/bridge/run-items.ts
index 8a0180b..abea697 100644
--- a/src/lib/bridge/run-items.ts
+++ b/src/lib/bridge/run-items.ts
@@ -61,6 +61,7 @@ export function reduce(items: RunItem[], event: RunEvent): RunItem[] {
return patchTool(items, event.toolId, { ok: event.ok, summary: event.summary, awaiting: false });
case 'session':
+ case 'usage':
return items;
case 'done':
diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.ts
index 2fcfbe5..879c1af 100644
--- a/src/lib/bridge/run-port.ts
+++ b/src/lib/bridge/run-port.ts
@@ -281,6 +281,8 @@ async function absorb(runId: string, event: RunEvent): Promise<void> {
});
} else if (event.kind === 'toolResult') {
await patchSession(sessionId, { pendingApproval: undefined });
+ } else if (event.kind === 'usage') {
+ await patchSession(sessionId, { usage: event.usage });
}
if (event.kind === 'done' || event.kind === 'error') await settle(sessionId);
@@ -472,6 +474,7 @@ async function restore(sessionId: string, anchor: TabAnchor): Promise<void> {
turns: meta.turns,
agent: meta.agent,
agentSessionId: meta.agentSessionId,
+ usage: meta.usage,
url: meta.url,
title: titleOf(meta) ?? anchor.title,
},
@@ -523,6 +526,7 @@ async function persist(sessionId: string): Promise<void> {
host: session?.host ?? stored?.host,
agent: session?.agent ?? stored?.agent,
agentSessionId: session?.agentSessionId ?? stored?.agentSessionId,
+ usage: session?.usage ?? stored?.usage,
createdAt: session?.createdAt ?? stored?.createdAt ?? now,
updatedAt: now,
},
diff --git a/src/lib/bridge/session-store.ts b/src/lib/bridge/session-store.ts
index 5db5f4c..b1f5bc4 100644
--- a/src/lib/bridge/session-store.ts
+++ b/src/lib/bridge/session-store.ts
@@ -1,4 +1,5 @@
import { browser } from 'wxt/browser';
+import type { TokenUsage } from '@/lib/actions/protocol';
import type { AgentKind } from '@/lib/agents/catalog';
import type { RunItem } from './run-items';
import { nameSession } from './socket';
@@ -21,6 +22,8 @@ export interface StoredSessionMeta {
/** The agent CLI that owns `agentSessionId` — another agent cannot resume it. */
agent?: AgentKind;
agentSessionId?: string;
+ /** The agent's own token counts, as of its most recent report. */
+ usage?: TokenUsage;
turns: number;
titledAtTurn?: number;
namingAt?: number;
diff --git a/src/lib/bridge/tab-sessions.ts b/src/lib/bridge/tab-sessions.ts
index 3b019be..0927c4e 100644
--- a/src/lib/bridge/tab-sessions.ts
+++ b/src/lib/bridge/tab-sessions.ts
@@ -1,4 +1,5 @@
import { browser } from 'wxt/browser';
+import type { TokenUsage } from '@/lib/actions/protocol';
import type { AgentKind } from '@/lib/agents/catalog';
export const TAB_SESSIONS_KEY = 'browsentic/tabSessions';
@@ -26,6 +27,8 @@ export interface TabSession {
runId: string | null;
agent?: AgentKind;
agentSessionId?: string;
+ /** The agent's own token counts, as of its most recent report. */
+ usage?: TokenUsage;
turns: number;
createdAt: number;
lastActivityAt: number;
@@ -118,7 +121,15 @@ export async function ensureSessionForTab(anchor: TabAnchor): Promise<Ensured> {
}
export function bindStoredSession(
- fields: { sessionId: string; turns: number; agent?: AgentKind; agentSessionId?: string; url?: string; title?: string },
+ fields: {
+ sessionId: string;
+ turns: number;
+ agent?: AgentKind;
+ agentSessionId?: string;
+ usage?: TokenUsage;
+ url?: string;
+ title?: string;
+ },
anchor: TabAnchor,
): Promise<TabSession> {
return mutateTabSessions((map) => {
@@ -138,6 +149,7 @@ export function bindStoredSession(
runId: null,
agent: fields.agent,
agentSessionId: fields.agentSessionId,
+ usage: fields.usage,
turns: fields.turns,
createdAt: now,
lastActivityAt: now,