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