Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2
3import {
4 GROK_COST_USD_TICKS_PER_DOLLAR,
5 initialCodexScanState,
6 parseClaudeLine,
7 parseCodexLine,
8 parseGrokLine,
9 totalTokens,
10} from "./usageTranscripts.ts";
11
12/** Shaped after a real Claude Code assistant record. */
13function claudeLine(overrides: {
14 messageId: string;
15 contentType: string;
16 model?: string;
17 outputTokens?: number;
18 speed?: string;
19}): string {
20 return JSON.stringify({
21 type: "assistant",
22 timestamp: "2026-08-07T04:05:13.944Z",
23 sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
24 cwd: "/home/theo/project",
25 message: {
26 id: overrides.messageId,
27 role: "assistant",
28 model: overrides.model ?? "claude-fable-5",
29 content: [{ type: overrides.contentType }],
30 usage: {
31 input_tokens: 2,
32 cache_creation_input_tokens: 66818,
33 cache_read_input_tokens: 1000,
34 output_tokens: overrides.outputTokens ?? 286,
35 ...(overrides.speed === undefined ? {} : { speed: overrides.speed }),
36 },
37 },
38 });
39}
40
41describe("parseClaudeLine", () => {
42 it("extracts token totals and a dedupe key", () => {
43 const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
44
45 expect(record).not.toBeNull();
46 expect(record?.provider).toBe("claude");
47 expect(record?.model).toBe("claude-fable-5");
48 expect(record?.totals).toEqual({
49 uncachedInputTokens: 2,
50 cachedInputTokens: 1000,
51 cacheCreationTokens: 66818,
52 outputTokens: 286,
53 reasoningTokens: 0,
54 });
55 expect(record?.dedupeKey).toBe("msg_1:");
56 expect(record?.fast).toBe(false);
57 });
58
59 it("marks fast-mode requests", () => {
60 const line = (speed: string) =>
61 parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed }));
62
63 expect(line("fast")?.fast).toBe(true);
64 expect(line("standard")?.fast).toBe(false);
65 });
66
67 it("gives every content block of one message the same dedupe key", () => {
68 // T3 Code writes one record per content block, each repeating the parent
69 // message's full usage. Summing them would overcount ~2.4x on real data.
70 const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
71 const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
72
73 expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
74 expect(text?.totals).toEqual(toolUse?.totals);
75 });
76
77 it("ignores records that are not assistant messages", () => {
78 expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
79 expect(parseClaudeLine("not json")).toBeNull();
80 });
81});
82
83describe("parseCodexLine", () => {
84 const sessionMeta = JSON.stringify({
85 type: "session_meta",
86 timestamp: "2026-08-01T05:17:41.289Z",
87 payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
88 });
89 const turnContext = JSON.stringify({
90 type: "turn_context",
91 timestamp: "2026-08-01T05:17:42.694Z",
92 payload: { type: "turn_context", model: "gpt-5.6-sol" },
93 });
94 const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
95 JSON.stringify({
96 type: "event_msg",
97 timestamp: "2026-08-01T05:17:49.919Z",
98 payload: {
99 type: "token_count",
100 info: {
101 last_token_usage: {
102 input_tokens: inputTokens,
103 cached_input_tokens: cached,
104 cache_write_input_tokens: 0,
105 output_tokens: output,
106 reasoning_output_tokens: reasoning,
107 },
108 },
109 },
110 });
111
112 it("attributes usage to the model from the preceding turn context", () => {
113 const state = initialCodexScanState();
114 parseCodexLine(sessionMeta, state);
115 parseCodexLine(turnContext, state);
116 const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
117
118 expect(record?.provider).toBe("codex");
119 expect(record?.model).toBe("gpt-5.6-sol");
120 expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
121 // Codex reports input_tokens inclusive of the cached portion.
122 expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
123 expect(record?.totals.cachedInputTokens).toBe(11008);
124 expect(record?.totals.reasoningTokens).toBe(116);
125 });
126
127 it("skips a repeated token_count so deltas are not double counted", () => {
128 const state = initialCodexScanState();
129 parseCodexLine(turnContext, state);
130 const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
131 const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
132
133 expect(first).not.toBeNull();
134 expect(repeat).toBeNull();
135 });
136
137 it("drops usage that arrives before any model is known", () => {
138 const state = initialCodexScanState();
139 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
140 });
141
142 it("does not let a pre-model event poison the duplicate signature", () => {
143 // A token_count before its turn_context is dropped; the identical event
144 // re-emitted once the model is known must still be counted.
145 const state = initialCodexScanState();
146 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
147 parseCodexLine(turnContext, state);
148 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
149 });
150
151 // A forked/subagent rollout opens with the parent's history copied in and
152 // every line re-stamped to the fork instant, then the ancestors' session
153 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
154 describe("forked rollouts", () => {
155 const meta = (overrides: {
156 id: string;
157 timestamp: string;
158 forkedFromId?: string;
159 spawnParentId?: string;
160 }) =>
161 JSON.stringify({
162 type: "session_meta",
163 timestamp: overrides.timestamp,
164 payload: {
165 type: "session_meta",
166 id: overrides.id,
167 ...(overrides.forkedFromId === undefined
168 ? {}
169 : { forked_from_id: overrides.forkedFromId }),
170 ...(overrides.spawnParentId === undefined
171 ? {}
172 : {
173 source: {
174 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
175 },
176 }),
177 },
178 });
179 const stamped = (timestamp: string, line: string) => {
180 const parsed = JSON.parse(line) as { timestamp: string };
181 parsed.timestamp = timestamp;
182 return JSON.stringify(parsed);
183 };
184
185 it("keeps the child session id over copied ancestor metas", () => {
186 const state = initialCodexScanState();
187 parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
188 parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
189 parseCodexLine(turnContext, state);
190 const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
191
192 expect(record?.sessionId).toBe("child");
193 });
194
195 it("drops the re-stamped copied burst and keeps the first real event", () => {
196 const state = initialCodexScanState();
197 const forkInstant = "2026-08-01T05:00:00.000Z";
198 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
199 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
200 parseCodexLine(stamped(forkInstant, turnContext), state);
201
202 // Copied history: written in one burst at the fork instant.
203 expect(
204 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
205 ).toBeNull();
206 expect(
207 parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
208 ).toBeNull();
209
210 // The child's first genuine turn lands seconds later and must count.
211 const real = parseCodexLine(
212 stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
213 state,
214 );
215 expect(real).not.toBeNull();
216 expect(real?.totals.outputTokens).toBe(30);
217
218 // Suppression never restarts, even for closely spaced later events.
219 const next = parseCodexLine(
220 stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
221 state,
222 );
223 expect(next).not.toBeNull();
224 });
225
226 it("recognizes subagent spawns without forked_from_id", () => {
227 const state = initialCodexScanState();
228 const spawnInstant = "2026-08-01T05:00:00.000Z";
229 parseCodexLine(
230 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
231 state,
232 );
233 parseCodexLine(stamped(spawnInstant, turnContext), state);
234 expect(
235 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
236 ).toBeNull();
237 });
238
239 it("does not suppress anything in a rollout that is not a fork", () => {
240 const state = initialCodexScanState();
241 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
242 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
243 const record = parseCodexLine(
244 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
245 state,
246 );
247 expect(record).not.toBeNull();
248 });
249 });
250});
251
252describe("totalTokens", () => {
253 it("does not add reasoning on top of output", () => {
254 expect(
255 totalTokens({
256 uncachedInputTokens: 10,
257 cachedInputTokens: 20,
258 cacheCreationTokens: 30,
259 outputTokens: 40,
260 reasoningTokens: 25,
261 }),
262 ).toBe(100);
263 });
264});
265
266describe("parseGrokLine", () => {
267 /** Shaped after a real Grok Build `turn_completed` session update. */
268 function turnCompleted(overrides?: {
269 sessionId?: string;
270 promptId?: string;
271 timestamp?: number;
272 agentTimestampMs?: number;
273 usage?: Record<string, unknown>;
274 modelUsage?: Record<string, Record<string, unknown>> | null;
275 }): string {
276 const modelUsage =
277 overrides && "modelUsage" in overrides
278 ? overrides.modelUsage
279 : {
280 "grok-4.5-build": {
281 inputTokens: 20_272,
282 outputTokens: 272,
283 totalTokens: 20_544,
284 cachedReadTokens: 11_264,
285 cacheCreationTokens: 0,
286 reasoningTokens: 180,
287 costUsdTicks: 230_272_000,
288 },
289 };
290
291 return JSON.stringify({
292 timestamp: overrides?.timestamp ?? 1_786_372_566,
293 method: "_x.ai/session/update",
294 params: {
295 sessionId: overrides?.sessionId ?? "019fec1a-12f7-72f2-9b1f-7778a00aea3c",
296 update: {
297 sessionUpdate: "turn_completed",
298 prompt_id: overrides?.promptId ?? "prompt-1",
299 stop_reason: "end_turn",
300 usage: {
301 inputTokens: 20_272,
302 outputTokens: 272,
303 totalTokens: 20_544,
304 cachedReadTokens: 11_264,
305 cacheCreationTokens: 0,
306 reasoningTokens: 180,
307 costUsdTicks: 230_272_000,
308 ...(modelUsage === null ? {} : { modelUsage }),
309 ...overrides?.usage,
310 },
311 },
312 _meta: {
313 eventId: "event-1",
314 agentTimestampMs: overrides?.agentTimestampMs ?? 1_786_372_566_485,
315 },
316 },
317 });
318 }
319
320 it("extracts per-model totals and provider-reported cost ticks", () => {
321 const records = parseGrokLine(turnCompleted());
322
323 expect(records).toHaveLength(1);
324 const [record] = records;
325 expect(record?.provider).toBe("grok");
326 expect(record?.model).toBe("grok-4.5-build");
327 expect(record?.sessionId).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c");
328 expect(record?.timestampMs).toBe(1_786_372_566_485);
329 expect(record?.totals).toEqual({
330 uncachedInputTokens: 20_272 - 11_264,
331 cachedInputTokens: 11_264,
332 cacheCreationTokens: 0,
333 outputTokens: 272,
334 reasoningTokens: 180,
335 });
336 expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
337 expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok-4.5-build");
338 });
339
340 it("emits one record per model when modelUsage has several entries", () => {
341 const records = parseGrokLine(
342 turnCompleted({
343 modelUsage: {
344 "grok-4.5": {
345 inputTokens: 1000,
346 outputTokens: 50,
347 cachedReadTokens: 400,
348 reasoningTokens: 20,
349 costUsdTicks: 50_000_000,
350 },
351 "grok-composer-2.5-fast": {
352 inputTokens: 200,
353 outputTokens: 30,
354 cachedReadTokens: 100,
355 reasoningTokens: 0,
356 costUsdTicks: 10_000_000,
357 },
358 },
359 }),
360 );
361
362 expect(records.map((record) => record.model).toSorted()).toEqual([
363 "grok-4.5",
364 "grok-composer-2.5-fast",
365 ]);
366 expect(records.every((record) => record.provider === "grok")).toBe(true);
367 expect(records.find((record) => record.model === "grok-4.5")?.reportedCostUsd).toBeCloseTo(
368 0.005,
369 12,
370 );
371 });
372
373 it("inherits top-level cost ticks for a single model without its own ticks", () => {
374 const records = parseGrokLine(
375 turnCompleted({
376 modelUsage: {
377 "grok-4.5-build": {
378 inputTokens: 1000,
379 outputTokens: 10,
380 cachedReadTokens: 0,
381 reasoningTokens: 0,
382 },
383 },
384 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
385 }),
386 );
387
388 expect(records).toHaveLength(1);
389 expect(records[0]?.reportedCostUsd).toBe(1);
390 });
391
392 it("falls back to a generic grok model when modelUsage is absent", () => {
393 const records = parseGrokLine(turnCompleted({ modelUsage: null }));
394
395 expect(records).toHaveLength(1);
396 const [record] = records;
397 expect(record?.provider).toBe("grok");
398 expect(record?.model).toBe("grok");
399 expect(record?.totals).toEqual({
400 uncachedInputTokens: 20_272 - 11_264,
401 cachedInputTokens: 11_264,
402 cacheCreationTokens: 0,
403 outputTokens: 272,
404 reasoningTokens: 180,
405 });
406 expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
407 expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok");
408 });
409
410 it("pro-rates top-level cost ticks across multi-model turns without per-model ticks", () => {
411 const records = parseGrokLine(
412 turnCompleted({
413 modelUsage: {
414 "grok-4.5": {
415 inputTokens: 300,
416 outputTokens: 0,
417 cachedReadTokens: 0,
418 reasoningTokens: 0,
419 },
420 "grok-composer-2.5-fast": {
421 inputTokens: 100,
422 outputTokens: 0,
423 cachedReadTokens: 0,
424 reasoningTokens: 0,
425 },
426 },
427 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
428 }),
429 );
430
431 expect(records).toHaveLength(2);
432 const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
433 expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
434 expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
435 const sum =
436 (byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
437 (byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
438 expect(sum).toBeCloseTo(1, 12);
439 });
440
441 it("pro-rates aggregate cost when a zero-token sibling carries costUsdTicks: 0", () => {
442 const records = parseGrokLine(
443 turnCompleted({
444 modelUsage: {
445 "grok-4.5": {
446 inputTokens: 300,
447 outputTokens: 0,
448 cachedReadTokens: 0,
449 reasoningTokens: 0,
450 },
451 "grok-composer-2.5-fast": {
452 inputTokens: 100,
453 outputTokens: 0,
454 cachedReadTokens: 0,
455 reasoningTokens: 0,
456 },
457 "empty-sibling": {
458 inputTokens: 0,
459 outputTokens: 0,
460 cachedReadTokens: 0,
461 reasoningTokens: 0,
462 costUsdTicks: 0,
463 },
464 },
465 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
466 }),
467 );
468
469 expect(records).toHaveLength(2);
470 expect(records.every((record) => record.model !== "empty-sibling")).toBe(true);
471 const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
472 expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
473 expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
474 const sum =
475 (byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
476 (byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
477 expect(sum).toBeCloseTo(1, 12);
478 });
479
480 it("allocates leftover aggregate ticks to models that omit per-model ticks", () => {
481 const records = parseGrokLine(
482 turnCompleted({
483 modelUsage: {
484 "grok-4.5": {
485 inputTokens: 300,
486 outputTokens: 0,
487 cachedReadTokens: 0,
488 reasoningTokens: 0,
489 costUsdTicks: 0.4 * GROK_COST_USD_TICKS_PER_DOLLAR,
490 },
491 "grok-composer-2.5-fast": {
492 inputTokens: 100,
493 outputTokens: 0,
494 cachedReadTokens: 0,
495 reasoningTokens: 0,
496 },
497 },
498 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
499 }),
500 );
501
502 expect(records).toHaveLength(2);
503 const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
504 expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.4, 12);
505 expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.6, 12);
506 const sum =
507 (byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
508 (byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
509 expect(sum).toBeCloseTo(1, 12);
510 });
511
512 it("does not invent a colliding dedupe key when prompt_id is missing", () => {
513 const line = JSON.stringify({
514 timestamp: 1_786_372_566,
515 method: "_x.ai/session/update",
516 params: {
517 sessionId: "s1",
518 update: {
519 sessionUpdate: "turn_completed",
520 usage: {
521 inputTokens: 10,
522 outputTokens: 2,
523 modelUsage: {
524 "grok-4.5": { inputTokens: 10, outputTokens: 2 },
525 },
526 },
527 },
528 },
529 });
530
531 expect(parseGrokLine(line)[0]?.dedupeKey).toBeNull();
532 });
533
534 it("ignores non-turn lines and empty usage", () => {
535 expect(parseGrokLine(JSON.stringify({ method: "session/update", params: {} }))).toEqual([]);
536 expect(parseGrokLine("not json")).toEqual([]);
537 expect(
538 parseGrokLine(
539 turnCompleted({
540 modelUsage: {
541 "grok-4.5-build": {
542 inputTokens: 0,
543 outputTokens: 0,
544 cachedReadTokens: 0,
545 reasoningTokens: 0,
546 costUsdTicks: 0,
547 },
548 },
549 }),
550 ),
551 ).toEqual([]);
552 });
553
554 it("falls back to the outer unix-seconds timestamp when agent meta is missing", () => {
555 const line = JSON.stringify({
556 timestamp: 1_786_372_566,
557 method: "_x.ai/session/update",
558 params: {
559 sessionId: "s1",
560 update: {
561 sessionUpdate: "turn_completed",
562 prompt_id: "p1",
563 usage: {
564 inputTokens: 10,
565 outputTokens: 2,
566 modelUsage: {
567 "grok-4.5": { inputTokens: 10, outputTokens: 2 },
568 },
569 },
570 },
571 },
572 });
573
574 const records = parseGrokLine(line);
575 expect(records[0]?.timestampMs).toBe(1_786_372_566_000);
576 });
577});