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

usageTranscripts.ts

300 lines11.2 KB

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;
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 return provider === "claude" ? line.includes('"usage"') : line.includes('"token_count"');
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 };
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 sawSessionMeta: boolean;
155 /** While true, leading usage events are re-stamped copies of parent history. */
156 suppressingForkCopies: boolean;
157 forkCopyAnchorMs: number;
159​
160export function initialCodexScanState(): CodexScanState {
161 return {
162 model: "",
163 sessionId: "",
164 lastUsageSignature: null,
165 sawSessionMeta: false,
166 suppressingForkCopies: false,
167 forkCopyAnchorMs: 0,
168 };
170​
171/**
172 * A forked or subagent rollout opens with the parent's full history copied in,
173 * every line re-stamped to the fork instant. Those copies are written in one
174 * synchronous burst (observed gaps 0-40ms), while the child's first genuine
175 * usage event only lands after a real model turn (observed 5s+). One second of
176 * separation splits the two cleanly; `ccusage` uses the same threshold.
177 */
178const FORK_COPY_MAX_GAP_MS = 1000;
179​
180/** Whether a `session_meta` payload marks the rollout as a fork or subagent. */
181function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
182 if (typeof payload["forked_from_id"] === "string") return true;
183 const source = payload["source"];
184 if (typeof source !== "object" || source === null) return false;
185 const subagent = (source as Record<string, unknown>)["subagent"];
186 if (typeof subagent !== "object" || subagent === null) return false;
187 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
188 if (typeof spawn !== "object" || spawn === null) return false;
189 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
191​
192/**
193 * Feeds one line of a Codex rollout into `state`, returning a record when the
194 * line was a usage event.
195 *
196 * Deltas come from `last_token_usage`. Summing those across a session
197 * reconciles with the session's final `total_token_usage`, provided
198 * consecutive duplicate events are dropped, which this does.
199 */
200export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
201 let parsed: unknown;
202 try {
203 parsed = JSON.parse(line);
204 } catch {
205 return null;
206 }
207 if (typeof parsed !== "object" || parsed === null) return null;
208​
209 const record = parsed as Record<string, unknown>;
210 const payload = record["payload"];
211 if (typeof payload !== "object" || payload === null) return null;
212 const payloadRecord = payload as Record<string, unknown>;
213 const payloadType = payloadRecord["type"];
214​
215 if (record["type"] === "session_meta") {
216 // Only the first meta describes this file's own session. A forked rollout
217 // repeats the ancestors' metas right after it; letting those through would
218 // reassign every subsequent record to an ancestor session.
219 if (state.sawSessionMeta) return null;
220 state.sawSessionMeta = true;
221 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
222 if (typeof id === "string") state.sessionId = id;
223 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
224 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
225 state.suppressingForkCopies = true;
226 state.forkCopyAnchorMs = metaTimestampMs;
227 }
228 return null;
229 }
230​
231 if (record["type"] === "turn_context") {
232 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
233 return null;
234 }
235​
236 if (payloadType !== "token_count") return null;
237​
238 const info = payloadRecord["info"];
239 if (typeof info !== "object" || info === null) return null;
240 const last = (info as Record<string, unknown>)["last_token_usage"];
241 if (typeof last !== "object" || last === null) return null;
242 const lastRecord = last as Record<string, unknown>;
243​
244 // Only an event that is otherwise eligible may consume the duplicate
245 // signature. A token_count arriving before its turn_context (no model yet)
246 // must not poison it, or the re-emitted copy after the model is known would
247 // be skipped as a duplicate and those tokens never counted.
248 const timestampMs = parseTimestampMs(record["timestamp"]);
249 if (timestampMs === null) return null;
250 if (state.model.length === 0) return null;
251​
252 // Codex re-emits an unchanged token_count on some stream boundaries. Summing
253 // those would double count, so identical consecutive payloads are skipped.
254 const signature = JSON.stringify(lastRecord);
255 if (signature === state.lastUsageSignature) return null;
256 state.lastUsageSignature = signature;
257​
258 // In a forked rollout the copied parent history was already counted from the
259 // parent's own file. Drop the leading burst; the first usage event separated
260 // from its predecessor by a real turn's worth of time ends it for good.
261 if (state.suppressingForkCopies) {
262 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
263 state.forkCopyAnchorMs = timestampMs;
264 return null;
265 }
266 state.suppressingForkCopies = false;
267 }
268​
269 const inputTokens = int(lastRecord["input_tokens"]);
270 const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
271 const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
272 const outputTokens = int(lastRecord["output_tokens"]);
273​
274 const totals: UsageTokenTotals = {
275 // Codex reports `input_tokens` inclusive of the cached portion.
276 uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
277 cachedInputTokens,
278 cacheCreationTokens,
279 outputTokens,
280 // Reported inside output_tokens, surfaced separately for the token mix.
281 reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])),
282 };
283​
284 if (totalTokens(totals) === 0) return null;
285​
286 return {
287 provider: "codex",
288 timestampMs,
289 model: state.model,
290 sessionId: state.sessionId,
291 totals,
292 // Codex does not report cost in the rollout.
293 reportedCostUsd: null,
294 // Events surviving the fork-copy suppression above are unique to this
295 // rollout, so they need no global dedup.
296 dedupeKey: null,
297 };
299​
300export { EMPTY_TOTALS };