Open History to see the last commit
1/**
2 * Pure parsers for the provider CLIs' on-disk session transcripts.
3 *
4 * Each parser is a line-at-a-time reducer so callers can stream large files
5 * without materialising them. None of them touch the filesystem.
6 *
7 * @module usageTranscripts
8 */
9import type { UsageProviderKind, UsageTokenTotals } from "@t3tools/contracts";
10
11export interface UsageRecord {
12 readonly provider: UsageProviderKind;
13 readonly timestampMs: number;
14 readonly model: string;
15 /**
16 * Rate-table key when the provider's display name carries tiers the table
17 * does not know, such as Cursor's `claude-opus-5-5-high`. Defaults to `model`.
18 */
19 readonly rateModel?: string;
20 readonly sessionId: string;
21 readonly totals: UsageTokenTotals;
22 readonly reportedCostUsd: number | null;
23 /**
24 * Whether the request ran in fast mode, which bills at a model-specific
25 * multiple of the standard rate. Only Claude Code records this.
26 */
27 readonly fast: boolean;
28 /**
29 * Key for cross-file de-duplication, or `null` when the record is inherently
30 * unique and needs no dedup.
31 */
32 readonly dedupeKey: string | null;
33}
34
35const EMPTY_TOTALS: UsageTokenTotals = {
36 uncachedInputTokens: 0,
37 cachedInputTokens: 0,
38 cacheCreationTokens: 0,
39 outputTokens: 0,
40 reasoningTokens: 0,
41};
42
43function int(value: unknown): number {
44 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
45}
46
47function parseTimestampMs(value: unknown): number | null {
48 if (typeof value !== "string") return null;
49 const parsed = Date.parse(value);
50 return Number.isNaN(parsed) ? null : parsed;
51}
52
53export function addTotals(a: UsageTokenTotals, b: UsageTokenTotals): UsageTokenTotals {
54 return {
55 uncachedInputTokens: a.uncachedInputTokens + b.uncachedInputTokens,
56 cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,
57 cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens,
58 outputTokens: a.outputTokens + b.outputTokens,
59 reasoningTokens: a.reasoningTokens + b.reasoningTokens,
60 };
61}
62
63export function totalTokens(totals: UsageTokenTotals): number {
64 // reasoningTokens is a subset of outputTokens and must not be added again.
65 return (
66 totals.uncachedInputTokens +
67 totals.cachedInputTokens +
68 totals.cacheCreationTokens +
69 totals.outputTokens
70 );
71}
72
73/**
74 * Cheap substring gate applied before `JSON.parse`.
75 *
76 * Transcripts are mostly tool output; only a minority of lines carry usage. On
77 * a 30-day window this skips roughly half the lines outright and is worth about
78 * an order of magnitude.
79 */
80export function mightCarryUsage(line: string, provider: UsageProviderKind): boolean {
81 if (provider === "claude") return line.includes('"usage"');
82 if (provider === "grok") return line.includes('"turn_completed"');
83 return line.includes('"token_count"');
84}
85
86/**
87 * Grok reports cost in integer ticks where `1 USD = 10^10` ticks. See Grok
88 * headless `total_cost_usd_ticks`. Convert to dollars for pricing.
89 */
90export const GROK_COST_USD_TICKS_PER_DOLLAR = 10_000_000_000;
91
92function grokCostTicksToUsd(ticks: unknown): number | null {
93 if (typeof ticks !== "number" || !Number.isFinite(ticks) || ticks < 0) return null;
94 return ticks / GROK_COST_USD_TICKS_PER_DOLLAR;
95}
96
97/* -------------------------------------------------------------------------- */
98/* Claude Code */
99/* -------------------------------------------------------------------------- */
100
101/**
102 * Parses one line of a Claude Code transcript.
103 *
104 * T3 Code writes one record per assistant *content block*, and every one of
105 * those records repeats the same complete `usage` object for the parent
106 * message. Summing them overcounts by roughly 2.4x on a real workload, so the
107 * caller must drop repeats by `dedupeKey` and keep the first.
108 */
109export function parseClaudeLine(line: string): UsageRecord | null {
110 let parsed: unknown;
111 try {
112 parsed = JSON.parse(line);
113 } catch {
114 return null;
115 }
116 return parseClaudeRecord(parsed);
117}
118
119export function parseClaudeRecord(parsed: unknown): UsageRecord | null {
120 if (typeof parsed !== "object" || parsed === null) return null;
121
122 const record = parsed as Record<string, unknown>;
123 if (record["type"] !== "assistant") return null;
124
125 const message = record["message"];
126 if (typeof message !== "object" || message === null) return null;
127 const messageRecord = message as Record<string, unknown>;
128
129 const usage = messageRecord["usage"];
130 if (typeof usage !== "object" || usage === null) return null;
131 const usageRecord = usage as Record<string, unknown>;
132
133 const timestampMs = parseTimestampMs(record["timestamp"]);
134 if (timestampMs === null) return null;
135
136 const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
137 if (model.length === 0) return null;
138
139 const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
140 const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
141 // Matches ccusage: prefer the message/request pair, fall back to whichever
142 // half exists. Records with neither cannot be de-duplicated.
143 const dedupeKey =
144 messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
145
146 const cost = record["costUSD"];
147
148 return {
149 provider: "claude",
150 timestampMs,
151 model,
152 sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
153 totals: {
154 uncachedInputTokens: int(usageRecord["input_tokens"]),
155 cachedInputTokens: int(usageRecord["cache_read_input_tokens"]),
156 cacheCreationTokens: int(usageRecord["cache_creation_input_tokens"]),
157 outputTokens: int(usageRecord["output_tokens"]),
158 // Anthropic folds thinking tokens into output and does not break them out.
159 reasoningTokens: 0,
160 },
161 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
162 fast: usageRecord["speed"] === "fast",
163 dedupeKey,
164 };
165}
166
167/* -------------------------------------------------------------------------- */
168/* Codex */
169/* -------------------------------------------------------------------------- */
170
171/**
172 * Rolling state for a single Codex rollout file.
173 *
174 * Codex `token_count` events carry no model, so the model is carried forward
175 * from the most recent `turn_context`. Sessions that switch models mid-run
176 * attribute correctly from the switch onward.
177 */
178export interface CodexScanState {
179 model: string;
180 sessionId: string;
181 lastUsageSignature: string | null;
182 sawSessionMeta: boolean;
183 /** While true, leading usage events are re-stamped copies of parent history. */
184 suppressingForkCopies: boolean;
185 forkCopyAnchorMs: number;
186}
187
188export function initialCodexScanState(): CodexScanState {
189 return {
190 model: "",
191 sessionId: "",
192 lastUsageSignature: null,
193 sawSessionMeta: false,
194 suppressingForkCopies: false,
195 forkCopyAnchorMs: 0,
196 };
197}
198
199/**
200 * A forked or subagent rollout opens with the parent's full history copied in,
201 * every line re-stamped to the fork instant. Those copies are written in one
202 * synchronous burst (observed gaps 0-40ms), while the child's first genuine
203 * usage event only lands after a real model turn (observed 5s+). One second of
204 * separation splits the two cleanly; `ccusage` uses the same threshold.
205 */
206const FORK_COPY_MAX_GAP_MS = 1000;
207
208/** Whether a `session_meta` payload marks the rollout as a fork or subagent. */
209function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
210 if (typeof payload["forked_from_id"] === "string") return true;
211 const source = payload["source"];
212 if (typeof source !== "object" || source === null) return false;
213 const subagent = (source as Record<string, unknown>)["subagent"];
214 if (typeof subagent !== "object" || subagent === null) return false;
215 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
216 if (typeof spawn !== "object" || spawn === null) return false;
217 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
218}
219
220/**
221 * Feeds one line of a Codex rollout into `state`, returning a record when the
222 * line was a usage event.
223 *
224 * Deltas come from `last_token_usage`. Summing those across a session
225 * reconciles with the session's final `total_token_usage`, provided
226 * consecutive duplicate events are dropped, which this does.
227 */
228export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
229 let parsed: unknown;
230 try {
231 parsed = JSON.parse(line);
232 } catch {
233 return null;
234 }
235 return parseCodexRecord(parsed, state);
236}
237
238export function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null {
239 if (typeof parsed !== "object" || parsed === null) return null;
240
241 const record = parsed as Record<string, unknown>;
242 const payload = record["payload"];
243 if (typeof payload !== "object" || payload === null) return null;
244 const payloadRecord = payload as Record<string, unknown>;
245 const payloadType = payloadRecord["type"];
246
247 if (record["type"] === "session_meta") {
248 // Only the first meta describes this file's own session. A forked rollout
249 // repeats the ancestors' metas right after it; letting those through would
250 // reassign every subsequent record to an ancestor session.
251 if (state.sawSessionMeta) return null;
252 state.sawSessionMeta = true;
253 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
254 if (typeof id === "string") state.sessionId = id;
255 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
256 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
257 state.suppressingForkCopies = true;
258 state.forkCopyAnchorMs = metaTimestampMs;
259 }
260 return null;
261 }
262
263 if (record["type"] === "turn_context") {
264 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
265 return null;
266 }
267
268 if (payloadType !== "token_count") return null;
269
270 const info = payloadRecord["info"];
271 if (typeof info !== "object" || info === null) return null;
272 const last = (info as Record<string, unknown>)["last_token_usage"];
273 if (typeof last !== "object" || last === null) return null;
274 const lastRecord = last as Record<string, unknown>;
275
276 // Only an event that is otherwise eligible may consume the duplicate
277 // signature. A token_count arriving before its turn_context (no model yet)
278 // must not poison it, or the re-emitted copy after the model is known would
279 // be skipped as a duplicate and those tokens never counted.
280 const timestampMs = parseTimestampMs(record["timestamp"]);
281 if (timestampMs === null) return null;
282 if (state.model.length === 0) return null;
283
284 // Codex re-emits an unchanged token_count on some stream boundaries. Summing
285 // those would double count, so identical consecutive payloads are skipped.
286 const signature = JSON.stringify(lastRecord);
287 if (signature === state.lastUsageSignature) return null;
288 state.lastUsageSignature = signature;
289
290 // In a forked rollout the copied parent history was already counted from the
291 // parent's own file. Drop the leading burst; the first usage event separated
292 // from its predecessor by a real turn's worth of time ends it for good.
293 if (state.suppressingForkCopies) {
294 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
295 state.forkCopyAnchorMs = timestampMs;
296 return null;
297 }
298 state.suppressingForkCopies = false;
299 }
300
301 const inputTokens = int(lastRecord["input_tokens"]);
302 const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
303 const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
304 const outputTokens = int(lastRecord["output_tokens"]);
305
306 const totals: UsageTokenTotals = {
307 // Codex reports `input_tokens` inclusive of the cached portion.
308 uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
309 cachedInputTokens,
310 cacheCreationTokens,
311 outputTokens,
312 // Reported inside output_tokens, surfaced separately for the token mix.
313 reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])),
314 };
315
316 if (totalTokens(totals) === 0) return null;
317
318 return {
319 provider: "codex",
320 timestampMs,
321 model: state.model,
322 sessionId: state.sessionId,
323 totals,
324 // Codex does not report cost in the rollout.
325 reportedCostUsd: null,
326 fast: false,
327 // Events surviving the fork-copy suppression above are unique to this
328 // rollout, so they need no global dedup.
329 dedupeKey: null,
330 };
331}
332
333/* -------------------------------------------------------------------------- */
334/* Grok Build */
335/* -------------------------------------------------------------------------- */
336
337interface GrokUsageTotals {
338 readonly inputTokens: number;
339 readonly outputTokens: number;
340 readonly cachedReadTokens: number;
341 readonly cacheCreationTokens: number;
342 readonly reasoningTokens: number;
343 readonly costUsdTicks: number | null;
344}
345
346function readGrokUsageTotals(value: unknown): GrokUsageTotals | null {
347 if (typeof value !== "object" || value === null) return null;
348 const record = value as Record<string, unknown>;
349 return {
350 inputTokens: int(record["inputTokens"]),
351 outputTokens: int(record["outputTokens"]),
352 cachedReadTokens: int(record["cachedReadTokens"]),
353 cacheCreationTokens: int(record["cacheCreationTokens"]),
354 reasoningTokens: int(record["reasoningTokens"]),
355 costUsdTicks:
356 typeof record["costUsdTicks"] === "number" && Number.isFinite(record["costUsdTicks"])
357 ? record["costUsdTicks"]
358 : null,
359 };
360}
361
362function grokTotalsToUsage(totals: GrokUsageTotals): UsageTokenTotals {
363 const cachedInputTokens = totals.cachedReadTokens;
364 const cacheCreationTokens = totals.cacheCreationTokens;
365 // Grok reports `inputTokens` inclusive of the cached portion, matching Codex.
366 const uncachedInputTokens = Math.max(
367 0,
368 totals.inputTokens - cachedInputTokens - cacheCreationTokens,
369 );
370 const outputTokens = totals.outputTokens;
371 return {
372 uncachedInputTokens,
373 cachedInputTokens,
374 cacheCreationTokens,
375 outputTokens,
376 reasoningTokens: Math.min(outputTokens, totals.reasoningTokens),
377 };
378}
379
380/**
381 * Parses one line of a Grok Build `updates.jsonl` session log.
382 *
383 * Usage lands on `turn_completed` session updates. Per-model breakdowns live
384 * under `usage.modelUsage`; when present each model becomes its own record.
385 *
386 * Returns every record for the line (0 or more). Callers stream line-by-line
387 * and flatten.
388 */
389export function parseGrokLine(line: string): readonly UsageRecord[] {
390 let parsed: unknown;
391 try {
392 parsed = JSON.parse(line);
393 } catch {
394 return [];
395 }
396 return parseGrokRecord(parsed);
397}
398
399export function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
400 if (typeof parsed !== "object" || parsed === null) return [];
401
402 const record = parsed as Record<string, unknown>;
403 const params = record["params"];
404 if (typeof params !== "object" || params === null) return [];
405 const paramsRecord = params as Record<string, unknown>;
406
407 const update = paramsRecord["update"];
408 if (typeof update !== "object" || update === null) return [];
409 const updateRecord = update as Record<string, unknown>;
410 if (updateRecord["sessionUpdate"] !== "turn_completed") return [];
411
412 const usage = updateRecord["usage"];
413 if (typeof usage !== "object" || usage === null) return [];
414 const usageRecord = usage as Record<string, unknown>;
415
416 const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : "";
417 const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null;
418
419 // Prefer the high-resolution agent clock; fall back to the outer unix seconds.
420 const meta = paramsRecord["_meta"];
421 let timestampMs: number | null = null;
422 if (typeof meta === "object" && meta !== null) {
423 const agentTimestampMs = (meta as Record<string, unknown>)["agentTimestampMs"];
424 if (typeof agentTimestampMs === "number" && Number.isFinite(agentTimestampMs)) {
425 timestampMs = agentTimestampMs;
426 }
427 }
428 if (timestampMs === null) {
429 const timestamp = record["timestamp"];
430 if (typeof timestamp === "number" && Number.isFinite(timestamp)) {
431 timestampMs = timestamp > 1e12 ? timestamp : timestamp * 1000;
432 }
433 }
434 if (timestampMs === null) return [];
435
436 const topLevel = readGrokUsageTotals(usageRecord);
437 if (topLevel === null) return [];
438
439 const modelUsage = usageRecord["modelUsage"];
440 const modelEntries: Array<{ model: string; totals: GrokUsageTotals }> = [];
441 if (typeof modelUsage === "object" && modelUsage !== null) {
442 for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
443 if (model.length === 0) continue;
444 const totals = readGrokUsageTotals(raw);
445 if (totals === null) continue;
446 modelEntries.push({ model, totals });
447 }
448 }
449
450 if (modelEntries.length === 0) {
451 if (totalTokens(grokTotalsToUsage(topLevel)) === 0) return [];
452 return [
453 {
454 provider: "grok",
455 timestampMs,
456 model: "grok",
457 sessionId,
458 totals: grokTotalsToUsage(topLevel),
459 reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
460 fast: false,
461 // No prompt id means we cannot tell two same-second updates apart.
462 dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
463 },
464 ];
465 }
466
467 // Cost allocation:
468 // 1. Emitted models with their own costUsdTicks keep those values.
469 // 2. Remaining aggregate cost (top-level minus those per-model ticks,
470 // clamped at 0) is pro-rated across emitted models that lack ticks,
471 // by token share among the unticked models only.
472 // 3. When no model has per-model ticks, remaining equals the full
473 // aggregate and every emitted model gets a token-share slice.
474 // Zero-token rows are never emitted and never count toward used ticks.
475 const topLevelCostUsd = grokCostTicksToUsd(topLevel.costUsdTicks);
476 let usedTickedCostUsd = 0;
477 let untickedTokenDenominator = 0;
478 for (const entry of modelEntries) {
479 const tokens = totalTokens(grokTotalsToUsage(entry.totals));
480 if (tokens === 0) continue;
481 if (entry.totals.costUsdTicks !== null) {
482 usedTickedCostUsd += grokCostTicksToUsd(entry.totals.costUsdTicks) ?? 0;
483 } else {
484 untickedTokenDenominator += tokens;
485 }
486 }
487 const remainingCostUsd =
488 topLevelCostUsd === null ? null : Math.max(0, topLevelCostUsd - usedTickedCostUsd);
489
490 const results: UsageRecord[] = [];
491 for (const entry of modelEntries) {
492 const totals = grokTotalsToUsage(entry.totals);
493 if (totalTokens(totals) === 0) continue;
494
495 let reportedCostUsd = grokCostTicksToUsd(entry.totals.costUsdTicks);
496 if (reportedCostUsd === null && remainingCostUsd !== null && untickedTokenDenominator > 0) {
497 reportedCostUsd = remainingCostUsd * (totalTokens(totals) / untickedTokenDenominator);
498 }
499
500 results.push({
501 provider: "grok",
502 timestampMs,
503 model: entry.model,
504 sessionId,
505 totals,
506 reportedCostUsd,
507 fast: false,
508 dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
509 });
510 }
511 return results;
512}
513
514export { EMPTY_TOTALS };