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// A zeroed baseline rebases the counters, so the sequence start measured against it is forgotten.
58function rebaseCodexUsage(state: CodexScanState, cumulative: CodexTokenUsage) {
59 state.lastCumulativeUsage = cumulative;
60 delete state.unreportedRequests;
61 if (cumulative.input_tokens + cumulative.output_tokens === 0) delete state.sequenceStartSignature;
62}
63
64function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsage) {
65 return readCodexTokenUsage(
66 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, (previous?.[key] ?? 0) + last[key]])),
67 );
68}
69
70const CodexSpeed = Schema.Literals(["standard", "fast", "ultrafast"]);
71
72// What a request is billed as is fixed when it is read, not when a later snapshot reconciles it.
73const CodexUnreportedRequest = Schema.Struct({
74 timestampMs: Schema.Finite,
75 model: Schema.String,
76 turnId: Schema.String,
77 speed: CodexSpeed,
78 sawThreadSettings: Schema.Boolean,
79 usage: CodexTokenUsage,
80});
81type CodexUnreportedRequest = typeof CodexUnreportedRequest.Type;
82type CodexRequestAttribution = Omit<CodexUnreportedRequest, "usage">;
83
84// An interrupted turn can end before a snapshot reports its last request. Bill those requests only
85// when the `token_usage_record`s since the previous snapshot explain the whole gap; `last` is the
86// final one.
87function unreportedRequests(
88 previous: CodexTokenUsage | null,
89 cumulative: CodexTokenUsage,
90 last: CodexTokenUsage,
91 pending: readonly CodexUnreportedRequest[] | undefined,
92) {
93 if (
94 previous === null ||
95 pending === undefined ||
96 CODEX_USAGE_FIELDS.some(
97 (key) =>
98 cumulative[key] - previous[key] !==
99 pending.reduce((sum, request) => sum + request.usage[key], 0),
100 )
101 ) {
102 return null;
103 }
104 const final = pending.at(-1)!;
105 const remainder = readCodexTokenUsage(
106 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, final.usage[key] - last[key]])),
107 );
108 if (remainder === null) return null;
109 return [...pending.slice(0, -1), { ...final, usage: remainder }].filter(
110 (request) => request.usage.input_tokens + request.usage.output_tokens > 0,
111 );
112}
113
114/**
115 * Codex `token_count` events carry no model or service tier, so both are carried forward: the model
116 * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`.
117 */
118export const CodexScanState = Schema.Struct({
119 model: Schema.mutableKey(Schema.String),
120 speed: Schema.mutableKey(CodexSpeed),
121 sessionId: Schema.mutableKey(Schema.String),
122 lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
123 lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)),
124 // Optional so scan states cached before this field existed stay valid.
125 sequenceStartSignature: Schema.mutableKey(Schema.optionalKey(Schema.String)),
126 // `token_usage_record` usage since the last cumulative snapshot, one entry per record.
127 unreportedRequests: Schema.mutableKey(
128 Schema.optionalKey(Schema.mutable(Schema.Array(CodexUnreportedRequest))),
129 ),
130 malformedRecords: Schema.mutableKey(TokenCount),
131 sawSessionMeta: Schema.mutableKey(Schema.Boolean),
132 modelProvider: Schema.mutableKey(Schema.String),
133 turnId: Schema.mutableKey(Schema.String),
134 sawThreadSettings: Schema.mutableKey(Schema.Boolean),
135 suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
136 forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
137});
138export type CodexScanState = typeof CodexScanState.Type;
139
140export function initialCodexScanState(): CodexScanState {
141 return {
142 model: "",
143 speed: "standard",
144 sessionId: "",
145 lastUsageSignature: null,
146 lastCumulativeUsage: null,
147 malformedRecords: 0,
148 sawSessionMeta: false,
149 modelProvider: "",
150 turnId: "",
151 sawThreadSettings: false,
152 suppressingForkCopies: false,
153 forkCopyAnchorMs: 0,
154 };
155}
156
157/** Forks copy and restamp parent history in a burst (0-40ms gaps); genuine child usage follows a model turn (5s+ observed). */
158const FORK_COPY_MAX_GAP_MS = 1000;
159
160function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
161 if (typeof payload["forked_from_id"] === "string") return true;
162 const source = payload["source"];
163 if (typeof source !== "object" || source === null) return false;
164 const subagent = (source as Record<string, unknown>)["subagent"];
165 if (typeof subagent !== "object" || subagent === null) return false;
166 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
167 if (typeof spawn !== "object" || spawn === null) return false;
168 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
169}
170
171// The first usage line past the copied burst ends suppression for the rest of the rollout.
172function isForkCopy(state: CodexScanState, timestampMs: number): boolean {
173 if (!state.suppressingForkCopies) return false;
174 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
175 state.forkCopyAnchorMs = timestampMs;
176 return true;
177 }
178 state.suppressingForkCopies = false;
179 state.lastUsageSignature = null;
180 return false;
181}
182
183/**
184 * Cumulative counters validate request deltas. Older events without cumulative counters use
185 * normalized consecutive-request deduplication.
186 */
187export function parseCodexLine(line: string, state: CodexScanState): readonly UsageRecord[] {
188 let parsed: unknown;
189 try {
190 parsed = JSON.parse(line);
191 } catch {
192 return [];
193 }
194 return parseCodexRecord(parsed, state);
195}
196
197function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly UsageRecord[] {
198 if (typeof parsed !== "object" || parsed === null) return [];
199
200 const record = parsed as Record<string, unknown>;
201 const payload = record["payload"];
202 if (typeof payload !== "object" || payload === null) return [];
203 const payloadRecord = payload as Record<string, unknown>;
204 const payloadType = payloadRecord["type"];
205
206 if (record["type"] === "session_meta") {
207 // Only the first meta identifies this session; copied ancestor metas would misattribute later records.
208 if (state.sawSessionMeta) return [];
209 state.sawSessionMeta = true;
210 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
211 if (typeof id === "string") state.sessionId = id;
212 if (typeof payloadRecord["model_provider"] === "string") {
213 state.modelProvider = payloadRecord["model_provider"];
214 }
215 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
216 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
217 state.suppressingForkCopies = true;
218 state.forkCopyAnchorMs = metaTimestampMs;
219 }
220 return [];
221 }
222
223 if (record["type"] === "turn_context") {
224 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
225 // Model carry is useful for usage, but history recovery needs this context's own identity.
226 state.turnId =
227 typeof payloadRecord["turn_id"] === "string" &&
228 typeof payloadRecord["model"] === "string" &&
229 payloadRecord["model"].length > 0
230 ? payloadRecord["turn_id"]
231 : "";
232 return [];
233 }
234
235 // Several of these may sit between two snapshots, so they only explain a gap in the counters.
236 if (record["type"] === "token_usage_record") {
237 const timestampMs = parseTimestampMs(record["timestamp"]);
238 const usage = readCodexTokenUsage(payloadRecord["usage"]);
239 if (timestampMs === null || usage === null || state.model.length === 0) return [];
240 // Copied history is already billed in the parent.
241 if (isForkCopy(state, timestampMs)) return [];
242 (state.unreportedRequests ??= []).push({ ...codexAttribution(state, timestampMs), usage });
243 return [];
244 }
245
246 if (payloadType === "thread_settings_applied") {
247 state.sawThreadSettings = true;
248 const settings = payloadRecord["thread_settings"];
249 if (typeof settings === "object" && settings !== null) {
250 state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
251 }
252 return [];
253 }
254
255 if (payloadType !== "token_count") return [];
256
257 const info = payloadRecord["info"];
258 if (typeof info !== "object" || info === null) return [];
259 const infoRecord = info as Record<string, unknown>;
260
261 // Codex may re-emit these counters after the model or timestamp becomes available.
262 const timestampMs = parseTimestampMs(record["timestamp"]);
263 if (timestampMs === null || state.model.length === 0) return [];
264
265 const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
266 const rawCumulative = infoRecord["total_token_usage"];
267 const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
268 const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
269
270 if (isForkCopy(state, timestampMs)) {
271 // Copied history is already billed in the parent, but establishes the child's baseline.
272 const signature = last === null ? null : JSON.stringify(last);
273 if (cumulative !== null) rebaseCodexUsage(state, cumulative);
274 else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
275 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
276 }
277 state.lastUsageSignature = signature;
278 return [];
279 }
280
281 const previous = state.lastCumulativeUsage;
282 const pending = state.unreportedRequests;
283 // A valid snapshot remains the next baseline even when its paired request is malformed.
284 if (cumulative !== null) rebaseCodexUsage(state, cumulative);
285 if (last === null || (hasCumulative && cumulative === null)) {
286 state.malformedRecords += 1;
287 return [];
288 }
289
290 // Zero-component counters report context size, not a request: fill_to_context_window, or the
291 // post-compaction marker whose total is the new context size (its cumulative may reset to zero).
292 if (last.input_tokens + last.output_tokens === 0) {
293 state.lastUsageSignature = null;
294 return [];
295 }
296
297 if (
298 cumulative !== null &&
299 previous !== null &&
300 CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
301 ) {
302 return [];
303 }
304
305 if (last.total_tokens !== last.input_tokens + last.output_tokens) {
306 state.malformedRecords += 1;
307 return [];
308 }
309
310 const signature = JSON.stringify(last);
311 let unreported: readonly CodexUnreportedRequest[] = [];
312 if (cumulative !== null) {
313 // A session resumed in a new Codex process restarts its cumulative counters at this request.
314 const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]);
315 const sequenceStart = JSON.stringify([timestampMs, last]);
316 // Only the same event is a replay; a later request can restart with identical counters.
317 if (restarted && sequenceStart === state.sequenceStartSignature) {
318 state.lastCumulativeUsage = previous;
319 return [];
320 }
321 // Forks and paginated continuations can inherit totals without copying a counter snapshot.
322 // Only bill the latest request, and require the unseen prefix to be valid usage too.
323 const reconciled =
324 previous === null
325 ? readCodexTokenUsage(
326 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, cumulative[key] - last[key]])),
327 ) !== null
328 : CODEX_USAGE_FIELDS.every((key) => cumulative[key] - previous[key] === last[key]);
329 if (!restarted && !reconciled) {
330 const bridged = unreportedRequests(previous, cumulative, last, pending);
331 if (bridged === null) {
332 state.malformedRecords += 1;
333 return [];
334 }
335 unreported = bridged;
336 }
337 if (restarted) state.sequenceStartSignature = sequenceStart;
338 } else {
339 if (signature === state.lastUsageSignature) return [];
340 // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
341 const advanced = advanceCodexUsage(previous, last);
342 if (advanced === null) {
343 state.malformedRecords += 1;
344 return [];
345 }
346 state.lastCumulativeUsage = advanced;
347 }
348 state.lastUsageSignature = signature;
349
350 return [
351 ...unreported.map((request) => codexRequestRecord(state, request.usage, request)),
352 codexRequestRecord(state, last, codexAttribution(state, timestampMs)),
353 ];
354}
355
356function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution {
357 return {
358 timestampMs,
359 model: state.model,
360 turnId: state.turnId,
361 speed: state.speed,
362 sawThreadSettings: state.sawThreadSettings,
363 };
364}
365
366function codexRequestRecord(
367 state: CodexScanState,
368 usage: CodexTokenUsage,
369 { timestampMs, model, turnId, speed, sawThreadSettings }: CodexRequestAttribution,
370): UsageRecord {
371 const inputTokens = usage.input_tokens;
372 const cachedInputTokens = usage.cached_input_tokens;
373 const cacheCreationTokens = usage.cache_write_input_tokens;
374 const outputTokens = usage.output_tokens;
375
376 const totals: UsageTokenTotals = {
377 // Codex reports `input_tokens` inclusive of the cached portion.
378 uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
379 cachedInputTokens,
380 cacheCreationTokens,
381 outputTokens,
382 // Reported inside output_tokens, surfaced separately for the token mix.
383 reasoningTokens: usage.reasoning_output_tokens,
384 };
385
386 return {
387 provider: "codex",
388 timestampMs,
389 model,
390 sessionId: state.sessionId,
391 totals,
392 reportedCostUsd: null,
393 speed,
394 ...(!sawThreadSettings &&
395 state.modelProvider === "openai" &&
396 state.sessionId.length > 0 &&
397 turnId.length > 0
398 ? { unresolvedServiceTierTurnId: turnId }
399 : {}),
400 dedupeKey: null,
401 };
402}
403
404/** Missing, default and standard tiers bill as standard; fast aliases priority. */
405function codexSpeed(serviceTier: unknown): UsageSpeed {
406 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
407 if (serviceTier === "ultrafast") return "ultrafast";
408 return "standard";
409}
410
411export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
412 selectFields: {
413 type: true,
414 timestamp: true,
415 payload: {
416 type: true,
417 id: true,
418 session_id: true,
419 model_provider: true,
420 turn_id: true,
421 model: true,
422 thread_settings: { service_tier: true },
423 forked_from_id: true,
424 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
425 info: { last_token_usage: true, total_token_usage: true },
426 usage: true,
427 },
428 },
429 // Metadata lines carry model, tier and session even without usage.
430 usageMarkers: [
431 '"token_count"',
432 '"token_usage_record"',
433 '"turn_context"',
434 '"thread_settings_applied"',
435 '"session_meta"',
436 ],
437 parseLine: parseCodexLine,
438 parseProjected: parseCodexRecord,
439 state: { initial: initialCodexScanState, schema: CodexScanState },
440 readMalformedRecords: (state) => state.malformedRecords,
441 // A rollout that moved after it was read leaves a copy in both places.
442 sharedSessionsAcrossFiles: true,
443};
444
445export const codexUsageReader: ProviderUsageReader<
446 CodexSettings,
447 Path.Path | CodexUsageHistory.CodexUsageHistory
448> = {
449 kind: "transcripts",
450 provider: "codex",
451 format: codexUsageFormat,
452 resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) {
453 const history = yield* CodexUsageHistory.CodexUsageHistory;
454 const requests = new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageRecord>();
455 for (const record of records) {
456 if (record.unresolvedServiceTierTurnId === undefined) continue;
457 requests.set(
458 {
459 sessionId: record.sessionId,
460 nativeTurnId: record.unresolvedServiceTierTurnId,
461 model: record.model,
462 },
463 record,
464 );
465 }
466 const resolved = yield* history.resolve([...requests.keys()]).pipe(
467 Effect.catchTags({
468 CodexUsageHistoryReadError: () =>
469 Effect.succeed(new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageSpeed>()),
470 }),
471 );
472 const speeds = new Map<UsageRecord, UsageSpeed>();
473 for (const [request, speed] of resolved) {
474 const record = requests.get(request);
475 if (record !== undefined) speeds.set(record, speed);
476 }
477 return speeds;
478 }),
479 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
480 if (config === undefined) return [];
481 const path = yield* Path.Path;
482 const environmentHome = environment.CODEX_HOME?.trim();
483 const layout = yield* resolveCodexHomeLayout(
484 config.setupMode !== "managed" &&
485 !config.homePath.trim() &&
486 !config.shadowHomePath.trim() &&
487 environmentHome
488 ? { ...config, homePath: environmentHome }
489 : config,
490 );
491 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
492 }),
493};