Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(tokens): split prompt_tokens into the three input counters (item 6)
Jack Rudenkof9baf2effbae
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex 6fd015d2..83df2909 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -68,7 +68,7 @@ import { createGeminiSseStream } from "./shared/stream-parsers/gemini-sse.js";import { createOllamaJsonlStream } from "./shared/stream-parsers/ollama-jsonl.js";import { createResponsesStreamHandler } from "./shared/stream-parsers/openai-responses-sse.js";import { createStreamingResponseHandler } from "./shared/stream-parsers/openai-sse.js";-import { TokenTracker } from "./shared/token-tracker.js";+import { TokenTracker, type UsageCacheDetail } from "./shared/token-tracker.js";import { captureUpstreamError } from "./shared/upstream-error-capture.js";/**@@ -1404,20 +1404,25 @@ export class ComposedHandler implements ModelHandler {// Local mutable copy so we can null it out after firing (prevents double-firing)// without reassigning the function parameter.let pendingOnComplete = onComplete;- const onTokenUpdate = (input: number, output: number) => {+ // `input` is the FULL context size, always — never the cache-reduced figure+ // that rides on the wire. `detail` is the optional cached breakdown of that+ // same number and is used for COST ONLY; see UsageCacheDetail and+ // `context-window.md`, which records what happens when a reduced count+ // reaches the context accounting (auto-compaction silently disarms).+ const onTokenUpdate = (input: number, output: number, detail?: UsageCacheDetail) => {const strategy = this.options.tokenStrategy || "standard";switch (strategy) {case "accumulate-both":- this.tokenTracker.accumulateBoth(input, output);+ this.tokenTracker.accumulateBoth(input, output, detail);break;case "delta-aware":- this.tokenTracker.updateWithDelta(input, output);+ this.tokenTracker.updateWithDelta(input, output, detail);break;case "local":- this.tokenTracker.updateLocal(input, output);+ this.tokenTracker.updateLocal(input, output, detail);break;default:- this.tokenTracker.update(input, output);+ this.tokenTracker.update(input, output, detail);break;}// Fire onComplete after token update so recordStats() sees the final token counts.diff --git a/packages/cli/src/handlers/shared/remote-provider-types.ts b/packages/cli/src/handlers/shared/remote-provider-types.tsindex cbd5503f..e19beb8f 100644--- a/packages/cli/src/handlers/shared/remote-provider-types.ts+++ b/packages/cli/src/handlers/shared/remote-provider-types.ts@@ -29,6 +29,22 @@ export interface ModelPricing {inputCostPer1M: number;/** Cost per 1M output tokens in USD */outputCostPer1M: number;+ /**+ * Cost per 1M tokens READ from the provider's prompt cache, in USD.+ *+ * OPTIONAL, and its absence is a RULE, not a missing number: absent means+ * "this provider bills a cache read as ordinary input", which is the only+ * reading that cannot understate spend. It is deliberately NOT defaulted to+ * the industry-typical 0.1x of `inputCostPer1M` — that would be a hardcoded+ * price, and CLAUDE.md's "a default is a rule, never a pinned id" forbids it.+ *+ * NOTHING SUPPLIES THIS TODAY. `getModelPricing` never sets it and the+ * pricing cache has no repopulator for it, so every cache discount computed+ * from it is exactly zero and no existing session's cost changes by a cent.+ * It exists so that the arithmetic in `token-tracker.ts` is already correct+ * on the day a pricing source starts publishing the rate.+ */+ cacheReadCostPer1M?: number;/** Whether this pricing is an estimate (not from official sources) */isEstimate?: boolean;/**diff --git a/packages/cli/src/handlers/shared/stream-parsers/message-start-usage.ts b/packages/cli/src/handlers/shared/stream-parsers/message-start-usage.tsindex 85f5e6b0..8430c2d0 100644--- a/packages/cli/src/handlers/shared/stream-parsers/message-start-usage.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/message-start-usage.ts@@ -19,13 +19,33 @@* Carrying the previous turn's count forward keeps the estimate in the right* order of magnitude; 100 remains only as the genuinely-unknown first-turn* fallback.+ *+ * ## Why the two cache counters are seeded at 0+ *+ * Claude Code merges the closing delta's usage over this object per key, and it+ * only takes a delta value that is greater than zero (verified in the 2.1.273+ * binary: `n.cache_creation_input_tokens !== null && n.cache_creation_input_tokens > 0+ * ? … : e.cache_creation_input_tokens`). So a delta reporting+ * `cache_creation_input_tokens: 0` — which is every provider that does not+ * report cache WRITES, i.e. most of them — falls back to whatever this seed+ * carried. Leaving the key out made that fallback `undefined`, and the client+ * sums the three input counters raw in places that do not coalesce, where an+ * `undefined` turns the conversation size into `NaN`.+ *+ * Emitting an explicit 0 changes no total anywhere (it is the value every+ * consumer already coalesced to) and removes that hazard for all five parsers+ * that seed from here.*/export function messageStartUsage(priorInputTokens?: number): {input_tokens: number;output_tokens: number;+ cache_read_input_tokens: number;+ cache_creation_input_tokens: number;} {return {input_tokens: priorInputTokens && priorInputTokens > 0 ? priorInputTokens : 100,output_tokens: 1,+ cache_read_input_tokens: 0,+ cache_creation_input_tokens: 0,};}diff --git a/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/openai-sse.tsindex 75d231fb..59b2a9a7 100644--- a/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts@@ -19,6 +19,7 @@ import { isWebSearchToolCall, warnWebSearchUnsupported } from "../web-search-detimport { type BlockRef, createBlockWriter } from "./block-writer.js";import { messageStartUsage } from "./message-start-usage.js";import { type ThinkSplit, createThinkTagSplitter } from "./think-tag-splitter.js";+import { splitPromptTokens } from "./usage-cache-split.js";/*** Hard ceiling, in characters, on ONE logged raw SSE payload.@@ -178,7 +179,17 @@ export function createStreamingResponseHandler(adapter: any,target: string,middlewareManager: any,- onTokenUpdate?: (input: number, output: number) => void,+ /**+ * `input` is ALWAYS `prompt_tokens` — the full context size. The cached+ * breakdown rides in the third argument and is for COST ONLY; handing the+ * reduced wire figure to the tracker would report a nearly-full conversation+ * as almost empty and disarm auto-compaction (`context-window.md`).+ */+ onTokenUpdate?: (+ input: number,+ output: number,+ detail?: { cacheReadTokens: number; cacheCreationTokens: number }+ ) => void,toolSchemas?: any[], // Tool schemas for validationtoolNameMap?: Map<string, string>, // Truncated → original tool name mappingpriorInputTokens?: number, // Last request's context size — seeds message_start.usage@@ -663,6 +674,30 @@ export function createStreamingResponseHandler(writer.close(writer.openText());}+ // The three input counters are derived ONCE and used for both the+ // wire and the cost update below, so the two cannot disagree.+ const split = splitPromptTokens(state.usage);+ // One degenerate turn is sent UNSPLIT, and this is not a special+ // case so much as the merge rule read honestly.+ //+ // Claude Code only lets a delta value override its running total+ // when that value is GREATER THAN ZERO (2.1.273:+ // `n.input_tokens !== null && n.input_tokens > 0 ? n.input_tokens : e.input_tokens`).+ // So on a turn whose input is entirely cache — possible only when+ // the request repeats one already cached, i.e. a retry — an+ // `input_tokens: 0` is DISCARDED and the message_start seed (the+ // PREVIOUS turn's full context) survives beside a full-size+ // `cache_read_input_tokens`. The client would then sum the two and+ // believe the conversation is roughly twice its real size.+ //+ // Reporting that turn as ordinary input keeps the client's sum+ // exactly equal to `prompt_tokens`, which is the invariant that+ // matters. It costs nothing on the money side: the cost split is+ // taken from `splitPromptTokens` independently, below.+ const fullyCached = split.promptTokens > 0 && split.inputTokens === 0;+ const wireInput = fullyCached ? split.promptTokens : split.inputTokens;+ const wireCacheRead = fullyCached ? 0 : split.cacheReadTokens;+ const wireCacheCreation = fullyCached ? 0 : split.cacheCreationTokens;send("message_delta", {type: "message_delta",delta: { stop_reason: stopReason, stop_sequence: null },@@ -671,10 +706,26 @@ export function createStreamingResponseHandler(// could only carry an estimate. Omitting it left the client// believing every conversation was 100 tokens, which silently// disabled auto-compaction on every openai-sse provider.+ //+ // All THREE keys ship TOGETHER, unconditionally, and that is not+ // stylistic. Claude Code reconstructs the conversation size by+ // summing them (verified in the 2.1.273 binary:+ // `input_tokens + cache_creation_input_tokens + cache_read_input_tokens`,+ // read by both the context meter and the auto-compaction+ // threshold), so a reduced `input_tokens` sent WITHOUT its two+ // siblings understates the context by exactly the cached portion+ // — on the measured xAI turn, 20352 of 20379 tokens. That is the+ // one shape that reproduces the failure the paragraph above+ // records. `splitPromptTokens` guarantees the three sum back to+ // `prompt_tokens`.+ //+ // `input_tokens` is emitted even when it is 0 (a fully-cached+ // turn), because omitting it is the same silent-omission bug in a+ // different disguise.usage: {- ...(state.usage?.prompt_tokens- ? { input_tokens: state.usage.prompt_tokens }- : {}),+ input_tokens: wireInput,+ cache_read_input_tokens: wireCacheRead,+ cache_creation_input_tokens: wireCacheCreation,output_tokens: state.usage?.completion_tokens || 0,},});@@ -688,7 +739,16 @@ export function createStreamingResponseHandler(log(`[Streaming] Final usage: prompt=${state.usage.prompt_tokens || 0}, completion=${state.usage.completion_tokens || 0}`);- onTokenUpdate(state.usage.prompt_tokens || 0, state.usage.completion_tokens || 0);+ // FIRST ARGUMENT STAYS `prompt_tokens`: the tracker's input number+ // is the context-occupancy figure the status line renders and the+ // billing baseline the delta strategy compares against. The split+ // goes in the third argument, where only the cost arithmetic sees+ // it.+ const costSplit = splitPromptTokens(state.usage);+ onTokenUpdate(state.usage.prompt_tokens || 0, state.usage.completion_tokens || 0, {+ cacheReadTokens: costSplit.cacheReadTokens,+ cacheCreationTokens: costSplit.cacheCreationTokens,+ });} else {// Estimate tokens for local models that don't return usage data// Rough estimate: ~4 characters per tokendiff --git a/packages/cli/src/handlers/shared/stream-parsers/usage-cache-split.test.ts b/packages/cli/src/handlers/shared/stream-parsers/usage-cache-split.test.tsnew file mode 100644index 00000000..ee5fcd67--- /dev/null+++ b/packages/cli/src/handlers/shared/stream-parsers/usage-cache-split.test.ts@@ -0,0 +1,252 @@+/**+ * Item 6 — the prompt-token split, against a REAL capture.+ *+ * Every number asserted below is READ OUT OF a committed `.sse` capture, never+ * written by hand: `grok-4.6-openai-advisor-turn1.sse` carries+ * `prompt_tokens: 20379` with `prompt_tokens_details.cached_tokens: 20352`, which+ * is the extreme case the split exists for — 99.9% of the context served from+ * cache. The OpenRouter captures supply the `cache_write_tokens` spelling.+ *+ * The end-to-end half replays the capture through the real parser and reads the+ * emitted `message_delta`, so it sees the wire bytes a client would.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import type { Context } from "hono";++import { DefaultAPIFormat } from "../../../adapters/base-api-format.js";+import { createStreamingResponseHandler } from "./openai-sse.js";+import { splitPromptTokens } from "./usage-cache-split.js";++const CACHED_TURN = new URL(+ "../../../test-fixtures/sse-responses/grok-4.6-openai-advisor-turn1.sse",+ import.meta.url+);+const OPENROUTER_TURN = new URL(+ "../../../test-fixtures/sse-responses/gemini-3.1-pro-or-maxtokens-empty.sse",+ import.meta.url+);++/** Pull the LAST `usage` object out of a capture, exactly as the parser does. */+function capturedUsage(url: URL): Record<string, any> {+ const wire = readFileSync(url, "utf8");+ let found: Record<string, any> | undefined;+ for (const line of wire.split("\n")) {+ if (!line.startsWith("data: ")) continue;+ const payload = line.slice(6).trim();+ if (payload === "[DONE]") continue;+ try {+ const chunk = JSON.parse(payload);+ if (chunk.usage) found = chunk.usage;+ } catch {+ // Not every data line is a chunk; the parser tolerates that too.+ }+ }+ if (!found) throw new Error(`No usage object in ${url.pathname}`);+ return found;+}++function createMockContext(): Context {+ return {+ body(stream: ReadableStream, init?: ResponseInit) {+ return new Response(stream, init);+ },+ json() {+ throw new Error("Unexpected no-body error path");+ },+ } as unknown as Context;+}++async function closingUsage(url: URL): Promise<Record<string, number>> {+ const upstream = new Response(readFileSync(url, "utf8"), {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ const out = await createStreamingResponseHandler(+ createMockContext(),+ upstream,+ new DefaultAPIFormat("test-model"),+ "test-model",+ null+ ).text();++ let usage: Record<string, number> | undefined;+ for (const part of out.split("\n\n")) {+ const data = part+ .split("\n")+ .find((l) => l.startsWith("data: "))+ ?.slice(6);+ if (!data || data === "[DONE]") continue;+ const parsed = JSON.parse(data);+ if (parsed?.type === "message_delta") usage = parsed.usage;+ }+ if (!usage) throw new Error("no message_delta usage");+ return usage;+}++describe("splitPromptTokens — against real captures", () => {+ test("A: the xAI capture splits 20379 into 27 fresh + 20352 cached", () => {+ const usage = capturedUsage(CACHED_TURN);+ // Provenance guard: if the fixture is ever replaced, this test must fail+ // loudly rather than assert the new file's numbers as if they were these.+ expect(usage.prompt_tokens).toBe(20379);+ expect(usage.prompt_tokens_details.cached_tokens).toBe(20352);++ const split = splitPromptTokens(usage);+ expect(split.promptTokens).toBe(20379);+ expect(split.inputTokens).toBe(27);+ expect(split.cacheReadTokens).toBe(20352);+ expect(split.cacheCreationTokens).toBe(0);+ });++ test("B: the three parts always sum back to prompt_tokens", () => {+ for (const url of [CACHED_TURN, OPENROUTER_TURN]) {+ const split = splitPromptTokens(capturedUsage(url));+ expect(split.inputTokens + split.cacheReadTokens + split.cacheCreationTokens).toBe(+ split.promptTokens+ );+ }+ });++ test("C: OpenRouter's cache_write_tokens is the cache-creation counter", () => {+ const usage = capturedUsage(OPENROUTER_TURN);+ // The committed capture reports both counters as 0 — an uncached turn — so+ // this pins the FIELD NAME against that real shape and the arithmetic+ // against a copy of it that carries a write.+ expect(usage.prompt_tokens_details).toHaveProperty("cache_write_tokens");+ const withWrite = {+ ...usage,+ prompt_tokens: 100,+ prompt_tokens_details: { ...usage.prompt_tokens_details, cache_write_tokens: 40 },+ };+ const split = splitPromptTokens(withWrite);+ expect(split.cacheCreationTokens).toBe(40);+ expect(split.inputTokens).toBe(60);+ });++ test("D: a provider that reports no details degrades to all-ordinary-input", () => {+ const split = splitPromptTokens({ prompt_tokens: 1234, completion_tokens: 7 });+ expect(split.inputTokens).toBe(1234);+ expect(split.cacheReadTokens).toBe(0);+ expect(split.cacheCreationTokens).toBe(0);+ });++ test("E: absent, null and nonsense usage never throw and never go negative", () => {+ for (const input of [undefined, null, "", 0, { prompt_tokens: -5 }, { prompt_tokens: "x" }]) {+ const split = splitPromptTokens(input);+ expect(split.promptTokens).toBe(0);+ expect(split.inputTokens).toBe(0);+ expect(split.cacheReadTokens).toBe(0);+ expect(split.cacheCreationTokens).toBe(0);+ }+ });++ test("F: a cached count larger than the prompt is clamped, not trusted", () => {+ // Holds the sum invariant against a provider whose counters disagree.+ const split = splitPromptTokens({+ prompt_tokens: 100,+ prompt_tokens_details: { cached_tokens: 900, cache_write_tokens: 900 },+ });+ expect(split.cacheReadTokens).toBe(100);+ expect(split.cacheCreationTokens).toBe(0);+ expect(split.inputTokens).toBe(0);+ expect(split.inputTokens + split.cacheReadTokens + split.cacheCreationTokens).toBe(100);+ });+});++describe("onTokenUpdate keeps the FULL context in its first argument", () => {+ test("I: the tracker is told 20379, not the reduced 27", async () => {+ const seen: Array<{ input: number; output: number; detail?: any }> = [];+ const upstream = new Response(readFileSync(CACHED_TURN, "utf8"), {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ await createStreamingResponseHandler(+ createMockContext(),+ upstream,+ new DefaultAPIFormat("test-model"),+ "test-model",+ null,+ (input, output, detail) => seen.push({ input, output, detail })+ ).text();++ expect(seen.length).toBeGreaterThan(0);+ const last = seen[seen.length - 1];+ // THE rule from the design's money section: passing the reduced wire value+ // here would report a nearly-full conversation as almost empty and disarm+ // auto-compaction. The split rides in the third argument, for cost only.+ expect(last.input).toBe(20379);+ expect(last.detail).toEqual({ cacheReadTokens: 20352, cacheCreationTokens: 0 });+ });+});++describe("openai-sse message_delta carries all three input counters", () => {+ test("G: the cached capture ships 27 / 20352 / 0, summing to the full context", async () => {+ const usage = await closingUsage(CACHED_TURN);+ expect(usage.input_tokens).toBe(27);+ expect(usage.cache_read_input_tokens).toBe(20352);+ expect(usage.cache_creation_input_tokens).toBe(0);+ // The client re-derives the conversation size from exactly this sum, so this+ // assertion is the whole safety argument for shipping a reduced input_tokens.+ expect(+ usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens+ ).toBe(20379);+ });++ test("J: a fully-cached turn is reported unsplit, so the client's sum stays right", async () => {+ // Reached only when a request repeats one already cached (a retry): the new+ // user message is never in the cached prefix. The client's usage merge+ // DISCARDS a delta `input_tokens: 0` and keeps its message_start seed, which+ // would then be summed with a full-size cache read and roughly double the+ // reported conversation size. Reporting the turn as ordinary input keeps+ // the sum exactly equal to prompt_tokens.+ const wire = readFileSync(CACHED_TURN, "utf8").replace(+ '"cached_tokens":20352',+ '"cached_tokens":20379'+ );+ const upstream = new Response(wire, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ const out = await createStreamingResponseHandler(+ createMockContext(),+ upstream,+ new DefaultAPIFormat("test-model"),+ "test-model",+ null+ ).text();+ const usage = out+ .split("\n\n")+ .map((p) =>+ p+ .split("\n")+ .find((l) => l.startsWith("data: "))+ ?.slice(6)+ )+ .filter((d): d is string => Boolean(d) && d !== "[DONE]")+ .map((d) => JSON.parse(d))+ .filter((p) => p?.type === "message_delta")+ .pop()?.usage;++ expect(usage.input_tokens).toBe(20379);+ expect(usage.cache_read_input_tokens).toBe(0);+ expect(usage.cache_creation_input_tokens).toBe(0);+ expect(+ usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens+ ).toBe(20379);+ });++ test("H: all three keys are PRESENT even when two of them are zero", async () => {+ const usage = await closingUsage(OPENROUTER_TURN);+ expect(Object.keys(usage).sort()).toEqual([+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+ "input_tokens",+ "output_tokens",+ ]);+ expect(usage.cache_read_input_tokens).toBe(0);+ expect(usage.cache_creation_input_tokens).toBe(0);+ expect(usage.input_tokens).toBe(8);+ });+});diff --git a/packages/cli/src/handlers/shared/stream-parsers/usage-cache-split.ts b/packages/cli/src/handlers/shared/stream-parsers/usage-cache-split.tsnew file mode 100644index 00000000..d37604d8--- /dev/null+++ b/packages/cli/src/handlers/shared/stream-parsers/usage-cache-split.ts@@ -0,0 +1,83 @@+/**+ * Split an OpenAI-shaped `usage` object's `prompt_tokens` into the three+ * Anthropic input counters.+ *+ * `prompt_tokens` is the FULL context the provider billed for. OpenAI-compatible+ * providers report the cached portion of it as a SUBSET, under+ * `prompt_tokens_details`, and claudish previously discarded that detail+ * entirely — so every turn looked uncached to both the client and the cost+ * accounting.+ *+ * ## Field names: observed, never invented+ *+ * Only two keys are read, and both appear verbatim in captures committed to+ * `test-fixtures/sse-responses/`:+ *+ * - `cached_tokens` — xAI (`grok-4.6-openai-advisor-turn1.sse`:+ * `prompt_tokens: 20379`, `cached_tokens: 20352`)+ * and OpenRouter.+ * - `cache_write_tokens` — OpenRouter's cache-CREATION counter+ * (`gemini-3.1-pro-or-maxtokens-*.sse`). Plain OpenAI+ * does not report cache writes at all, so this is 0+ * for most providers, which is correct: nothing was+ * written.+ *+ * A provider that spells either differently reports 0 here, and 0 is the+ * pre-change behaviour exactly — the split degrades to "all of it is ordinary+ * input", never to a wrong number.+ *+ * ## The invariant every consumer depends on+ *+ * inputTokens + cacheReadTokens + cacheCreationTokens === promptTokens+ *+ * Claude Code re-derives the conversation size by summing those three+ * (verified against the client binary, 2.1.273:+ * `function FRn(e){return e.input_tokens+e.cache_creation_input_tokens+e.cache_read_input_tokens}`,+ * used by the auto-compaction threshold and the context meter). A split whose+ * parts do not add back up therefore moves the client's idea of how full the+ * context is — which is the failure mode `message-start-usage.ts` documents.+ * The clamps below exist to hold the invariant against a provider that reports a+ * cached count larger than the prompt it belongs to.+ */++export interface PromptTokenSplit {+ /** The full context size — `prompt_tokens`, unchanged. NEVER the reduced value. */+ promptTokens: number;+ /** Uncached, freshly-read input: `promptTokens - cacheRead - cacheCreation`. */+ inputTokens: number;+ /** Tokens served from the provider's prompt cache. */+ cacheReadTokens: number;+ /** Tokens written INTO the provider's prompt cache this turn. */+ cacheCreationTokens: number;+}++function nonNegativeInt(value: unknown): number {+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;+}++/**+ * Derive the three-way split from a provider `usage` object. Safe on `null`,+ * `undefined` and anything that is not an object: it runs on the stream's+ * closing path, where refusing to produce a number would cost the turn's+ * accounting entirely.+ */+export function splitPromptTokens(usage: unknown): PromptTokenSplit {+ const u = (usage ?? {}) as Record<string, unknown>;+ const promptTokens = nonNegativeInt(u.prompt_tokens);+ const details = (u.prompt_tokens_details ?? {}) as Record<string, unknown>;++ // Clamped against the prompt, then against what is left, so the three parts+ // always sum back to `promptTokens` however the provider's numbers disagree.+ const cacheReadTokens = Math.min(nonNegativeInt(details.cached_tokens), promptTokens);+ const cacheCreationTokens = Math.min(+ nonNegativeInt(details.cache_write_tokens),+ promptTokens - cacheReadTokens+ );++ return {+ promptTokens,+ inputTokens: promptTokens - cacheReadTokens - cacheCreationTokens,+ cacheReadTokens,+ cacheCreationTokens,+ };+}diff --git a/packages/cli/src/handlers/shared/stream-parsers/usage-regressions.test.ts b/packages/cli/src/handlers/shared/stream-parsers/usage-regressions.test.tsindex f4fbf2d4..e8f24c6c 100644--- a/packages/cli/src/handlers/shared/stream-parsers/usage-regressions.test.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/usage-regressions.test.ts@@ -172,6 +172,11 @@ describe("messageStartUsage", () => {expect(messageStartUsage(priorInputTokens)).toEqual({input_tokens: expected,output_tokens: 1,+ // Seeded, not omitted: Claude Code's per-key usage merge ignores a delta+ // value of 0, so an absent seed leaves the accumulated count `undefined`+ // and the client's raw three-way sum becomes NaN. See message-start-usage.ts.+ cache_read_input_tokens: 0,+ cache_creation_input_tokens: 0,});});});@@ -202,25 +207,45 @@ describe("closing message_delta usage", () => {const parsers: Array<{name: string;create: (promptTokens: number) => Response;+ /**+ * Does this parser still OMIT a zero input count?+ *+ * openai-sse no longer does. It now ships the three-way input split+ * (`input_tokens` / `cache_read_input_tokens` / `cache_creation_input_tokens`)+ * as one group, and a group with a hole in it is worse than no group: the+ * client sums the three to size the conversation. Emitting an explicit 0 is+ * behaviourally identical for the client anyway — its usage merge only takes+ * a delta value greater than zero, so a `0` and an absent key both leave the+ * message_start seed standing — so this is a wire-bytes change, not a+ * semantic one. See usage-cache-split.test.ts for the split's own gate.+ */+ omitsZeroInput: boolean;}> = [- { name: "openai-sse", create: (promptTokens) => createOpenAiStream(undefined, promptTokens) },+ {+ name: "openai-sse",+ create: (promptTokens) => createOpenAiStream(undefined, promptTokens),+ omitsZeroInput: false,+ },{name: "gemini-sse",create: (promptTokens) => createGeminiStream(undefined, promptTokens),+ omitsZeroInput: true,},{name: "ollama-jsonl",create: (promptTokens) => createOllamaStream(undefined, promptTokens),+ omitsZeroInput: true,},];for (const parser of parsers) {- test(`${parser.name} includes positive input tokens and omits zero`, async () => {+ test(`${parser.name} includes positive input tokens`, async () => {const positive = closingUsage(await parseClaudeSseStream(parser.create(456)));const zero = closingUsage(await parseClaudeSseStream(parser.create(0)));expect(positive.input_tokens).toBe(456);- expect(zero).not.toHaveProperty("input_tokens");+ if (parser.omitsZeroInput) expect(zero).not.toHaveProperty("input_tokens");+ else expect(zero.input_tokens).toBe(0);});}});diff --git a/packages/cli/src/handlers/shared/token-tracker.test.ts b/packages/cli/src/handlers/shared/token-tracker.test.tsindex dd2d1678..3f5b4aee 100644--- a/packages/cli/src/handlers/shared/token-tracker.test.ts+++ b/packages/cli/src/handlers/shared/token-tracker.test.ts@@ -3,7 +3,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { TokenTracker } from "./token-tracker.js";+import { TokenTracker, computeCacheReadDiscount } from "./token-tracker.js";interface TokenFile {input_tokens: number;@@ -161,3 +161,114 @@ describe("TokenTracker tool-name accounting", () => {expect(tracker.getToolCallCount()).toBe(4);});});++/**+ * Item 6's money half.+ *+ * The capture numbers below come from+ * `test-fixtures/sse-responses/grok-4.6-openai-advisor-turn1.sse`+ * (`prompt_tokens: 20379`, `prompt_tokens_details.cached_tokens: 20352`) — the+ * turn that makes the clamp necessary, because the delta strategy charges the+ * 27-token GROWTH while the cache read is three orders of magnitude larger.+ *+ * `cacheReadCostPer1M` has no producer in the tree by design (its absence is the+ * rule "price a cache read as ordinary input"), so the only way to reach a+ * non-zero discount at all is to hand `computeCacheReadDiscount` a pricing+ * object. That is why the arithmetic is pinned on the exported function and the+ * "nothing changed" property is pinned on the tracker itself.+ */+describe("TokenTracker cache-read discount", () => {+ const CAPTURE_PROMPT_TOKENS = 20_379;+ const CAPTURE_CACHED_TOKENS = 20_352;+ const CAPTURE_GROWTH = CAPTURE_PROMPT_TOKENS - CAPTURE_CACHED_TOKENS; // 27+ const detail = { cacheReadTokens: CAPTURE_CACHED_TOKENS, cacheCreationTokens: 0 };++ test("no cache rate anywhere means the discount is EXACTLY zero", () => {+ const pricing = { inputCostPer1M: 3, outputCostPer1M: 15 };+ expect(computeCacheReadDiscount(pricing, CAPTURE_PROMPT_TOKENS, detail)).toBe(0);+ });++ test("a rate equal to the input rate is also exactly zero", () => {+ const pricing = { inputCostPer1M: 3, outputCostPer1M: 15, cacheReadCostPer1M: 3 };+ expect(computeCacheReadDiscount(pricing, CAPTURE_PROMPT_TOKENS, detail)).toBe(0);+ });++ test("a cache rate ABOVE the input rate never becomes a surcharge", () => {+ const pricing = { inputCostPer1M: 3, outputCostPer1M: 15, cacheReadCostPer1M: 9 };+ expect(computeCacheReadDiscount(pricing, CAPTURE_PROMPT_TOKENS, detail)).toBe(0);+ });++ test("the discount is clamped to what the strategy actually charged", () => {+ const pricing = { inputCostPer1M: 3, outputCostPer1M: 15, cacheReadCostPer1M: 0.3 };+ // Delta strategy: it charged 27 tokens, so at most 27 tokens may be discounted.+ const clamped = computeCacheReadDiscount(pricing, CAPTURE_GROWTH, detail);+ expect(clamped).toBeCloseTo((CAPTURE_GROWTH / 1_000_000) * 2.7, 12);++ // Unclamped, the same inputs would subtract three orders of magnitude more+ // than the charge — this is the number that drove sessionTotalCost negative.+ const unclamped = (CAPTURE_CACHED_TOKENS / 1_000_000) * 2.7;+ const charged = (CAPTURE_GROWTH / 1_000_000) * 3;+ expect(charged - unclamped).toBeLessThan(0);+ expect(charged - clamped).toBeGreaterThanOrEqual(0);+ });++ test("an assignment strategy discounts against the full context it charged", () => {+ const pricing = { inputCostPer1M: 3, outputCostPer1M: 15, cacheReadCostPer1M: 0.3 };+ expect(computeCacheReadDiscount(pricing, CAPTURE_PROMPT_TOKENS, detail)).toBeCloseTo(+ (CAPTURE_CACHED_TOKENS / 1_000_000) * 2.7,+ 12+ );+ });++ test("no detail, or a zero cache read, is zero", () => {+ const pricing = { inputCostPer1M: 3, outputCostPer1M: 15, cacheReadCostPer1M: 0.3 };+ expect(computeCacheReadDiscount(pricing, 1000, undefined)).toBe(0);+ expect(+ computeCacheReadDiscount(pricing, 1000, { cacheReadTokens: 0, cacheCreationTokens: 0 })+ ).toBe(0);+ });++ test("every strategy's cost is bit-identical with and without the detail today", () => {+ // The whole safety claim for shipping this: with no cache rate in the tree,+ // passing the split changes nothing, for all five strategies.+ const run = (withDetail: boolean) => {+ const totals: number[] = [];+ const d = withDetail ? detail : undefined;++ const a = createTracker().tracker;+ a.update(CAPTURE_PROMPT_TOKENS, 100, d);+ a.update(CAPTURE_PROMPT_TOKENS + 500, 100, d);+ totals.push(a.getTotalCost());++ const b = createTracker().tracker;+ b.updateWithDelta(CAPTURE_PROMPT_TOKENS, 100, d);+ b.updateWithDelta(CAPTURE_PROMPT_TOKENS + 500, 100, d);+ totals.push(b.getTotalCost());++ const c = createTracker().tracker;+ c.accumulateBoth(CAPTURE_PROMPT_TOKENS, 100, d);+ c.accumulateBoth(CAPTURE_PROMPT_TOKENS, 100, d);+ totals.push(c.getTotalCost());++ const e = createTracker().tracker;+ e.updateWithActualCost(CAPTURE_PROMPT_TOKENS, 100, undefined, d);+ e.updateWithActualCost(CAPTURE_PROMPT_TOKENS, 100, 0.25, d);+ totals.push(e.getTotalCost());++ const f = createTracker().tracker;+ f.updateLocal(CAPTURE_PROMPT_TOKENS, 100, d);+ totals.push(f.getTotalCost());++ return totals;+ };++ expect(run(true)).toEqual(run(false));+ });++ test("session cost never goes negative on the real cached turn", () => {+ const { tracker } = createTracker();+ tracker.updateWithDelta(CAPTURE_PROMPT_TOKENS, 100, detail);+ tracker.updateWithDelta(CAPTURE_PROMPT_TOKENS + CAPTURE_GROWTH, 5, detail);+ expect(tracker.getTotalCost()).toBeGreaterThanOrEqual(0);+ });+});diff --git a/packages/cli/src/handlers/shared/token-tracker.ts b/packages/cli/src/handlers/shared/token-tracker.tsindex 8573de70..3920d0ae 100644--- a/packages/cli/src/handlers/shared/token-tracker.ts+++ b/packages/cli/src/handlers/shared/token-tracker.ts@@ -26,6 +26,24 @@ export interface TokenTrackerConfig {providerDisplayName?: string;}+/**+ * The cached breakdown of a turn's input tokens, for COST ONLY.+ *+ * Every `update*` method below still takes the FULL context size as its+ * `inputTokens` argument — that number answers "how full is the conversation"+ * and drives the status line's occupancy bar. This object rides alongside and+ * answers a different question: how much of that context the provider served+ * from its prompt cache, and therefore may bill at a lower rate.+ *+ * Both counts are SUBSETS of `inputTokens`, not additions to it.+ */+export interface UsageCacheDetail {+ /** Tokens served from the provider's prompt cache this turn. */+ cacheReadTokens: number;+ /** Tokens written into the provider's prompt cache this turn. */+ cacheCreationTokens: number;+}+/*** Strip a `provider@` routing prefix from a model spec.*@@ -40,6 +58,45 @@ export function stripProviderPrefix(name: string): string {return at === -1 ? name : name.slice(at + 1);}+/**+ * The amount to SUBTRACT from a turn's computed cost because part of its input+ * was served from the provider's prompt cache.+ *+ * Written as a subtraction rather than folded into the input term on purpose:+ * with no `cacheReadCostPer1M` anywhere in the tree the rate defaults to+ * `inputCostPer1M`, the difference is exactly 0, and every existing session's+ * cost is bit-identical to what it was before the cache split landed. A+ * rewritten input term could not make that claim as cheaply.+ *+ * `billedInputTokens` is what the CALLING STRATEGY actually charged for, and+ * the `Math.min` against it is load-bearing — not defensive tidiness. The+ * delta-aware strategy charges only the GROWTH in context, so on the real xAI+ * capture (`grok-4.6-openai-advisor-turn1.sse`: prompt 20379, cached 20352) an+ * unclamped discount would subtract 20352 tokens' worth from a 27-token charge+ * and drive `sessionTotalCost` negative. Clamped, the discount can never exceed+ * the charge it is discounting, so per-turn cost stays >= 0 and the session+ * total stays non-negative.+ *+ * Exported because it is the whole of the money change and the only part with+ * arithmetic worth pinning: the field it reads has no producer yet, so a test+ * has to hand it a pricing object to reach any non-zero branch at all.+ */+export function computeCacheReadDiscount(+ pricing: ModelPricing,+ billedInputTokens: number,+ detail?: UsageCacheDetail+): number {+ const cacheReadTokens = detail?.cacheReadTokens ?? 0;+ if (cacheReadTokens <= 0 || billedInputTokens <= 0) return 0;+ // Absent rate => cache reads are priced as ordinary input => no discount.+ // See ModelPricing.cacheReadCostPer1M for why this is a rule, not a ratio.+ const rate = pricing.cacheReadCostPer1M ?? pricing.inputCostPer1M;+ const perMillionSaved = pricing.inputCostPer1M - rate;+ if (!(perMillionSaved > 0)) return 0;+ const discountedTokens = Math.min(cacheReadTokens, billedInputTokens);+ return (discountedTokens / 1_000_000) * perMillionSaved;+}+export class TokenTracker {private port: number;private config: TokenTrackerConfig;@@ -97,6 +154,17 @@ export class TokenTracker {* full context on the assignment paths, the running total on accumulate-both.*/private sessionBilledInputTokens = 0;+ /**+ * Cache-read tokens summed across the session, for the accumulate-both+ * strategy ALONE.+ *+ * That strategy ASSIGNS `sessionTotalCost` from cumulative totals rather than+ * accumulating per-turn costs, so a per-turn discount subtracted there is+ * simply overwritten on the next turn. The discount has to be recomputed from+ * a cumulative cache-read total to survive, which is what this counter is.+ * Every other strategy accumulates and needs no such counter.+ */+ private sessionCacheReadTokens = 0;constructor(port: number, config: TokenTrackerConfig) {this.port = port;@@ -180,16 +248,20 @@ export class TokenTracker {* Standard update: assign input (latest context), accumulate output.* Used by most remote providers (Gemini, AnthropicCompat, Vertex, RemoteProvider, etc.)*/- update(inputTokens: number, outputTokens: number): void {+ update(inputTokens: number, outputTokens: number, detail?: UsageCacheDetail): void {this.sessionInputTokens = inputTokens;this.lastInputTokens = inputTokens;this.sessionOutputTokens += outputTokens;this.sessionBilledInputTokens += inputTokens;+ this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;const pricing = this.getPricing();+ // This strategy charges the whole context every turn, so the whole context+ // is what the cache discount is clamped against.const cost =(inputTokens / 1_000_000) * pricing.inputCostPer1M +- (outputTokens / 1_000_000) * pricing.outputCostPer1M;+ (outputTokens / 1_000_000) * pricing.outputCostPer1M -+ this.cacheReadDiscount(pricing, inputTokens, detail);this.sessionTotalCost += cost;this.writeFile(inputTokens, this.sessionOutputTokens, pricing.isEstimate);@@ -199,15 +271,24 @@ export class TokenTracker {* Accumulate both input and output tokens.* Used by OllamaCloud where cost is calculated on cumulative totals.*/- accumulateBoth(inputTokens: number, outputTokens: number): void {+ accumulateBoth(inputTokens: number, outputTokens: number, detail?: UsageCacheDetail): void {this.sessionInputTokens += inputTokens;this.lastInputTokens = this.sessionInputTokens;this.sessionOutputTokens += outputTokens;+ this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;const pricing = this.getPricing();+ // ASSIGNED from cumulative totals, so the discount must be cumulative too: a+ // per-turn subtraction here would be thrown away by the next turn's+ // assignment. `sessionCacheReadTokens` is the running total, clamped against+ // the running input total this line is already pricing.const cost =(this.sessionInputTokens / 1_000_000) * pricing.inputCostPer1M +- (this.sessionOutputTokens / 1_000_000) * pricing.outputCostPer1M;+ (this.sessionOutputTokens / 1_000_000) * pricing.outputCostPer1M -+ this.cacheReadDiscount(pricing, this.sessionInputTokens, {+ cacheReadTokens: this.sessionCacheReadTokens,+ cacheCreationTokens: 0,+ });// OllamaCloud recalculates total cost each time (not incremental)this.sessionTotalCost = cost;// Assigned, not accumulated, for the same reason the cost above is: this strategy@@ -224,7 +305,7 @@ export class TokenTracker {* inputTokens = full context size from the API (not incremental)* Only charges for the delta (new tokens added since last request).*/- updateWithDelta(inputTokens: number, outputTokens: number): void {+ updateWithDelta(inputTokens: number, outputTokens: number, detail?: UsageCacheDetail): void {let incrementalInputTokens: number;// The status file always reports THIS request's context, even when the@@ -257,12 +338,18 @@ export class TokenTracker {}this.sessionOutputTokens += outputTokens;+ this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;const pricing = this.getPricing();this.sessionBilledInputTokens += incrementalInputTokens;+ // The clamp matters MOST here: this strategy charges only the growth, which+ // on a cached continuation is a handful of tokens against a cache read of+ // tens of thousands. Discounting the raw cache-read count would make the+ // turn cost negative. See cacheReadDiscount for the measured capture.const cost =(incrementalInputTokens / 1_000_000) * pricing.inputCostPer1M +- (outputTokens / 1_000_000) * pricing.outputCostPer1M;+ (outputTokens / 1_000_000) * pricing.outputCostPer1M -+ this.cacheReadDiscount(pricing, incrementalInputTokens, detail);this.sessionTotalCost += cost;this.writeFile(inputTokens, this.sessionOutputTokens, pricing.isEstimate);@@ -275,21 +362,29 @@ export class TokenTracker {updateWithActualCost(inputTokens: number,outputTokens: number,- actualCost: number | undefined+ actualCost: number | undefined,+ detail?: UsageCacheDetail): void {this.sessionInputTokens = inputTokens;this.lastInputTokens = inputTokens;this.sessionOutputTokens += outputTokens;this.sessionBilledInputTokens += inputTokens;+ this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;if (typeof actualCost === "number" && actualCost > 0) {+ // NO DISCOUNT on this branch. The provider's own figure is already net of+ // whatever caching it applied; subtracting a cache discount from it would+ // double-count the saving and under-report real spend.this.sessionTotalCost += actualCost;log(`[TokenTracker] Actual cost from API: $${actualCost.toFixed(6)}`);} else {+ // The computed fallback is the `update` arithmetic, so it takes the+ // `update` treatment: full context charged, discount clamped against it.const pricing = this.getPricing();const inputCost = (inputTokens / 1_000_000) * pricing.inputCostPer1M;const outputCost = (outputTokens / 1_000_000) * pricing.outputCostPer1M;- this.sessionTotalCost += inputCost + outputCost;+ this.sessionTotalCost +=+ inputCost + outputCost - this.cacheReadDiscount(pricing, inputTokens, detail);}this.writeFile(inputTokens, this.sessionOutputTokens);@@ -299,7 +394,10 @@ export class TokenTracker {* For local models: assign input (API reports full context), accumulate output.* Cost is always 0 for local models.*/- updateLocal(inputTokens: number, outputTokens: number): void {+ updateLocal(inputTokens: number, outputTokens: number, _detail?: UsageCacheDetail): void {+ // No discount: local models have no pricing at all, so there is nothing to+ // discount. The parameter exists only so every strategy shares one shape and+ // the caller does not have to know which ones care.if (inputTokens > 0) {this.sessionInputTokens = inputTokens;this.lastInputTokens = inputTokens;@@ -348,6 +446,15 @@ export class TokenTracker {return getModelPricing(this.config.providerName, this.config.modelName);}+ /** Instance shim over `computeCacheReadDiscount` — see that function. */+ private cacheReadDiscount(+ pricing: ModelPricing,+ billedInputTokens: number,+ detail?: UsageCacheDetail+ ): number {+ return computeCacheReadDiscount(pricing, billedInputTokens, detail);+ }+private getDisplayName(): string {if (this.config.providerDisplayName) return this.config.providerDisplayName;const name = this.config.providerName;