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

usageTranscripts.ts

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