Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): build contract slot rows from pane accounting
Jack Rudenkoc454a44da2bd
diff --git a/packages/cli/src/pane/accounting.test.ts b/packages/cli/src/pane/accounting.test.tsnew file mode 100644index 00000000..b81e8e43--- /dev/null+++ b/packages/cli/src/pane/accounting.test.ts@@ -0,0 +1,231 @@+import { afterEach, describe, expect, test } from "bun:test";+import { copyFileSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { nativeRouteFor } from "../providers/native-route.js";+import { readTokenStatsAt } from "../team-stats.js";+import {+ mergeAccounting,+ parsePinnedSpec,+ readTokenFileCached,+ resolveProvider,+ tokenFileHasData,+} from "./accounting.js";+import { toSlotRow } from "./slot-row.js";+import { FIXTURES } from "./test-helpers/fixtures.js";+import type { PaneSnapshot } from "./types.js";++/** Token files are real proxy outputs (a served foreign session, and the initialised zeros). */+const FOREIGN = join(FIXTURES, "token-files", "foreign-grok.json");+const ZEROS = join(FIXTURES, "token-files", "initialised-zeros.json");++const dirs: string[] = [];+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++function snap(over: Partial<PaneSnapshot> = {}): PaneSnapshot {+ return {+ paneId: "c1-k0-t01-abcdef",+ phase: "RUNNING",+ state: "RUNNING",+ reason: null,+ detail: null,+ activity: "Bash",+ lastActivityAt: "2026-10-06T01:00:00.000Z",+ idleSeconds: 0,+ turnsCompleted: 0,+ tokensIn: 33324,+ tokensOut: 44,+ toolCalls: 2,+ liveAnswerBytes: 0,+ exitCode: null,+ captureSource: null,+ turnSource: "transcript",+ pendingInputs: 0,+ connected: true,+ startedAt: "2026-10-06T00:59:00.000Z",+ endedAt: null,+ transcriptPath: "/x.jsonl",+ panePid: 1,+ screenTail: "",+ anomalies: [],+ ...over,+ };+}++describe("mergeAccounting", () => {+ test("a served token file is authoritative: billed_input_tokens (never input_tokens), output, cost, Σ tool calls", () => {+ const tf = readTokenStatsAt(FOREIGN)!;+ expect(tf.billed_input_tokens).toBe(221807);+ expect(tf.input_tokens).toBe(39594); // the CURRENT context, not the session's input+ const a = mergeAccounting(snap(), tf);+ expect(a).toEqual({+ tokensIn: 221807,+ tokensOut: 21435,+ costUsd: 0.30754699999999996,+ toolCalls: 59 + 26 + 14 + 10,+ provider: "X-ai",+ });+ });++ test("the initialised zeros carry no data: tokens and tool calls come from the transcript, cost is null", () => {+ const tf = readTokenStatsAt(ZEROS)!;+ expect(tokenFileHasData(tf)).toBe(false);+ expect(mergeAccounting(snap(), tf)).toEqual({+ tokensIn: 33324,+ tokensOut: 44,+ costUsd: null,+ toolCalls: 2,+ provider: null,+ });+ });++ test("no token file (a native route writes none): transcript accounting, cost null", () => {+ expect(mergeAccounting(snap(), null, { model: "haiku", spawnModel: null })).toEqual({+ tokensIn: 33324,+ tokensOut: 44,+ costUsd: null,+ toolCalls: 2,+ provider: "Anthropic (Native)",+ });+ });+});++describe("resolveProvider (M11)", () => {+ test("the token file's provider_name wins (served-by)", () => {+ expect(+ resolveProvider({+ model: "grok-4.7",+ spawnModel: "[email protected]",+ tokenFile: readTokenStatsAt(FOREIGN),+ })+ ).toBe("X-ai");+ });++ test("a native name resolves through nativeRouteFor before any route lookup", () => {+ for (const m of ["haiku", "claude-opus-5", "opus"]) {+ expect(nativeRouteFor(m)).not.toBeNull();+ expect(resolveProvider({ model: m, spawnModel: null, tokenFile: null })).toBe(+ "Anthropic (Native)"+ );+ }+ });++ test("a native model never yields a token file with a different provider", () => {+ expect(+ resolveProvider({ model: "haiku", spawnModel: null, tokenFile: readTokenStatsAt(ZEROS) })+ ).toBe("Anthropic (Native)");+ });++ test("a pinned single-hop spec names its provider; a chain or a bare name is not known yet", () => {+ expect(+ resolveProvider({ model: "grok-4.7", spawnModel: "[email protected]", tokenFile: null })+ ).toBe("xAI");+ expect(+ resolveProvider({ model: "glm-5", spawnModel: "zgo@glm-5+or@z-ai/glm-5", tokenFile: null })+ ).toBeNull();+ expect(resolveProvider({ model: "kimi-k3", spawnModel: null, tokenFile: null })).toBeNull();+ });++ test("parsePinnedSpec", () => {+ expect(parsePinnedSpec("or@qwen/qwen3.8-max")).toEqual({+ provider: "openrouter",+ model: "qwen/qwen3.8-max",+ });+ expect(parsePinnedSpec("a@x+b@y")).toBeNull();+ expect(parsePinnedSpec("bare-name")).toBeNull();+ expect(parsePinnedSpec(null)).toBeNull();+ });+});++describe("readTokenFileCached", () => {+ test("re-reads only when mtime or size changes; a missing file is null", () => {+ const dir = mkdtempSync(join(tmpdir(), "pane-acct-"));+ dirs.push(dir);+ const p = join(dir, "tokens.json");+ expect(readTokenFileCached(p)).toBeNull();+ copyFileSync(ZEROS, p);+ const fixed = new Date("2026-10-06T00:00:00Z");+ utimesSync(p, fixed, fixed);+ expect(readTokenFileCached(p)?.total_tokens).toBe(0);+ copyFileSync(FOREIGN, p);+ utimesSync(p, fixed, fixed);+ // same mtime, different size → re-read+ expect(readTokenFileCached(p)?.provider_name).toBe("X-ai");+ writeFileSync(p, "{partial");+ expect(readTokenFileCached(p)).toBeNull();+ });+});++describe("toSlotRow (§8 B)", () => {+ test("a running row: idle seconds from last activity, activity kept, reason null", () => {+ const now = Date.parse("2026-10-06T01:00:07.900Z");+ const row = toSlotRow(+ { slot: "01", model: "haiku", spawnModel: null },+ snap(),+ mergeAccounting(snap(), null, { model: "haiku", spawnModel: null }),+ now+ );+ expect(row).toEqual({+ slot: "01",+ model: "haiku",+ provider: "Anthropic (Native)",+ state: "RUNNING",+ reason: null,+ tokens_in: 33324,+ tokens_out: 44,+ cost_usd: null,+ tool_calls: 2,+ turns_completed: 0,+ last_activity_at: "2026-10-06T01:00:00.000Z",+ idle_seconds: 7,+ activity: "Bash",+ pane: "c1-k0-t01-abcdef",+ });+ expect(Object.keys(row).sort()).toEqual(+ [+ "activity",+ "cost_usd",+ "idle_seconds",+ "last_activity_at",+ "model",+ "pane",+ "provider",+ "reason",+ "slot",+ "state",+ "tokens_in",+ "tokens_out",+ "tool_calls",+ "turns_completed",+ ].sort()+ );+ });++ test("terminal rows: idle_seconds and activity null; COMPLETED has no reason; FAILED keeps it", () => {+ const acct = mergeAccounting(snap(), readTokenStatsAt(FOREIGN));+ const done = toSlotRow(+ { slot: "02", model: "grok-4.7", spawnModel: "[email protected]" },+ snap({ state: "COMPLETED", phase: "COMPLETED", reason: null, activity: "x" }),+ acct+ );+ expect([done.idle_seconds, done.activity, done.reason]).toEqual([null, null, null]);+ const failed = toSlotRow(+ { slot: "03", model: "m", spawnModel: null },+ snap({ state: "FAILED", phase: "FAILED", reason: "api_error" }),+ acct+ );+ expect(failed.reason).toBe("api_error");+ expect(failed.idle_seconds).toBeNull();+ });++ test("a pane that never spawned has pane null", () => {+ const row = toSlotRow(+ { slot: "04", model: "m", spawnModel: null },+ snap({ paneId: "", state: "FAILED", phase: "FAILED", reason: "pane_lost" }),+ mergeAccounting(snap(), null)+ );+ expect(row.pane).toBeNull();+ });+});diff --git a/packages/cli/src/pane/accounting.ts b/packages/cli/src/pane/accounting.tsnew file mode 100644index 00000000..93a232e0--- /dev/null+++ b/packages/cli/src/pane/accounting.ts@@ -0,0 +1,108 @@+/**+ * Tokens, cost, tool calls and provider for one pane (architecture §2.12, M6, M11).+ *+ * The proxy's token file is authoritative when it carries data (a foreign route writes+ * it as it serves). A native route writes no token data (research §2.5: the file stays+ * at its initialised zeros), so tokens and tool calls then come from the transcript and+ * `cost_usd` stays null: Claude Code's own `cost-state` prices at API rates, which is+ * fictional spend for a subscription user (D12).+ */++import { statSync } from "node:fs";+import { parseModelChain, parseModelSpec } from "../providers/model-parser.js";+import { nativeRouteFor } from "../providers/native-route.js";+import { getProviderByName } from "../providers/provider-definitions.js";+import { type ModelTokenStats, readTokenStatsAt } from "../team-stats.js";+import type { PaneSnapshot } from "./types.js";++export type TokenFileStats = ModelTokenStats;++const cache = new Map<string, { mtimeMs: number; size: number; stats: TokenFileStats | null }>();++/** `readTokenStatsAt`, re-read only when the file's mtime or size changed. */+export function readTokenFileCached(path: string): TokenFileStats | null {+ let st: { mtimeMs: number; size: number };+ try {+ const s = statSync(path);+ st = { mtimeMs: s.mtimeMs, size: s.size };+ } catch {+ cache.delete(path);+ return null;+ }+ const hit = cache.get(path);+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.stats;+ const stats = readTokenStatsAt(path);+ // A mid-write read returns null; do not cache it, the next tick retries.+ if (stats) cache.set(path, { ...st, stats });+ return stats;+}++/** The token file carries real data: the proxy served at least one request. */+export function tokenFileHasData(t: TokenFileStats | null): t is TokenFileStats {+ return !!t && (!!t.provider_name || (t.total_tokens ?? 0) > 0);+}++export interface Accounting {+ tokensIn: number | null;+ tokensOut: number | null;+ costUsd: number | null;+ toolCalls: number;+ provider: string | null;+}++export function mergeAccounting(+ snap: Pick<PaneSnapshot, "tokensIn" | "tokensOut" | "toolCalls">,+ tokenFile: TokenFileStats | null,+ ids: { model: string; spawnModel: string | null } | null = null+): Accounting {+ const provider = ids+ ? resolveProvider({ model: ids.model, spawnModel: ids.spawnModel, tokenFile })+ : (tokenFile?.provider_name ?? null);+ if (tokenFileHasData(tokenFile)) {+ const toolCalls = (tokenFile.tool_calls ?? []).reduce((n, t) => n + (t.count ?? 0), 0);+ return {+ // billed_input_tokens is the cumulative input; input_tokens is the CURRENT context.+ tokensIn: tokenFile.billed_input_tokens ?? null,+ tokensOut: tokenFile.output_tokens ?? null,+ costUsd: typeof tokenFile.total_cost === "number" ? tokenFile.total_cost : null,+ toolCalls,+ provider,+ };+ }+ return {+ tokensIn: snap.tokensIn,+ tokensOut: snap.tokensOut,+ costUsd: null,+ toolCalls: snap.toolCalls,+ provider,+ };+}++/** `provider@model`, a single hop only; null for a bare name or a `+` chain. */+export function parsePinnedSpec(+ spawnModel: string | null+): { provider: string; model: string } | null {+ if (!spawnModel) return null;+ if (parseModelChain(spawnModel).length !== 1) return null;+ if (!/^[^@]+@.+$/.test(spawnModel)) return null;+ const p = parseModelSpec(spawnModel);+ return p.isExplicitProvider ? { provider: p.provider, model: p.model } : null;+}++/**+ * Display name of the claudish provider serving the slot. The token file is+ * observation, not routing; `nativeRouteFor` runs before any route lookup (CLAUDE.md+ * invariant); a pinned spec names its provider; anything else is not known yet.+ */+export function resolveProvider(input: {+ model: string;+ spawnModel: string | null;+ tokenFile: TokenFileStats | null;+}): string | null {+ if (input.tokenFile?.provider_name) return input.tokenFile.provider_name;+ const native = nativeRouteFor(input.model);+ if (native) return getProviderByName("native-anthropic")?.displayName ?? native.displayName;+ const pinned = parsePinnedSpec(input.spawnModel);+ if (pinned) return getProviderByName(pinned.provider)?.displayName ?? pinned.provider;+ return null;+}diff --git a/packages/cli/src/pane/slot-row.ts b/packages/cli/src/pane/slot-row.tsnew file mode 100644index 00000000..8158db9b--- /dev/null+++ b/packages/cli/src/pane/slot-row.ts@@ -0,0 +1,39 @@+/**+ * One contract `SlotRow` from a pane snapshot and its accounting (architecture §2.12,+ * §8 B). Pure; the polling verbs call it on memory only.+ */++import type { Accounting } from "./accounting.js";+import { type SlotRow, isTerminalState } from "./contract.js";+import type { PaneSnapshot } from "./types.js";++export function toSlotRow(+ id: { slot: string; model: string; spawnModel: string | null },+ snap: PaneSnapshot,+ acct: Accounting,+ now: number = Date.now()+): SlotRow {+ const terminal = isTerminalState(snap.state);+ let idle: number | null = null;+ if (!terminal && snap.lastActivityAt) {+ const t = Date.parse(snap.lastActivityAt);+ if (Number.isFinite(t)) idle = Math.max(0, Math.floor((now - t) / 1000));+ }+ return {+ slot: id.slot,+ model: id.model,+ provider: acct.provider,+ state: snap.state,+ // set on FAILED / EMPTY / CANCELLED / TIMEOUT; null otherwise+ reason: snap.state === "COMPLETED" || !terminal ? null : snap.reason,+ tokens_in: acct.tokensIn,+ tokens_out: acct.tokensOut,+ cost_usd: acct.costUsd,+ tool_calls: acct.toolCalls,+ turns_completed: snap.turnsCompleted,+ last_activity_at: snap.lastActivityAt,+ idle_seconds: idle,+ activity: terminal ? null : snap.activity,+ pane: snap.paneId || null,+ };+}diff --git a/packages/cli/src/pane/types.ts b/packages/cli/src/pane/types.tsnew file mode 100644index 00000000..5ecee7a5--- /dev/null+++ b/packages/cli/src/pane/types.ts@@ -0,0 +1,62 @@+/**+ * Shapes shared between the pure pane core (this phase) and `PaneSession` (architecture+ * §2.9): what a settled turn hands its owner, the owner's verdict, and the in-memory+ * snapshot every polling verb reads.+ */++import type { FailureReason, SlotState } from "./contract.js";+import type { Delivery } from "./prompt-delivery.js";+import type { SettledBy } from "./settle-rule.js";+import type { Phase } from "./slot-state.js";+import type { TurnView } from "./transcript-follower.js";++export interface SettledTurn {+ index: number;+ answer: string;+ apiError: TurnView["apiError"];+ stopReason: string | null;+ captureSource: "transcript" | "screen" | "none";+ settledBy: SettledBy | "screen";+ /** owners map `complete === false` → prompt_not_read */+ delivery: {+ mode: Delivery["mode"];+ linesTotal: number | null;+ linesRead: number | null;+ complete: boolean | null;+ preambleBytes: number;+ };+}++export interface FinalVerdict {+ state: "COMPLETED" | "EMPTY" | "FAILED";+ reason?: FailureReason;+ detail?: string;+}++export interface PaneSnapshot {+ paneId: string;+ phase: Phase;+ state: SlotState;+ reason: FailureReason | null;+ detail: string | null;+ activity: string | null;+ lastActivityAt: string | null;+ idleSeconds: number | null;+ turnsCompleted: number;+ /** from the transcript (main chain + subagents, once per message.id); null = no source yet */+ tokensIn: number | null;+ tokensOut: number | null;+ toolCalls: number;+ liveAnswerBytes: number;+ exitCode: number | null;+ captureSource: SettledTurn["captureSource"] | null;+ turnSource: "transcript" | "screen";+ pendingInputs: number;+ connected: boolean;+ startedAt: string;+ endedAt: string | null;+ transcriptPath: string;+ panePid: number | null;+ screenTail: string;+ anomalies: string[];+}