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 if (typeof parsed !== "object" || parsed === null) return null;
117
118 const record = parsed as Record<string, unknown>;
119 if (record["type"] !== "assistant") return null;
120
121 const message = record["message"];
122 if (typeof message !== "object" || message === null) return null;
123 const messageRecord = message as Record<string, unknown>;
124
125 const usage = messageRecord["usage"];
126 if (typeof usage !== "object" || usage === null) return null;
127 const usageRecord = usage as Record<string, unknown>;
128
129 const timestampMs = parseTimestampMs(record["timestamp"]);
130 if (timestampMs === null) return null;
131
132 const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
133 if (model.length === 0) return null;
134
135 const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
136 const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
137 // Matches ccusage: prefer the message/request pair, fall back to whichever
138 // half exists. Records with neither cannot be de-duplicated.
139 const dedupeKey =
140 messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
141
142 const cost = record["costUSD"];
143
144 return {
145 provider: "claude",
146 timestampMs,
147 model,
148 sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
149 totals: {
150 uncachedInputTokens: int(usageRecord["input_tokens"]),
151 cachedInputTokens: int(usageRecord["cache_read_input_tokens"]),
152 cacheCreationTokens: int(usageRecord["cache_creation_input_tokens"]),
153 outputTokens: int(usageRecord["output_tokens"]),
154 // Anthropic folds thinking tokens into output and does not break them out.
155 reasoningTokens: 0,
156 },
157 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
158 fast: usageRecord["speed"] === "fast",
159 dedupeKey,
160 };
161}
162
163/* -------------------------------------------------------------------------- */
164/* Codex */
165/* -------------------------------------------------------------------------- */
166
167/**
168 * Rolling state for a single Codex rollout file.
169 *
170 * Codex `token_count` events carry no model, so the model is carried forward
171 * from the most recent `turn_context`. Sessions that switch models mid-run
172 * attribute correctly from the switch onward.
173 */
174export interface CodexScanState {
175 model: string;
176 sessionId: string;
177 lastUsageSignature: string | null;
178 sawSessionMeta: boolean;
179 /** While true, leading usage events are re-stamped copies of parent history. */
180 suppressingForkCopies: boolean;
181 forkCopyAnchorMs: number;
182}
183
184export function initialCodexScanState(): CodexScanState {
185 return {
186 model: "",
187 sessionId: "",
188 lastUsageSignature: null,
189 sawSessionMeta: false,
190 suppressingForkCopies: false,
191 forkCopyAnchorMs: 0,
192 };
193}
194
195/**
196 * A forked or subagent rollout opens with the parent's full history copied in,
197 * every line re-stamped to the fork instant. Those copies are written in one
198 * synchronous burst (observed gaps 0-40ms), while the child's first genuine
199 * usage event only lands after a real model turn (observed 5s+). One second of
200 * separation splits the two cleanly; `ccusage` uses the same threshold.
201 */
202const FORK_COPY_MAX_GAP_MS = 1000;
203
204/** Whether a `session_meta` payload marks the rollout as a fork or subagent. */
205function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
206 if (typeof payload["forked_from_id"] === "string") return true;
207 const source = payload["source"];
208 if (typeof source !== "object" || source === null) return false;
209 const subagent = (source as Record<string, unknown>)["subagent"];
210 if (typeof subagent !== "object" || subagent === null) return false;
211 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
212 if (typeof spawn !== "object" || spawn === null) return false;
213 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
214}
215
216/**
217 * Feeds one line of a Codex rollout into `state`, returning a record when the
218 * line was a usage event.
219 *
220 * Deltas come from `last_token_usage`. Summing those across a session
221 * reconciles with the session's final `total_token_usage`, provided
222 * consecutive duplicate events are dropped, which this does.
223 */
224export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
225 let parsed: unknown;
226 try {
227 parsed = JSON.parse(line);
228 } catch {
229 return null;
230 }
231 if (typeof parsed !== "object" || parsed === null) return null;
232
233 const record = parsed as Record<string, unknown>;
234 const payload = record["payload"];
235 if (typeof payload !== "object" || payload === null) return null;
236 const payloadRecord = payload as Record<string, unknown>;
237 const payloadType = payloadRecord["type"];
238
239 if (record["type"] === "session_meta") {
240 // Only the first meta describes this file's own session. A forked rollout
241 // repeats the ancestors' metas right after it; letting those through would
242 // reassign every subsequent record to an ancestor session.
243 if (state.sawSessionMeta) return null;
244 state.sawSessionMeta = true;
245 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
246 if (typeof id === "string") state.sessionId = id;
247 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
248 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
249 state.suppressingForkCopies = true;
250 state.forkCopyAnchorMs = metaTimestampMs;
251 }
252 return null;
253 }
254
255 if (record["type"] === "turn_context") {
256 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
257 return null;
258 }
259
260 if (payloadType !== "token_count") return null;
261
262 const info = payloadRecord["info"];
263 if (typeof info !== "object" || info === null) return null;
264 const last = (info as Record<string, unknown>)["last_token_usage"];
265 if (typeof last !== "object" || last === null) return null;
266 const lastRecord = last as Record<string, unknown>;
267
268 // Only an event that is otherwise eligible may consume the duplicate
269 // signature. A token_count arriving before its turn_context (no model yet)
270 // must not poison it, or the re-emitted copy after the model is known would
271 // be skipped as a duplicate and those tokens never counted.
272 const timestampMs = parseTimestampMs(record["timestamp"]);
273 if (timestampMs === null) return null;
274 if (state.model.length === 0) return null;
275
276 // Codex re-emits an unchanged token_count on some stream boundaries. Summing
277 // those would double count, so identical consecutive payloads are skipped.
278 const signature = JSON.stringify(lastRecord);
279 if (signature === state.lastUsageSignature) return null;
280 state.lastUsageSignature = signature;
281
282 // In a forked rollout the copied parent history was already counted from the
283 // parent's own file. Drop the leading burst; the first usage event separated
284 // from its predecessor by a real turn's worth of time ends it for good.
285 if (state.suppressingForkCopies) {
286 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
287 state.forkCopyAnchorMs = timestampMs;
288 return null;
289 }
290 state.suppressingForkCopies = false;
291 }
292
293 const inputTokens = int(lastRecord["input_tokens"]);
294 const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
295 const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
296 const outputTokens = int(lastRecord["output_tokens"]);
297
298 const totals: UsageTokenTotals = {
299 // Codex reports `input_tokens` inclusive of the cached portion.
300 uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
301 cachedInputTokens,
302 cacheCreationTokens,
303 outputTokens,
304 // Reported inside output_tokens, surfaced separately for the token mix.
305 reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])),
306 };
307
308 if (totalTokens(totals) === 0) return null;
309
310 return {
311 provider: "codex",
312 timestampMs,
313 model: state.model,
314 sessionId: state.sessionId,
315 totals,
316 // Codex does not report cost in the rollout.
317 reportedCostUsd: null,
318 fast: false,
319 // Events surviving the fork-copy suppression above are unique to this
320 // rollout, so they need no global dedup.
321 dedupeKey: null,
322 };
323}
324
325/* -------------------------------------------------------------------------- */
326/* Grok Build */
327/* -------------------------------------------------------------------------- */
328
329interface GrokUsageTotals {
330 readonly inputTokens: number;
331 readonly outputTokens: number;
332 readonly cachedReadTokens: number;
333 readonly cacheCreationTokens: number;
334 readonly reasoningTokens: number;
335 readonly costUsdTicks: number | null;
336}
337
338function readGrokUsageTotals(value: unknown): GrokUsageTotals | null {
339 if (typeof value !== "object" || value === null) return null;
340 const record = value as Record<string, unknown>;
341 return {
342 inputTokens: int(record["inputTokens"]),
343 outputTokens: int(record["outputTokens"]),
344 cachedReadTokens: int(record["cachedReadTokens"]),
345 cacheCreationTokens: int(record["cacheCreationTokens"]),
346 reasoningTokens: int(record["reasoningTokens"]),
347 costUsdTicks:
348 typeof record["costUsdTicks"] === "number" && Number.isFinite(record["costUsdTicks"])
349 ? record["costUsdTicks"]
350 : null,
351 };
352}
353
354function grokTotalsToUsage(totals: GrokUsageTotals): UsageTokenTotals {
355 const cachedInputTokens = totals.cachedReadTokens;
356 const cacheCreationTokens = totals.cacheCreationTokens;
357 // Grok reports `inputTokens` inclusive of the cached portion, matching Codex.
358 const uncachedInputTokens = Math.max(
359 0,
360 totals.inputTokens - cachedInputTokens - cacheCreationTokens,
361 );
362 const outputTokens = totals.outputTokens;
363 return {
364 uncachedInputTokens,
365 cachedInputTokens,
366 cacheCreationTokens,
367 outputTokens,
368 reasoningTokens: Math.min(outputTokens, totals.reasoningTokens),
369 };
370}
371
372/**
373 * Parses one line of a Grok Build `updates.jsonl` session log.
374 *
375 * Usage lands on `turn_completed` session updates. Per-model breakdowns live
376 * under `usage.modelUsage`; when present each model becomes its own record.
377 *
378 * Returns every record for the line (0 or more). Callers stream line-by-line
379 * and flatten.
380 */
381export function parseGrokLine(line: string): readonly UsageRecord[] {
382 let parsed: unknown;
383 try {
384 parsed = JSON.parse(line);
385 } catch {
386 return [];
387 }
388 if (typeof parsed !== "object" || parsed === null) return [];
389
390 const record = parsed as Record<string, unknown>;
391 const params = record["params"];
392 if (typeof params !== "object" || params === null) return [];
393 const paramsRecord = params as Record<string, unknown>;
394
395 const update = paramsRecord["update"];
396 if (typeof update !== "object" || update === null) return [];
397 const updateRecord = update as Record<string, unknown>;
398 if (updateRecord["sessionUpdate"] !== "turn_completed") return [];
399
400 const usage = updateRecord["usage"];
401 if (typeof usage !== "object" || usage === null) return [];
402 const usageRecord = usage as Record<string, unknown>;
403
404 const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : "";
405 const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null;
406
407 // Prefer the high-resolution agent clock; fall back to the outer unix seconds.
408 const meta = paramsRecord["_meta"];
409 let timestampMs: number | null = null;
410 if (typeof meta === "object" && meta !== null) {
411 const agentTimestampMs = (meta as Record<string, unknown>)["agentTimestampMs"];
412 if (typeof agentTimestampMs === "number" && Number.isFinite(agentTimestampMs)) {
413 timestampMs = agentTimestampMs;
414 }
415 }
416 if (timestampMs === null) {
417 const timestamp = record["timestamp"];
418 if (typeof timestamp === "number" && Number.isFinite(timestamp)) {
419 timestampMs = timestamp > 1e12 ? timestamp : timestamp * 1000;
420 }
421 }
422 if (timestampMs === null) return [];
423
424 const topLevel = readGrokUsageTotals(usageRecord);
425 if (topLevel === null) return [];
426
427 const modelUsage = usageRecord["modelUsage"];
428 const modelEntries: Array<{ model: string; totals: GrokUsageTotals }> = [];
429 if (typeof modelUsage === "object" && modelUsage !== null) {
430 for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
431 if (model.length === 0) continue;
432 const totals = readGrokUsageTotals(raw);
433 if (totals === null) continue;
434 modelEntries.push({ model, totals });
435 }
436 }
437
438 if (modelEntries.length === 0) {
439 if (totalTokens(grokTotalsToUsage(topLevel)) === 0) return [];
440 return [
441 {
442 provider: "grok",
443 timestampMs,
444 model: "grok",
445 sessionId,
446 totals: grokTotalsToUsage(topLevel),
447 reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
448 fast: false,
449 // No prompt id means we cannot tell two same-second updates apart.
450 dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
451 },
452 ];
453 }
454
455 // Cost allocation:
456 // 1. Emitted models with their own costUsdTicks keep those values.
457 // 2. Remaining aggregate cost (top-level minus those per-model ticks,
458 // clamped at 0) is pro-rated across emitted models that lack ticks,
459 // by token share among the unticked models only.
460 // 3. When no model has per-model ticks, remaining equals the full
461 // aggregate and every emitted model gets a token-share slice.
462 // Zero-token rows are never emitted and never count toward used ticks.
463 const topLevelCostUsd = grokCostTicksToUsd(topLevel.costUsdTicks);
464 let usedTickedCostUsd = 0;
465 let untickedTokenDenominator = 0;
466 for (const entry of modelEntries) {
467 const tokens = totalTokens(grokTotalsToUsage(entry.totals));
468 if (tokens === 0) continue;
469 if (entry.totals.costUsdTicks !== null) {
470 usedTickedCostUsd += grokCostTicksToUsd(entry.totals.costUsdTicks) ?? 0;
471 } else {
472 untickedTokenDenominator += tokens;
473 }
474 }
475 const remainingCostUsd =
476 topLevelCostUsd === null ? null : Math.max(0, topLevelCostUsd - usedTickedCostUsd);
477
478 const results: UsageRecord[] = [];
479 for (const entry of modelEntries) {
480 const totals = grokTotalsToUsage(entry.totals);
481 if (totalTokens(totals) === 0) continue;
482
483 let reportedCostUsd = grokCostTicksToUsd(entry.totals.costUsdTicks);
484 if (reportedCostUsd === null && remainingCostUsd !== null && untickedTokenDenominator > 0) {
485 reportedCostUsd = remainingCostUsd * (totalTokens(totals) / untickedTokenDenominator);
486 }
487
488 results.push({
489 provider: "grok",
490 timestampMs,
491 model: entry.model,
492 sessionId,
493 totals,
494 reportedCostUsd,
495 fast: false,
496 dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
497 });
498 }
499 return results;
500}
501
502export { EMPTY_TOTALS };