Open History to see the last commit
1import type { CodexSettings } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Path from "effect/Path";
4import * as Schema from "effect/Schema";
5
6import {
7 parseTimestampMs,
8 type ProviderUsageReader,
9 type TranscriptUsageFormat,
10 type UsageRecord,
11 type UsageSpeed,
12} from "@t3tools/provider-core/server/usage";
13import type { UsageTokenTotals } from "@t3tools/contracts";
14
15import * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts";
16import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts";
17
18const TokenCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
19const CodexTokenUsage = Schema.Struct({
20 input_tokens: TokenCount,
21 cached_input_tokens: TokenCount,
22 cache_write_input_tokens: TokenCount,
23 output_tokens: TokenCount,
24 reasoning_output_tokens: TokenCount,
25 total_tokens: TokenCount,
26}).check(
27 Schema.makeFilter(
28 (usage) =>
29 usage.cached_input_tokens + usage.cache_write_input_tokens <= usage.input_tokens &&
30 usage.reasoning_output_tokens <= usage.output_tokens &&
31 usage.total_tokens >= usage.input_tokens + usage.output_tokens,
32 ),
33);
34type CodexTokenUsage = typeof CodexTokenUsage.Type;
35const isCodexTokenUsage = Schema.is(CodexTokenUsage);
36const CODEX_USAGE_FIELDS = Object.keys(CodexTokenUsage.fields) as (keyof CodexTokenUsage)[];
37
38function readCodexTokenUsage(value: unknown): CodexTokenUsage | null {
39 if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
40 const raw = value as Record<string, unknown>;
41 const input = raw["input_tokens"];
42 const output = raw["output_tokens"];
43 if (typeof input !== "number" || typeof output !== "number") return null;
44 const usage = {
45 input_tokens: input,
46 cached_input_tokens: raw["cached_input_tokens"] === undefined ? 0 : raw["cached_input_tokens"],
47 cache_write_input_tokens:
48 raw["cache_write_input_tokens"] === undefined ? 0 : raw["cache_write_input_tokens"],
49 output_tokens: output,
50 reasoning_output_tokens:
51 raw["reasoning_output_tokens"] === undefined ? 0 : raw["reasoning_output_tokens"],
52 total_tokens: raw["total_tokens"] === undefined ? input + output : raw["total_tokens"],
53 };
54 return isCodexTokenUsage(usage) ? usage : null;
55}
56
57// Every move of the baseline dates it, so an older snapshot re-emitted later is never a rewind.
58function dateCodexBaseline(state: CodexScanState, timestampMs: number) {
59 state.latestCumulativeAtMs = Math.max(state.latestCumulativeAtMs ?? timestampMs, timestampMs);
60}
61
62// A zeroed baseline rebases the counters, so the sequence start measured against it is forgotten.
63function rebaseCodexUsage(state: CodexScanState, cumulative: CodexTokenUsage, timestampMs: number) {
64 state.lastCumulativeUsage = cumulative;
65 dateCodexBaseline(state, timestampMs);
66 delete state.unreportedRequests;
67 if (cumulative.input_tokens + cumulative.output_tokens === 0) delete state.sequenceStartSignature;
68}
69
70function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsage) {
71 return readCodexTokenUsage(
72 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, (previous?.[key] ?? 0) + last[key]])),
73 );
74}
75
76const CodexSpeed = Schema.Literals(["standard", "fast", "ultrafast"]);
77
78// What a request is billed as is fixed when it is read, not when a later snapshot reconciles it.
79const CodexUnreportedRequest = Schema.Struct({
80 timestampMs: Schema.Finite,
81 model: Schema.String,
82 turnId: Schema.String,
83 speed: CodexSpeed,
84 sawThreadSettings: Schema.Boolean,
85 usage: CodexTokenUsage,
86});
87type CodexUnreportedRequest = typeof CodexUnreportedRequest.Type;
88type CodexRequestAttribution = Omit<CodexUnreportedRequest, "usage">;
89
90// An interrupted turn can end before a snapshot reports its last request. Bill those requests only
91// when the `token_usage_record`s since the previous snapshot explain the whole gap; `last` is the
92// final one.
93function unreportedRequests(
94 previous: CodexTokenUsage | null,
95 cumulative: CodexTokenUsage,
96 last: CodexTokenUsage,
97 pending: readonly CodexUnreportedRequest[] | undefined,
98) {
99 if (
100 previous === null ||
101 pending === undefined ||
102 CODEX_USAGE_FIELDS.some(
103 (key) =>
104 cumulative[key] - previous[key] !==
105 pending.reduce((sum, request) => sum + request.usage[key], 0),
106 )
107 ) {
108 return null;
109 }
110 const final = pending.at(-1)!;
111 const remainder = readCodexTokenUsage(
112 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, final.usage[key] - last[key]])),
113 );
114 if (remainder === null) return null;
115 return [...pending.slice(0, -1), { ...final, usage: remainder }].filter(
116 (request) => request.usage.input_tokens + request.usage.output_tokens > 0,
117 );
118}
119
120// A rewound snapshot vouches only for the request it reports, so the anonymous requests read before
121// it can be neither billed nor ruled out as that request's prefix.
122function discardedRequests(
123 pending: readonly CodexUnreportedRequest[] | undefined,
124 last: CodexTokenUsage,
125) {
126 const final = pending?.at(-1);
127 if (pending === undefined || final === undefined) return 0;
128 const reported = CODEX_USAGE_FIELDS.every((key) => final.usage[key] === last[key]);
129 return pending.length - (reported ? 1 : 0);
130}
131
132/**
133 * Codex `token_count` events carry no model or service tier, so both are carried forward: the model
134 * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`.
135 */
136export const CodexScanState = Schema.Struct({
137 model: Schema.mutableKey(Schema.String),
138 speed: Schema.mutableKey(CodexSpeed),
139 sessionId: Schema.mutableKey(Schema.String),
140 lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
141 lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)),
142 // Optional so scan states cached before these fields existed stay valid.
143 sequenceStartSignature: Schema.mutableKey(Schema.optionalKey(Schema.String)),
144 latestCumulativeAtMs: Schema.mutableKey(Schema.optionalKey(Schema.Finite)),
145 // `token_usage_record` usage since the last cumulative snapshot, one entry per record.
146 unreportedRequests: Schema.mutableKey(
147 Schema.optionalKey(Schema.mutable(Schema.Array(CodexUnreportedRequest))),
148 ),
149 requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)),
150 malformedRecords: Schema.mutableKey(TokenCount),
151 malformedRecordTimestamps: Schema.mutableKey(
152 Schema.optionalKey(Schema.mutable(Schema.Array(Schema.Finite))),
153 ),
154 sawSessionMeta: Schema.mutableKey(Schema.Boolean),
155 modelProvider: Schema.mutableKey(Schema.String),
156 turnId: Schema.mutableKey(Schema.String),
157 sawThreadSettings: Schema.mutableKey(Schema.Boolean),
158 suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
159 forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
160});
161export type CodexScanState = typeof CodexScanState.Type;
162
163export function initialCodexScanState(): CodexScanState {
164 return {
165 model: "",
166 speed: "standard",
167 sessionId: "",
168 lastUsageSignature: null,
169 lastCumulativeUsage: null,
170 malformedRecords: 0,
171 sawSessionMeta: false,
172 modelProvider: "",
173 turnId: "",
174 sawThreadSettings: false,
175 suppressingForkCopies: false,
176 forkCopyAnchorMs: 0,
177 };
178}
179
180/** Forks copy and restamp parent history in a burst (0-40ms gaps); genuine child usage follows a model turn (5s+ observed). */
181const FORK_COPY_MAX_GAP_MS = 1000;
182
183function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
184 if (typeof payload["forked_from_id"] === "string") return true;
185 const source = payload["source"];
186 if (typeof source !== "object" || source === null) return false;
187 const subagent = (source as Record<string, unknown>)["subagent"];
188 if (typeof subagent !== "object" || subagent === null) return false;
189 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
190 if (typeof spawn !== "object" || spawn === null) return false;
191 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
192}
193
194// The first usage line past the copied burst ends suppression for the rest of the rollout.
195function isForkCopy(state: CodexScanState, timestampMs: number): boolean {
196 if (!state.suppressingForkCopies) return false;
197 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
198 state.forkCopyAnchorMs = timestampMs;
199 return true;
200 }
201 state.suppressingForkCopies = false;
202 state.lastUsageSignature = null;
203 return false;
204}
205
206/**
207 * Identified request-ledger entries report spending independently of context snapshots.
208 * Legacy snapshots validate request deltas against cumulative counters.
209 */
210export function parseCodexLine(line: string, state: CodexScanState): readonly UsageRecord[] {
211 let parsed: unknown;
212 try {
213 parsed = JSON.parse(line);
214 } catch {
215 return [];
216 }
217 return parseCodexRecord(parsed, state);
218}
219
220function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly UsageRecord[] {
221 if (typeof parsed !== "object" || parsed === null) return [];
222
223 const record = parsed as Record<string, unknown>;
224 const payload = record["payload"];
225 if (typeof payload !== "object" || payload === null) return [];
226 const payloadRecord = payload as Record<string, unknown>;
227 const payloadType = payloadRecord["type"];
228
229 if (record["type"] === "session_meta") {
230 // Only the first meta identifies this session; copied ancestor metas would misattribute later records.
231 if (state.sawSessionMeta) return [];
232 state.sawSessionMeta = true;
233 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
234 if (typeof id === "string") state.sessionId = id;
235 if (typeof payloadRecord["model_provider"] === "string") {
236 state.modelProvider = payloadRecord["model_provider"];
237 }
238 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
239 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
240 state.suppressingForkCopies = true;
241 state.forkCopyAnchorMs = metaTimestampMs;
242 }
243 return [];
244 }
245
246 if (record["type"] === "turn_context") {
247 state.requestLedgerActive = false;
248 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
249 // Model carry is useful for usage, but history recovery needs this context's own identity.
250 state.turnId =
251 typeof payloadRecord["turn_id"] === "string" &&
252 typeof payloadRecord["model"] === "string" &&
253 payloadRecord["model"].length > 0
254 ? payloadRecord["turn_id"]
255 : "";
256 return [];
257 }
258
259 // Request ledgers include spending that context snapshots can omit.
260 if (record["type"] === "token_usage_record") {
261 const timestampMs = parseTimestampMs(record["timestamp"]);
262 const usage = readCodexTokenUsage(payloadRecord["usage"]);
263 if (timestampMs === null || usage === null || state.model.length === 0) return [];
264 // Copied history is already billed in the parent.
265 if (isForkCopy(state, timestampMs)) return [];
266 const responseId = payloadRecord["response_id"];
267 if (typeof responseId === "string" && responseId.length > 0) {
268 const pending = state.unreportedRequests ?? [];
269 state.requestLedgerActive = true;
270 for (const request of pending) {
271 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, request.usage);
272 }
273 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, usage);
274 dateCodexBaseline(state, timestampMs);
275 delete state.unreportedRequests;
276 return [
277 ...pending.map((request) => codexRequestRecord(state, request.usage, request)),
278 {
279 ...codexRequestRecord(state, usage, codexAttribution(state, timestampMs)),
280 dedupeKey: JSON.stringify(["codex", state.sessionId, responseId]),
281 },
282 ];
283 }
284 state.requestLedgerActive = false;
285 (state.unreportedRequests ??= []).push({ ...codexAttribution(state, timestampMs), usage });
286 return [];
287 }
288
289 if (payloadType === "thread_settings_applied") {
290 state.sawThreadSettings = true;
291 const settings = payloadRecord["thread_settings"];
292 if (typeof settings === "object" && settings !== null) {
293 state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
294 }
295 return [];
296 }
297
298 if (payloadType !== "token_count") return [];
299
300 const info = payloadRecord["info"];
301 if (typeof info !== "object" || info === null) return [];
302 const infoRecord = info as Record<string, unknown>;
303
304 // Codex may re-emit these counters after the model or timestamp becomes available.
305 const timestampMs = parseTimestampMs(record["timestamp"]);
306 if (timestampMs === null || state.model.length === 0) return [];
307
308 const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
309 const rawCumulative = infoRecord["total_token_usage"];
310 const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
311 const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
312
313 if (isForkCopy(state, timestampMs)) {
314 // Copied history is already billed in the parent, but establishes the child's baseline.
315 const signature = last === null ? null : JSON.stringify(last);
316 if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs);
317 else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
318 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
319 dateCodexBaseline(state, timestampMs);
320 }
321 state.lastUsageSignature = signature;
322 return [];
323 }
324
325 // Context snapshots can rewind on resume and omit compaction spending; identified requests are authoritative.
326 if (state.requestLedgerActive) {
327 if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs);
328 return [];
329 }
330
331 const previous = state.lastCumulativeUsage;
332 const latestCumulativeAtMs = state.latestCumulativeAtMs;
333 const pending = state.unreportedRequests;
334 // A valid snapshot remains the next baseline even when its paired request is malformed.
335 if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs);
336 if (last === null || (hasCumulative && cumulative === null)) {
337 noteMalformedRecord(state, timestampMs);
338 return [];
339 }
340
341 // Zero-component counters report context size, not a request: fill_to_context_window, or the
342 // post-compaction marker whose total is the new context size (its cumulative may reset to zero).
343 if (last.input_tokens + last.output_tokens === 0) {
344 state.lastUsageSignature = null;
345 return [];
346 }
347
348 if (
349 cumulative !== null &&
350 previous !== null &&
351 CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
352 ) {
353 return [];
354 }
355
356 if (last.total_tokens !== last.input_tokens + last.output_tokens) {
357 noteMalformedRecord(state, timestampMs);
358 return [];
359 }
360
361 const signature = JSON.stringify(last);
362 let unreported: readonly CodexUnreportedRequest[] = [];
363 if (cumulative !== null) {
364 // A session resumed in a new Codex process restarts its cumulative counters at this request.
365 const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]);
366 const sequenceStart = JSON.stringify([timestampMs, last]);
367 // Only the same event is a replay; a later request can restart with identical counters.
368 if (restarted && sequenceStart === state.sequenceStartSignature) {
369 state.lastCumulativeUsage = previous;
370 // The retained baseline keeps its own age; one of unknown age must not take the replay's.
371 if (latestCumulativeAtMs === undefined) delete state.latestCumulativeAtMs;
372 return [];
373 }
374 // Forks and paginated continuations can inherit totals without copying a counter snapshot, and
375 // a later request can continue from an earlier snapshot; a re-emitted old snapshot is not later.
376 // Only bill the latest request, and require the unseen prefix to be valid usage too. A baseline
377 // of unknown age (a scan state cached before every move dated it) cannot order the snapshot.
378 const lowered =
379 previous !== null && CODEX_USAGE_FIELDS.some((key) => cumulative[key] < previous[key]);
380 const rewound =
381 lowered && latestCumulativeAtMs !== undefined && timestampMs > latestCumulativeAtMs;
382 const reconciled =
383 previous === null || rewound
384 ? readCodexTokenUsage(
385 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, cumulative[key] - last[key]])),
386 ) !== null
387 : CODEX_USAGE_FIELDS.every((key) => cumulative[key] - previous[key] === last[key]);
388 if (!restarted && !reconciled) {
389 const bridged = unreportedRequests(previous, cumulative, last, pending);
390 if (bridged === null) {
391 // A rejected snapshot from before the baseline's time is a replay, not the next baseline.
392 // At the baseline's own time only lower counters are one; zeroed counters still rebase.
393 const replayed =
394 latestCumulativeAtMs !== undefined &&
395 (timestampMs < latestCumulativeAtMs ||
396 (timestampMs === latestCumulativeAtMs &&
397 lowered &&
398 cumulative.input_tokens + cumulative.output_tokens > 0));
399 if (replayed) {
400 state.lastCumulativeUsage = previous;
401 if (pending !== undefined) state.unreportedRequests = pending;
402 }
403 noteMalformedRecord(state, timestampMs);
404 return [];
405 }
406 unreported = bridged;
407 } else if (!restarted && rewound) {
408 noteMalformedRecord(state, timestampMs, discardedRequests(pending, last));
409 }
410 if (restarted) state.sequenceStartSignature = sequenceStart;
411 } else {
412 if (signature === state.lastUsageSignature) return [];
413 // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
414 const advanced = advanceCodexUsage(previous, last);
415 if (advanced === null) {
416 noteMalformedRecord(state, timestampMs);
417 return [];
418 }
419 state.lastCumulativeUsage = advanced;
420 dateCodexBaseline(state, timestampMs);
421 }
422 state.lastUsageSignature = signature;
423
424 return [
425 ...unreported.map((request) => codexRequestRecord(state, request.usage, request)),
426 codexRequestRecord(state, last, codexAttribution(state, timestampMs)),
427 ];
428}
429
430function noteMalformedRecord(state: CodexScanState, timestampMs: number, count = 1) {
431 state.malformedRecords += count;
432 const timestamps = (state.malformedRecordTimestamps ??= []);
433 for (let index = 0; index < count; index++) timestamps.push(timestampMs);
434}
435
436function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution {
437 return {
438 timestampMs,
439 model: state.model,
440 turnId: state.turnId,
441 speed: state.speed,
442 sawThreadSettings: state.sawThreadSettings,
443 };
444}
445
446function codexRequestRecord(
447 state: CodexScanState,
448 usage: CodexTokenUsage,
449 { timestampMs, model, turnId, speed, sawThreadSettings }: CodexRequestAttribution,
450): UsageRecord {
451 const inputTokens = usage.input_tokens;
452 const cachedInputTokens = usage.cached_input_tokens;
453 const cacheCreationTokens = usage.cache_write_input_tokens;
454 const outputTokens = usage.output_tokens;
455
456 const totals: UsageTokenTotals = {
457 // Codex reports `input_tokens` inclusive of the cached portion.
458 uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
459 cachedInputTokens,
460 cacheCreationTokens,
461 outputTokens,
462 // Reported inside output_tokens, surfaced separately for the token mix.
463 reasoningTokens: usage.reasoning_output_tokens,
464 };
465
466 return {
467 provider: "codex",
468 timestampMs,
469 model,
470 sessionId: state.sessionId,
471 totals,
472 reportedCostUsd: null,
473 speed,
474 ...(!sawThreadSettings &&
475 state.modelProvider === "openai" &&
476 state.sessionId.length > 0 &&
477 turnId.length > 0
478 ? { unresolvedServiceTierTurnId: turnId }
479 : {}),
480 dedupeKey: null,
481 };
482}
483
484/** Missing, default and standard tiers bill as standard; fast aliases priority. */
485function codexSpeed(serviceTier: unknown): UsageSpeed {
486 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
487 if (serviceTier === "ultrafast") return "ultrafast";
488 return "standard";
489}
490
491export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
492 selectFields: {
493 type: true,
494 timestamp: true,
495 payload: {
496 type: true,
497 id: true,
498 session_id: true,
499 model_provider: true,
500 turn_id: true,
501 response_id: true,
502 model: true,
503 thread_settings: { service_tier: true },
504 forked_from_id: true,
505 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
506 info: { last_token_usage: true, total_token_usage: true },
507 usage: true,
508 },
509 },
510 // Metadata lines carry model, tier and session even without usage.
511 usageMarkers: [
512 '"token_count"',
513 '"token_usage_record"',
514 '"turn_context"',
515 '"thread_settings_applied"',
516 '"session_meta"',
517 ],
518 parseLine: parseCodexLine,
519 parseProjected: parseCodexRecord,
520 state: { initial: initialCodexScanState, schema: CodexScanState },
521 readMalformedRecords: (state) => state.malformedRecordTimestamps ?? [],
522 // A rollout that moved after it was read leaves a copy in both places.
523 sharedSessionsAcrossFiles: true,
524};
525
526export const codexUsageReader: ProviderUsageReader<
527 CodexSettings,
528 Path.Path | CodexUsageHistory.CodexUsageHistory
529> = {
530 kind: "transcripts",
531 provider: "codex",
532 format: codexUsageFormat,
533 resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) {
534 const history = yield* CodexUsageHistory.CodexUsageHistory;
535 const requests = new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageRecord>();
536 for (const record of records) {
537 if (record.unresolvedServiceTierTurnId === undefined) continue;
538 requests.set(
539 {
540 sessionId: record.sessionId,
541 nativeTurnId: record.unresolvedServiceTierTurnId,
542 model: record.model,
543 },
544 record,
545 );
546 }
547 const resolved = yield* history.resolve([...requests.keys()]).pipe(
548 Effect.catchTags({
549 CodexUsageHistoryReadError: () =>
550 Effect.succeed(new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageSpeed>()),
551 }),
552 );
553 const speeds = new Map<UsageRecord, UsageSpeed>();
554 for (const [request, speed] of resolved) {
555 const record = requests.get(request);
556 if (record !== undefined) speeds.set(record, speed);
557 }
558 return speeds;
559 }),
560 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
561 if (config === undefined) return [];
562 const path = yield* Path.Path;
563 const environmentHome = environment.CODEX_HOME?.trim();
564 const layout = yield* resolveCodexHomeLayout(
565 config.setupMode !== "managed" && !config.homePath.trim() && environmentHome
566 ? { ...config, homePath: environmentHome }
567 : config,
568 );
569 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
570 }),
571};