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 totalTokens,
9 type ProviderUsageReader,
10 type TranscriptUsageFormat,
11 type UsageRecord,
12 type UsageSpeed,
13} from "@t3tools/provider-core/server/usage";
14import type { UsageTokenTotals } from "@t3tools/contracts";
15
16import * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts";
17import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts";
18
19const TokenCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
20const CodexTokenUsage = Schema.Struct({
21 input_tokens: TokenCount,
22 cached_input_tokens: TokenCount,
23 cache_write_input_tokens: TokenCount,
24 output_tokens: TokenCount,
25 reasoning_output_tokens: TokenCount,
26 total_tokens: TokenCount,
27}).check(
28 Schema.makeFilter(
29 (usage) =>
30 usage.cached_input_tokens + usage.cache_write_input_tokens <= usage.input_tokens &&
31 usage.reasoning_output_tokens <= usage.output_tokens &&
32 usage.total_tokens >= usage.input_tokens + usage.output_tokens,
33 ),
34);
35type CodexTokenUsage = typeof CodexTokenUsage.Type;
36const isCodexTokenUsage = Schema.is(CodexTokenUsage);
37const CODEX_USAGE_FIELDS = Object.keys(CodexTokenUsage.fields) as (keyof CodexTokenUsage)[];
38
39function readCodexTokenUsage(value: unknown): CodexTokenUsage | null {
40 if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
41 const raw = value as Record<string, unknown>;
42 const input = raw["input_tokens"];
43 const output = raw["output_tokens"];
44 if (typeof input !== "number" || typeof output !== "number") return null;
45 const usage = {
46 input_tokens: input,
47 cached_input_tokens: raw["cached_input_tokens"] === undefined ? 0 : raw["cached_input_tokens"],
48 cache_write_input_tokens:
49 raw["cache_write_input_tokens"] === undefined ? 0 : raw["cache_write_input_tokens"],
50 output_tokens: output,
51 reasoning_output_tokens:
52 raw["reasoning_output_tokens"] === undefined ? 0 : raw["reasoning_output_tokens"],
53 total_tokens: raw["total_tokens"] === undefined ? input + output : raw["total_tokens"],
54 };
55 return isCodexTokenUsage(usage) ? usage : null;
56}
57
58function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsage) {
59 return readCodexTokenUsage(
60 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, (previous?.[key] ?? 0) + last[key]])),
61 );
62}
63
64/**
65 * Codex `token_count` events carry no model or service tier, so both are carried forward: the model
66 * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`.
67 */
68export const CodexScanState = Schema.Struct({
69 model: Schema.mutableKey(Schema.String),
70 speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])),
71 sessionId: Schema.mutableKey(Schema.String),
72 lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
73 lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)),
74 malformedRecords: Schema.mutableKey(TokenCount),
75 sawSessionMeta: Schema.mutableKey(Schema.Boolean),
76 modelProvider: Schema.mutableKey(Schema.String),
77 turnId: Schema.mutableKey(Schema.String),
78 sawThreadSettings: Schema.mutableKey(Schema.Boolean),
79 suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
80 forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
81});
82export type CodexScanState = typeof CodexScanState.Type;
83
84export function initialCodexScanState(): CodexScanState {
85 return {
86 model: "",
87 speed: "standard",
88 sessionId: "",
89 lastUsageSignature: null,
90 lastCumulativeUsage: null,
91 malformedRecords: 0,
92 sawSessionMeta: false,
93 modelProvider: "",
94 turnId: "",
95 sawThreadSettings: false,
96 suppressingForkCopies: false,
97 forkCopyAnchorMs: 0,
98 };
99}
100
101/**
102 * A forked or subagent rollout opens with the parent's full history copied in,
103 * every line re-stamped to the fork instant. Those copies are written in one
104 * synchronous burst (observed gaps 0-40ms), while the child's first genuine
105 * usage event only lands after a real model turn (observed 5s+).
106 */
107const FORK_COPY_MAX_GAP_MS = 1000;
108
109function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
110 if (typeof payload["forked_from_id"] === "string") return true;
111 const source = payload["source"];
112 if (typeof source !== "object" || source === null) return false;
113 const subagent = (source as Record<string, unknown>)["subagent"];
114 if (typeof subagent !== "object" || subagent === null) return false;
115 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
116 if (typeof spawn !== "object" || spawn === null) return false;
117 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
118}
119
120/**
121 * Cumulative counters validate request deltas. Older events without cumulative counters use
122 * normalized consecutive-request deduplication.
123 */
124export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
125 let parsed: unknown;
126 try {
127 parsed = JSON.parse(line);
128 } catch {
129 return null;
130 }
131 return parseCodexRecord(parsed, state);
132}
133
134function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null {
135 if (typeof parsed !== "object" || parsed === null) return null;
136
137 const record = parsed as Record<string, unknown>;
138 const payload = record["payload"];
139 if (typeof payload !== "object" || payload === null) return null;
140 const payloadRecord = payload as Record<string, unknown>;
141 const payloadType = payloadRecord["type"];
142
143 if (record["type"] === "session_meta") {
144 // Only the first meta describes this file's own session. A forked rollout
145 // repeats the ancestors' metas right after it; letting those through would
146 // reassign every subsequent record to an ancestor session.
147 if (state.sawSessionMeta) return null;
148 state.sawSessionMeta = true;
149 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
150 if (typeof id === "string") state.sessionId = id;
151 if (typeof payloadRecord["model_provider"] === "string") {
152 state.modelProvider = payloadRecord["model_provider"];
153 }
154 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
155 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
156 state.suppressingForkCopies = true;
157 state.forkCopyAnchorMs = metaTimestampMs;
158 }
159 return null;
160 }
161
162 if (record["type"] === "turn_context") {
163 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
164 // Model carry is useful for usage, but history recovery needs this context's own identity.
165 state.turnId =
166 typeof payloadRecord["turn_id"] === "string" &&
167 typeof payloadRecord["model"] === "string" &&
168 payloadRecord["model"].length > 0
169 ? payloadRecord["turn_id"]
170 : "";
171 return null;
172 }
173
174 if (payloadType === "thread_settings_applied") {
175 state.sawThreadSettings = true;
176 const settings = payloadRecord["thread_settings"];
177 if (typeof settings === "object" && settings !== null) {
178 state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
179 }
180 return null;
181 }
182
183 if (payloadType !== "token_count") return null;
184
185 const info = payloadRecord["info"];
186 if (typeof info !== "object" || info === null) return null;
187 const infoRecord = info as Record<string, unknown>;
188
189 // Codex may re-emit these counters after the model or timestamp becomes available.
190 const timestampMs = parseTimestampMs(record["timestamp"]);
191 if (timestampMs === null || state.model.length === 0) return null;
192
193 const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
194 const rawCumulative = infoRecord["total_token_usage"];
195 const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
196 const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
197
198 if (state.suppressingForkCopies) {
199 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
200 state.forkCopyAnchorMs = timestampMs;
201 // Copied history is already billed in the parent, but establishes the child's baseline.
202 const signature = last === null ? null : JSON.stringify(last);
203 if (cumulative !== null) state.lastCumulativeUsage = cumulative;
204 else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
205 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
206 }
207 state.lastUsageSignature = signature;
208 return null;
209 }
210 state.suppressingForkCopies = false;
211 state.lastUsageSignature = null;
212 }
213
214 const previous = state.lastCumulativeUsage;
215 // A valid snapshot remains the next baseline even when its paired request is malformed.
216 if (cumulative !== null) state.lastCumulativeUsage = cumulative;
217 if (last === null || (hasCumulative && cumulative === null)) {
218 state.malformedRecords += 1;
219 return null;
220 }
221
222 // Zero-component counters report context size, not a request: fill_to_context_window, or the
223 // post-compaction marker whose total is the new context size (its cumulative may reset to zero).
224 if (last.input_tokens + last.output_tokens === 0) {
225 state.lastUsageSignature = null;
226 return null;
227 }
228
229 if (
230 cumulative !== null &&
231 previous !== null &&
232 CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
233 ) {
234 return null;
235 }
236
237 if (last.total_tokens !== last.input_tokens + last.output_tokens) {
238 state.malformedRecords += 1;
239 return null;
240 }
241
242 const signature = JSON.stringify(last);
243 if (cumulative !== null) {
244 // A session resumed in a new Codex process restarts its cumulative counters at this request.
245 const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]);
246 if (
247 !restarted &&
248 !CODEX_USAGE_FIELDS.every((key) => cumulative[key] - (previous?.[key] ?? 0) === last[key])
249 ) {
250 state.malformedRecords += 1;
251 return null;
252 }
253 } else {
254 if (signature === state.lastUsageSignature) return null;
255 // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
256 const advanced = advanceCodexUsage(previous, last);
257 if (advanced === null) {
258 state.malformedRecords += 1;
259 return null;
260 }
261 state.lastCumulativeUsage = advanced;
262 }
263 state.lastUsageSignature = signature;
264
265 const inputTokens = last.input_tokens;
266 const cachedInputTokens = last.cached_input_tokens;
267 const cacheCreationTokens = last.cache_write_input_tokens;
268 const outputTokens = last.output_tokens;
269
270 const totals: UsageTokenTotals = {
271 // Codex reports `input_tokens` inclusive of the cached portion.
272 uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
273 cachedInputTokens,
274 cacheCreationTokens,
275 outputTokens,
276 // Reported inside output_tokens, surfaced separately for the token mix.
277 reasoningTokens: last.reasoning_output_tokens,
278 };
279
280 if (totalTokens(totals) === 0) return null;
281
282 return {
283 provider: "codex",
284 timestampMs,
285 model: state.model,
286 sessionId: state.sessionId,
287 totals,
288 reportedCostUsd: null,
289 speed: state.speed,
290 ...(!state.sawThreadSettings &&
291 state.modelProvider === "openai" &&
292 state.sessionId.length > 0 &&
293 state.turnId.length > 0
294 ? { unresolvedServiceTierTurnId: state.turnId }
295 : {}),
296 dedupeKey: null,
297 };
298}
299
300/**
301 * Codex omits the field when no tier was requested, which bills as standard, as
302 * do `default` and `standard`. `fast` is accepted as an alias of `priority`.
303 */
304function codexSpeed(serviceTier: unknown): UsageSpeed {
305 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
306 if (serviceTier === "ultrafast") return "ultrafast";
307 return "standard";
308}
309
310const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
311 record === null ? [] : [record];
312
313export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
314 selectFields: {
315 type: true,
316 timestamp: true,
317 payload: {
318 type: true,
319 id: true,
320 session_id: true,
321 model_provider: true,
322 turn_id: true,
323 model: true,
324 thread_settings: { service_tier: true },
325 forked_from_id: true,
326 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
327 info: { last_token_usage: true, total_token_usage: true },
328 },
329 },
330 // `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
331 // usage, but they carry the model, tier and session the reducer needs.
332 usageMarkers: ['"token_count"', '"turn_context"', '"thread_settings_applied"', '"session_meta"'],
333 parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
334 parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
335 state: { initial: initialCodexScanState, schema: CodexScanState },
336 readMalformedRecords: (state) => state.malformedRecords,
337 // A rollout that moved after it was read leaves a copy in both places.
338 sharedSessionsAcrossFiles: true,
339};
340
341export const codexUsageReader: ProviderUsageReader<
342 CodexSettings,
343 Path.Path | CodexUsageHistory.CodexUsageHistory
344> = {
345 kind: "transcripts",
346 provider: "codex",
347 format: codexUsageFormat,
348 resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) {
349 const history = yield* CodexUsageHistory.CodexUsageHistory;
350 const requests = new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageRecord>();
351 for (const record of records) {
352 if (record.unresolvedServiceTierTurnId === undefined) continue;
353 requests.set(
354 {
355 sessionId: record.sessionId,
356 nativeTurnId: record.unresolvedServiceTierTurnId,
357 model: record.model,
358 },
359 record,
360 );
361 }
362 const resolved = yield* history.resolve([...requests.keys()]).pipe(
363 Effect.catchTags({
364 CodexUsageHistoryReadError: () =>
365 Effect.succeed(new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageSpeed>()),
366 }),
367 );
368 const speeds = new Map<UsageRecord, UsageSpeed>();
369 for (const [request, speed] of resolved) {
370 const record = requests.get(request);
371 if (record !== undefined) speeds.set(record, speed);
372 }
373 return speeds;
374 }),
375 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
376 if (config === undefined) return [];
377 const path = yield* Path.Path;
378 const environmentHome = environment.CODEX_HOME?.trim();
379 const layout = yield* resolveCodexHomeLayout(
380 config.setupMode !== "managed" &&
381 !config.homePath.trim() &&
382 !config.shadowHomePath.trim() &&
383 environmentHome
384 ? { ...config, homePath: environmentHome }
385 : config,
386 );
387 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
388 }),
389};