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/** Forks copy and restamp parent history in a burst (0-40ms gaps); genuine child usage follows a model turn (5s+ observed). */
102const FORK_COPY_MAX_GAP_MS = 1000;
103
104function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
105 if (typeof payload["forked_from_id"] === "string") return true;
106 const source = payload["source"];
107 if (typeof source !== "object" || source === null) return false;
108 const subagent = (source as Record<string, unknown>)["subagent"];
109 if (typeof subagent !== "object" || subagent === null) return false;
110 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
111 if (typeof spawn !== "object" || spawn === null) return false;
112 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
113}
114
115/**
116 * Cumulative counters validate request deltas. Older events without cumulative counters use
117 * normalized consecutive-request deduplication.
118 */
119export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
120 let parsed: unknown;
121 try {
122 parsed = JSON.parse(line);
123 } catch {
124 return null;
125 }
126 return parseCodexRecord(parsed, state);
127}
128
129function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null {
130 if (typeof parsed !== "object" || parsed === null) return null;
131
132 const record = parsed as Record<string, unknown>;
133 const payload = record["payload"];
134 if (typeof payload !== "object" || payload === null) return null;
135 const payloadRecord = payload as Record<string, unknown>;
136 const payloadType = payloadRecord["type"];
137
138 if (record["type"] === "session_meta") {
139 // Only the first meta identifies this session; copied ancestor metas would misattribute later records.
140 if (state.sawSessionMeta) return null;
141 state.sawSessionMeta = true;
142 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
143 if (typeof id === "string") state.sessionId = id;
144 if (typeof payloadRecord["model_provider"] === "string") {
145 state.modelProvider = payloadRecord["model_provider"];
146 }
147 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
148 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
149 state.suppressingForkCopies = true;
150 state.forkCopyAnchorMs = metaTimestampMs;
151 }
152 return null;
153 }
154
155 if (record["type"] === "turn_context") {
156 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
157 // Model carry is useful for usage, but history recovery needs this context's own identity.
158 state.turnId =
159 typeof payloadRecord["turn_id"] === "string" &&
160 typeof payloadRecord["model"] === "string" &&
161 payloadRecord["model"].length > 0
162 ? payloadRecord["turn_id"]
163 : "";
164 return null;
165 }
166
167 if (payloadType === "thread_settings_applied") {
168 state.sawThreadSettings = true;
169 const settings = payloadRecord["thread_settings"];
170 if (typeof settings === "object" && settings !== null) {
171 state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
172 }
173 return null;
174 }
175
176 if (payloadType !== "token_count") return null;
177
178 const info = payloadRecord["info"];
179 if (typeof info !== "object" || info === null) return null;
180 const infoRecord = info as Record<string, unknown>;
181
182 // Codex may re-emit these counters after the model or timestamp becomes available.
183 const timestampMs = parseTimestampMs(record["timestamp"]);
184 if (timestampMs === null || state.model.length === 0) return null;
185
186 const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
187 const rawCumulative = infoRecord["total_token_usage"];
188 const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
189 const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
190
191 if (state.suppressingForkCopies) {
192 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
193 state.forkCopyAnchorMs = timestampMs;
194 // Copied history is already billed in the parent, but establishes the child's baseline.
195 const signature = last === null ? null : JSON.stringify(last);
196 if (cumulative !== null) state.lastCumulativeUsage = cumulative;
197 else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
198 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
199 }
200 state.lastUsageSignature = signature;
201 return null;
202 }
203 state.suppressingForkCopies = false;
204 state.lastUsageSignature = null;
205 }
206
207 const previous = state.lastCumulativeUsage;
208 // A valid snapshot remains the next baseline even when its paired request is malformed.
209 if (cumulative !== null) state.lastCumulativeUsage = cumulative;
210 if (last === null || (hasCumulative && cumulative === null)) {
211 state.malformedRecords += 1;
212 return null;
213 }
214
215 // Zero-component counters report context size, not a request: fill_to_context_window, or the
216 // post-compaction marker whose total is the new context size (its cumulative may reset to zero).
217 if (last.input_tokens + last.output_tokens === 0) {
218 state.lastUsageSignature = null;
219 return null;
220 }
221
222 if (
223 cumulative !== null &&
224 previous !== null &&
225 CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
226 ) {
227 return null;
228 }
229
230 if (last.total_tokens !== last.input_tokens + last.output_tokens) {
231 state.malformedRecords += 1;
232 return null;
233 }
234
235 const signature = JSON.stringify(last);
236 if (cumulative !== null) {
237 // A session resumed in a new Codex process restarts its cumulative counters at this request.
238 const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]);
239 // Forks and paginated continuations can inherit totals without copying a counter snapshot.
240 // Only bill the latest request, and require the unseen prefix to be valid usage too.
241 const reconciled =
242 previous === null
243 ? readCodexTokenUsage(
244 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, cumulative[key] - last[key]])),
245 ) !== null
246 : CODEX_USAGE_FIELDS.every((key) => cumulative[key] - previous[key] === last[key]);
247 if (!restarted && !reconciled) {
248 state.malformedRecords += 1;
249 return null;
250 }
251 } else {
252 if (signature === state.lastUsageSignature) return null;
253 // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
254 const advanced = advanceCodexUsage(previous, last);
255 if (advanced === null) {
256 state.malformedRecords += 1;
257 return null;
258 }
259 state.lastCumulativeUsage = advanced;
260 }
261 state.lastUsageSignature = signature;
262
263 const inputTokens = last.input_tokens;
264 const cachedInputTokens = last.cached_input_tokens;
265 const cacheCreationTokens = last.cache_write_input_tokens;
266 const outputTokens = last.output_tokens;
267
268 const totals: UsageTokenTotals = {
269 // Codex reports `input_tokens` inclusive of the cached portion.
270 uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
271 cachedInputTokens,
272 cacheCreationTokens,
273 outputTokens,
274 // Reported inside output_tokens, surfaced separately for the token mix.
275 reasoningTokens: last.reasoning_output_tokens,
276 };
277
278 if (totalTokens(totals) === 0) return null;
279
280 return {
281 provider: "codex",
282 timestampMs,
283 model: state.model,
284 sessionId: state.sessionId,
285 totals,
286 reportedCostUsd: null,
287 speed: state.speed,
288 ...(!state.sawThreadSettings &&
289 state.modelProvider === "openai" &&
290 state.sessionId.length > 0 &&
291 state.turnId.length > 0
292 ? { unresolvedServiceTierTurnId: state.turnId }
293 : {}),
294 dedupeKey: null,
295 };
296}
297
298/** Missing, default and standard tiers bill as standard; fast aliases priority. */
299function codexSpeed(serviceTier: unknown): UsageSpeed {
300 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
301 if (serviceTier === "ultrafast") return "ultrafast";
302 return "standard";
303}
304
305const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
306 record === null ? [] : [record];
307
308export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
309 selectFields: {
310 type: true,
311 timestamp: true,
312 payload: {
313 type: true,
314 id: true,
315 session_id: true,
316 model_provider: true,
317 turn_id: true,
318 model: true,
319 thread_settings: { service_tier: true },
320 forked_from_id: true,
321 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
322 info: { last_token_usage: true, total_token_usage: true },
323 },
324 },
325 // Metadata lines carry model, tier and session even without usage.
326 usageMarkers: ['"token_count"', '"turn_context"', '"thread_settings_applied"', '"session_meta"'],
327 parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
328 parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
329 state: { initial: initialCodexScanState, schema: CodexScanState },
330 readMalformedRecords: (state) => state.malformedRecords,
331 // A rollout that moved after it was read leaves a copy in both places.
332 sharedSessionsAcrossFiles: true,
333};
334
335export const codexUsageReader: ProviderUsageReader<
336 CodexSettings,
337 Path.Path | CodexUsageHistory.CodexUsageHistory
338> = {
339 kind: "transcripts",
340 provider: "codex",
341 format: codexUsageFormat,
342 resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) {
343 const history = yield* CodexUsageHistory.CodexUsageHistory;
344 const requests = new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageRecord>();
345 for (const record of records) {
346 if (record.unresolvedServiceTierTurnId === undefined) continue;
347 requests.set(
348 {
349 sessionId: record.sessionId,
350 nativeTurnId: record.unresolvedServiceTierTurnId,
351 model: record.model,
352 },
353 record,
354 );
355 }
356 const resolved = yield* history.resolve([...requests.keys()]).pipe(
357 Effect.catchTags({
358 CodexUsageHistoryReadError: () =>
359 Effect.succeed(new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageSpeed>()),
360 }),
361 );
362 const speeds = new Map<UsageRecord, UsageSpeed>();
363 for (const [request, speed] of resolved) {
364 const record = requests.get(request);
365 if (record !== undefined) speeds.set(record, speed);
366 }
367 return speeds;
368 }),
369 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
370 if (config === undefined) return [];
371 const path = yield* Path.Path;
372 const environmentHome = environment.CODEX_HOME?.trim();
373 const layout = yield* resolveCodexHomeLayout(
374 config.setupMode !== "managed" &&
375 !config.homePath.trim() &&
376 !config.shadowHomePath.trim() &&
377 environmentHome
378 ? { ...config, homePath: environmentHome }
379 : config,
380 );
381 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
382 }),
383};