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 // fill_to_context_window uses zero components and synthetic totals, then offsets future totals.
223 if (
224 cumulative !== null &&
225 last.input_tokens + last.output_tokens === 0 &&
226 cumulative.input_tokens + cumulative.output_tokens === 0 &&
227 cumulative.total_tokens === infoRecord["model_context_window"]
228 ) {
229 state.lastUsageSignature = null;
230 return null;
231 }
232
233 if (
234 cumulative !== null &&
235 previous !== null &&
236 CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
237 ) {
238 return null;
239 }
240
241 if (last.total_tokens !== last.input_tokens + last.output_tokens) {
242 state.malformedRecords += 1;
243 return null;
244 }
245
246 const signature = JSON.stringify(last);
247 if (cumulative !== null) {
248 if (
249 !CODEX_USAGE_FIELDS.every((key) => cumulative[key] - (previous?.[key] ?? 0) === last[key])
250 ) {
251 state.malformedRecords += 1;
252 return null;
253 }
254 } else {
255 if (signature === state.lastUsageSignature) return null;
256 // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
257 const advanced = advanceCodexUsage(previous, last);
258 if (advanced === null) {
259 state.malformedRecords += 1;
260 return null;
261 }
262 state.lastCumulativeUsage = advanced;
263 }
264 state.lastUsageSignature = signature;
265
266 const inputTokens = last.input_tokens;
267 const cachedInputTokens = last.cached_input_tokens;
268 const cacheCreationTokens = last.cache_write_input_tokens;
269 const outputTokens = last.output_tokens;
270
271 const totals: UsageTokenTotals = {
272 // Codex reports `input_tokens` inclusive of the cached portion.
273 uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
274 cachedInputTokens,
275 cacheCreationTokens,
276 outputTokens,
277 // Reported inside output_tokens, surfaced separately for the token mix.
278 reasoningTokens: last.reasoning_output_tokens,
279 };
280
281 if (totalTokens(totals) === 0) return null;
282
283 return {
284 provider: "codex",
285 timestampMs,
286 model: state.model,
287 sessionId: state.sessionId,
288 totals,
289 reportedCostUsd: null,
290 speed: state.speed,
291 ...(!state.sawThreadSettings &&
292 state.modelProvider === "openai" &&
293 state.sessionId.length > 0 &&
294 state.turnId.length > 0
295 ? { unresolvedServiceTierTurnId: state.turnId }
296 : {}),
297 dedupeKey: null,
298 };
299}
300
301/**
302 * Codex omits the field when no tier was requested, which bills as standard, as
303 * do `default` and `standard`. `fast` is accepted as an alias of `priority`.
304 */
305function codexSpeed(serviceTier: unknown): UsageSpeed {
306 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
307 if (serviceTier === "ultrafast") return "ultrafast";
308 return "standard";
309}
310
311const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
312 record === null ? [] : [record];
313
314export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
315 selectFields: {
316 type: true,
317 timestamp: true,
318 payload: {
319 type: true,
320 id: true,
321 session_id: true,
322 model_provider: true,
323 turn_id: true,
324 model: true,
325 thread_settings: { service_tier: true },
326 forked_from_id: true,
327 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
328 info: { last_token_usage: true, total_token_usage: true, model_context_window: true },
329 },
330 },
331 // `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
332 // usage, but they carry the model, tier and session the reducer needs.
333 usageMarkers: ['"token_count"', '"turn_context"', '"thread_settings_applied"', '"session_meta"'],
334 parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
335 parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
336 state: { initial: initialCodexScanState, schema: CodexScanState },
337 readMalformedRecords: (state) => state.malformedRecords,
338 // A rollout that moved after it was read leaves a copy in both places.
339 sharedSessionsAcrossFiles: true,
340};
341
342export const codexUsageReader: ProviderUsageReader<
343 CodexSettings,
344 Path.Path | CodexUsageHistory.CodexUsageHistory
345> = {
346 kind: "transcripts",
347 provider: "codex",
348 format: codexUsageFormat,
349 resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) {
350 const history = yield* CodexUsageHistory.CodexUsageHistory;
351 const requests = new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageRecord>();
352 for (const record of records) {
353 if (record.unresolvedServiceTierTurnId === undefined) continue;
354 requests.set(
355 {
356 sessionId: record.sessionId,
357 nativeTurnId: record.unresolvedServiceTierTurnId,
358 model: record.model,
359 },
360 record,
361 );
362 }
363 const resolved = yield* history.resolve([...requests.keys()]).pipe(
364 Effect.catchTags({
365 CodexUsageHistoryReadError: () =>
366 Effect.succeed(new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageSpeed>()),
367 }),
368 );
369 const speeds = new Map<UsageRecord, UsageSpeed>();
370 for (const [request, speed] of resolved) {
371 const record = requests.get(request);
372 if (record !== undefined) speeds.set(record, speed);
373 }
374 return speeds;
375 }),
376 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
377 if (config === undefined) return [];
378 const path = yield* Path.Path;
379 const environmentHome = environment.CODEX_HOME?.trim();
380 const layout = yield* resolveCodexHomeLayout(
381 config.setupMode !== "managed" &&
382 !config.homePath.trim() &&
383 !config.shadowHomePath.trim() &&
384 environmentHome
385 ? { ...config, homePath: environmentHome }
386 : config,
387 );
388 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
389 }),
390};