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