Open History to see the last commit
1/**
2 * Pure parsers for the provider CLIs' on-disk session transcripts.
3 *
4 * Both parsers are line-at-a-time reducers so callers can stream large files
5 * without materialising them. Neither touches 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
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 };
51}
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 );
61}
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 *
70 * Exhaustive over the provider kinds, so extending `UsageProviderKind` fails
71 * to compile here instead of silently reusing another provider's gate.
72 */
73export function mightCarryUsage(line: string, provider: UsageProviderKind): boolean {
74 switch (provider) {
75 case "claude":
76 return line.includes('"usage"');
77 case "codex":
78 return line.includes('"token_count"');
79 }
80}
81
82/* -------------------------------------------------------------------------- */
83/* Claude Code */
84/* -------------------------------------------------------------------------- */
85
86/**
87 * Parses one line of a Claude Code transcript.
88 *
89 * T3 Code writes one record per assistant *content block*, and every one of
90 * those records repeats the same complete `usage` object for the parent
91 * message. Summing them overcounts by roughly 2.4x on a real workload, so the
92 * caller must drop repeats by `dedupeKey` and keep the first.
93 */
94export function parseClaudeLine(line: string): UsageRecord | null {
95 let parsed: unknown;
96 try {
97 parsed = JSON.parse(line);
98 } catch {
99 return null;
100 }
101 if (typeof parsed !== "object" || parsed === null) return null;
102
103 const record = parsed as Record<string, unknown>;
104 if (record["type"] !== "assistant") return null;
105
106 const message = record["message"];
107 if (typeof message !== "object" || message === null) return null;
108 const messageRecord = message as Record<string, unknown>;
109
110 const usage = messageRecord["usage"];
111 if (typeof usage !== "object" || usage === null) return null;
112 const usageRecord = usage as Record<string, unknown>;
113
114 const timestampMs = parseTimestampMs(record["timestamp"]);
115 if (timestampMs === null) return null;
116
117 const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : "";
118 if (model.length === 0) return null;
119
120 const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null;
121 const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null;
122 // Matches ccusage: prefer the message/request pair, fall back to whichever
123 // half exists. Records with neither cannot be de-duplicated.
124 const dedupeKey =
125 messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`;
126
127 const cost = record["costUSD"];
128
129 return {
130 provider: "claude",
131 timestampMs,
132 model,
133 sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "",
134 totals: {
135 uncachedInputTokens: int(usageRecord["input_tokens"]),
136 cachedInputTokens: int(usageRecord["cache_read_input_tokens"]),
137 cacheCreationTokens: int(usageRecord["cache_creation_input_tokens"]),
138 outputTokens: int(usageRecord["output_tokens"]),
139 // Anthropic folds thinking tokens into output and does not break them out.
140 reasoningTokens: 0,
141 },
142 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
143 dedupeKey,
144 };
145}
146
147/* -------------------------------------------------------------------------- */
148/* Codex */
149/* -------------------------------------------------------------------------- */
150
151/**
152 * Rolling state for a single Codex rollout file.
153 *
154 * Codex `token_count` events carry no model, so the model is carried forward
155 * from the most recent `turn_context`. Sessions that switch models mid-run
156 * attribute correctly from the switch onward.
157 */
158export interface CodexScanState {
159 model: string;
160 sessionId: string;
161 lastUsageSignature: string | null;
162}
163
164export function initialCodexScanState(): CodexScanState {
165 return { model: "", sessionId: "", lastUsageSignature: null };
166}
167
168/**
169 * Feeds one line of a Codex rollout into `state`, returning a record when the
170 * line was a usage event.
171 *
172 * Deltas come from `last_token_usage`. Summing those across a session
173 * reconciles with the session's final `total_token_usage`, provided
174 * consecutive duplicate events are dropped, which this does.
175 */
176export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
177 let parsed: unknown;
178 try {
179 parsed = JSON.parse(line);
180 } catch {
181 return null;
182 }
183 if (typeof parsed !== "object" || parsed === null) return null;
184
185 const record = parsed as Record<string, unknown>;
186 const payload = record["payload"];
187 if (typeof payload !== "object" || payload === null) return null;
188 const payloadRecord = payload as Record<string, unknown>;
189 const payloadType = payloadRecord["type"];
190
191 if (record["type"] === "session_meta") {
192 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
193 if (typeof id === "string") state.sessionId = id;
194 return null;
195 }
196
197 if (record["type"] === "turn_context") {
198 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
199 return null;
200 }
201
202 if (payloadType !== "token_count") return null;
203
204 const info = payloadRecord["info"];
205 if (typeof info !== "object" || info === null) return null;
206 const last = (info as Record<string, unknown>)["last_token_usage"];
207 if (typeof last !== "object" || last === null) return null;
208 const lastRecord = last as Record<string, unknown>;
209
210 // Only an event that is otherwise eligible may consume the duplicate
211 // signature. A token_count arriving before its turn_context (no model yet)
212 // must not poison it, or the re-emitted copy after the model is known would
213 // be skipped as a duplicate and those tokens never counted.
214 const timestampMs = parseTimestampMs(record["timestamp"]);
215 if (timestampMs === null) return null;
216 if (state.model.length === 0) return null;
217
218 // Codex re-emits an unchanged token_count on some stream boundaries. Summing
219 // those would double count, so identical consecutive payloads are skipped.
220 const signature = JSON.stringify(lastRecord);
221 if (signature === state.lastUsageSignature) return null;
222 state.lastUsageSignature = signature;
223
224 const inputTokens = int(lastRecord["input_tokens"]);
225 const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
226 const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
227 const outputTokens = int(lastRecord["output_tokens"]);
228
229 const totals: UsageTokenTotals = {
230 // Codex reports `input_tokens` inclusive of the cached portion.
231 uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
232 cachedInputTokens,
233 cacheCreationTokens,
234 outputTokens,
235 // Reported inside output_tokens, surfaced separately for the token mix.
236 reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])),
237 };
238
239 if (totalTokens(totals) === 0) return null;
240
241 return {
242 provider: "codex",
243 timestampMs,
244 model: state.model,
245 sessionId: state.sessionId,
246 totals,
247 // Codex does not report cost in the rollout.
248 reportedCostUsd: null,
249 // Rollout files are unique per session, so events need no global dedup.
250 dedupeKey: null,
251 };
252}
253
254export { EMPTY_TOTALS };