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

usageTranscripts.ts

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