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