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

usageTranscripts.ts

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