Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageTranscripts.ts

540 lines20.0 KB

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