Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

codexUsage.ts

520 lines19.6 KB

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;
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;
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 );
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 );
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 requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)),
131 malformedRecords: Schema.mutableKey(TokenCount),
132 sawSessionMeta: Schema.mutableKey(Schema.Boolean),
133 modelProvider: Schema.mutableKey(Schema.String),
134 turnId: Schema.mutableKey(Schema.String),
135 sawThreadSettings: Schema.mutableKey(Schema.Boolean),
136 suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
137 forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
138});
139export type CodexScanState = typeof CodexScanState.Type;
140​
141export function initialCodexScanState(): CodexScanState {
142 return {
143 model: "",
144 speed: "standard",
145 sessionId: "",
146 lastUsageSignature: null,
147 lastCumulativeUsage: null,
148 malformedRecords: 0,
149 sawSessionMeta: false,
150 modelProvider: "",
151 turnId: "",
152 sawThreadSettings: false,
153 suppressingForkCopies: false,
154 forkCopyAnchorMs: 0,
155 };
157​
158/** Forks copy and restamp parent history in a burst (0-40ms gaps); genuine child usage follows a model turn (5s+ observed). */
159const FORK_COPY_MAX_GAP_MS = 1000;
160​
161function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
162 if (typeof payload["forked_from_id"] === "string") return true;
163 const source = payload["source"];
164 if (typeof source !== "object" || source === null) return false;
165 const subagent = (source as Record<string, unknown>)["subagent"];
166 if (typeof subagent !== "object" || subagent === null) return false;
167 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
168 if (typeof spawn !== "object" || spawn === null) return false;
169 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
171​
172// The first usage line past the copied burst ends suppression for the rest of the rollout.
173function isForkCopy(state: CodexScanState, timestampMs: number): boolean {
174 if (!state.suppressingForkCopies) return false;
175 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
176 state.forkCopyAnchorMs = timestampMs;
177 return true;
178 }
179 state.suppressingForkCopies = false;
180 state.lastUsageSignature = null;
181 return false;
183​
184/**
185 * Identified request-ledger entries report spending independently of context snapshots.
186 * Legacy snapshots validate request deltas against cumulative counters.
187 */
188export function parseCodexLine(line: string, state: CodexScanState): readonly UsageRecord[] {
189 let parsed: unknown;
190 try {
191 parsed = JSON.parse(line);
192 } catch {
193 return [];
194 }
195 return parseCodexRecord(parsed, state);
197​
198function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly UsageRecord[] {
199 if (typeof parsed !== "object" || parsed === null) return [];
200​
201 const record = parsed as Record<string, unknown>;
202 const payload = record["payload"];
203 if (typeof payload !== "object" || payload === null) return [];
204 const payloadRecord = payload as Record<string, unknown>;
205 const payloadType = payloadRecord["type"];
206​
207 if (record["type"] === "session_meta") {
208 // Only the first meta identifies this session; copied ancestor metas would misattribute later records.
209 if (state.sawSessionMeta) return [];
210 state.sawSessionMeta = true;
211 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
212 if (typeof id === "string") state.sessionId = id;
213 if (typeof payloadRecord["model_provider"] === "string") {
214 state.modelProvider = payloadRecord["model_provider"];
215 }
216 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
217 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
218 state.suppressingForkCopies = true;
219 state.forkCopyAnchorMs = metaTimestampMs;
220 }
221 return [];
222 }
223​
224 if (record["type"] === "turn_context") {
225 state.requestLedgerActive = false;
226 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
227 // Model carry is useful for usage, but history recovery needs this context's own identity.
228 state.turnId =
229 typeof payloadRecord["turn_id"] === "string" &&
230 typeof payloadRecord["model"] === "string" &&
231 payloadRecord["model"].length > 0
232 ? payloadRecord["turn_id"]
233 : "";
234 return [];
235 }
236​
237 // Request ledgers include spending that context snapshots can omit.
238 if (record["type"] === "token_usage_record") {
239 const timestampMs = parseTimestampMs(record["timestamp"]);
240 const usage = readCodexTokenUsage(payloadRecord["usage"]);
241 if (timestampMs === null || usage === null || state.model.length === 0) return [];
242 // Copied history is already billed in the parent.
243 if (isForkCopy(state, timestampMs)) return [];
244 const responseId = payloadRecord["response_id"];
245 if (typeof responseId === "string" && responseId.length > 0) {
246 const pending = state.unreportedRequests ?? [];
247 state.requestLedgerActive = true;
248 for (const request of pending) {
249 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, request.usage);
250 }
251 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, usage);
252 delete state.unreportedRequests;
253 return [
254 ...pending.map((request) => codexRequestRecord(state, request.usage, request)),
255 {
256 ...codexRequestRecord(state, usage, codexAttribution(state, timestampMs)),
257 dedupeKey: JSON.stringify(["codex", state.sessionId, responseId]),
258 },
259 ];
260 }
261 state.requestLedgerActive = false;
262 (state.unreportedRequests ??= []).push({ ...codexAttribution(state, timestampMs), usage });
263 return [];
264 }
265​
266 if (payloadType === "thread_settings_applied") {
267 state.sawThreadSettings = true;
268 const settings = payloadRecord["thread_settings"];
269 if (typeof settings === "object" && settings !== null) {
270 state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
271 }
272 return [];
273 }
274​
275 if (payloadType !== "token_count") return [];
276​
277 const info = payloadRecord["info"];
278 if (typeof info !== "object" || info === null) return [];
279 const infoRecord = info as Record<string, unknown>;
280​
281 // Codex may re-emit these counters after the model or timestamp becomes available.
282 const timestampMs = parseTimestampMs(record["timestamp"]);
283 if (timestampMs === null || state.model.length === 0) return [];
284​
285 const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
286 const rawCumulative = infoRecord["total_token_usage"];
287 const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
288 const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
289​
290 if (isForkCopy(state, timestampMs)) {
291 // Copied history is already billed in the parent, but establishes the child's baseline.
292 const signature = last === null ? null : JSON.stringify(last);
293 if (cumulative !== null) rebaseCodexUsage(state, cumulative);
294 else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
295 state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
296 }
297 state.lastUsageSignature = signature;
298 return [];
299 }
300​
301 // Context snapshots can rewind on resume and omit compaction spending; identified requests are authoritative.
302 if (state.requestLedgerActive) {
303 if (cumulative !== null) rebaseCodexUsage(state, cumulative);
304 return [];
305 }
306​
307 const previous = state.lastCumulativeUsage;
308 const pending = state.unreportedRequests;
309 // A valid snapshot remains the next baseline even when its paired request is malformed.
310 if (cumulative !== null) rebaseCodexUsage(state, cumulative);
311 if (last === null || (hasCumulative && cumulative === null)) {
312 state.malformedRecords += 1;
313 return [];
314 }
315​
316 // Zero-component counters report context size, not a request: fill_to_context_window, or the
317 // post-compaction marker whose total is the new context size (its cumulative may reset to zero).
318 if (last.input_tokens + last.output_tokens === 0) {
319 state.lastUsageSignature = null;
320 return [];
321 }
322​
323 if (
324 cumulative !== null &&
325 previous !== null &&
326 CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
327 ) {
328 return [];
329 }
330​
331 if (last.total_tokens !== last.input_tokens + last.output_tokens) {
332 state.malformedRecords += 1;
333 return [];
334 }
335​
336 const signature = JSON.stringify(last);
337 let unreported: readonly CodexUnreportedRequest[] = [];
338 if (cumulative !== null) {
339 // A session resumed in a new Codex process restarts its cumulative counters at this request.
340 const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]);
341 const sequenceStart = JSON.stringify([timestampMs, last]);
342 // Only the same event is a replay; a later request can restart with identical counters.
343 if (restarted && sequenceStart === state.sequenceStartSignature) {
344 state.lastCumulativeUsage = previous;
345 return [];
346 }
347 // Forks and paginated continuations can inherit totals without copying a counter snapshot.
348 // Only bill the latest request, and require the unseen prefix to be valid usage too.
349 const reconciled =
350 previous === null
351 ? readCodexTokenUsage(
352 Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, cumulative[key] - last[key]])),
353 ) !== null
354 : CODEX_USAGE_FIELDS.every((key) => cumulative[key] - previous[key] === last[key]);
355 if (!restarted && !reconciled) {
356 const bridged = unreportedRequests(previous, cumulative, last, pending);
357 if (bridged === null) {
358 state.malformedRecords += 1;
359 return [];
360 }
361 unreported = bridged;
362 }
363 if (restarted) state.sequenceStartSignature = sequenceStart;
364 } else {
365 if (signature === state.lastUsageSignature) return [];
366 // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
367 const advanced = advanceCodexUsage(previous, last);
368 if (advanced === null) {
369 state.malformedRecords += 1;
370 return [];
371 }
372 state.lastCumulativeUsage = advanced;
373 }
374 state.lastUsageSignature = signature;
375​
376 return [
377 ...unreported.map((request) => codexRequestRecord(state, request.usage, request)),
378 codexRequestRecord(state, last, codexAttribution(state, timestampMs)),
379 ];
381​
382function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution {
383 return {
384 timestampMs,
385 model: state.model,
386 turnId: state.turnId,
387 speed: state.speed,
388 sawThreadSettings: state.sawThreadSettings,
389 };
391​
392function codexRequestRecord(
393 state: CodexScanState,
394 usage: CodexTokenUsage,
395 { timestampMs, model, turnId, speed, sawThreadSettings }: CodexRequestAttribution,
396): UsageRecord {
397 const inputTokens = usage.input_tokens;
398 const cachedInputTokens = usage.cached_input_tokens;
399 const cacheCreationTokens = usage.cache_write_input_tokens;
400 const outputTokens = usage.output_tokens;
401​
402 const totals: UsageTokenTotals = {
403 // Codex reports `input_tokens` inclusive of the cached portion.
404 uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
405 cachedInputTokens,
406 cacheCreationTokens,
407 outputTokens,
408 // Reported inside output_tokens, surfaced separately for the token mix.
409 reasoningTokens: usage.reasoning_output_tokens,
410 };
411​
412 return {
413 provider: "codex",
414 timestampMs,
415 model,
416 sessionId: state.sessionId,
417 totals,
418 reportedCostUsd: null,
419 speed,
420 ...(!sawThreadSettings &&
421 state.modelProvider === "openai" &&
422 state.sessionId.length > 0 &&
423 turnId.length > 0
424 ? { unresolvedServiceTierTurnId: turnId }
425 : {}),
426 dedupeKey: null,
427 };
429​
430/** Missing, default and standard tiers bill as standard; fast aliases priority. */
431function codexSpeed(serviceTier: unknown): UsageSpeed {
432 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
433 if (serviceTier === "ultrafast") return "ultrafast";
434 return "standard";
436​
437export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
438 selectFields: {
439 type: true,
440 timestamp: true,
441 payload: {
442 type: true,
443 id: true,
444 session_id: true,
445 model_provider: true,
446 turn_id: true,
447 response_id: true,
448 model: true,
449 thread_settings: { service_tier: true },
450 forked_from_id: true,
451 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
452 info: { last_token_usage: true, total_token_usage: true },
453 usage: true,
454 },
455 },
456 // Metadata lines carry model, tier and session even without usage.
457 usageMarkers: [
458 '"token_count"',
459 '"token_usage_record"',
460 '"turn_context"',
461 '"thread_settings_applied"',
462 '"session_meta"',
463 ],
464 parseLine: parseCodexLine,
465 parseProjected: parseCodexRecord,
466 state: { initial: initialCodexScanState, schema: CodexScanState },
467 readMalformedRecords: (state) => state.malformedRecords,
468 // A rollout that moved after it was read leaves a copy in both places.
469 sharedSessionsAcrossFiles: true,
470};
471​
472export const codexUsageReader: ProviderUsageReader<
473 CodexSettings,
474 Path.Path | CodexUsageHistory.CodexUsageHistory
475> = {
476 kind: "transcripts",
477 provider: "codex",
478 format: codexUsageFormat,
479 resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) {
480 const history = yield* CodexUsageHistory.CodexUsageHistory;
481 const requests = new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageRecord>();
482 for (const record of records) {
483 if (record.unresolvedServiceTierTurnId === undefined) continue;
484 requests.set(
485 {
486 sessionId: record.sessionId,
487 nativeTurnId: record.unresolvedServiceTierTurnId,
488 model: record.model,
489 },
490 record,
491 );
492 }
493 const resolved = yield* history.resolve([...requests.keys()]).pipe(
494 Effect.catchTags({
495 CodexUsageHistoryReadError: () =>
496 Effect.succeed(new Map<CodexUsageHistory.CodexUsageHistoryRequest, UsageSpeed>()),
497 }),
498 );
499 const speeds = new Map<UsageRecord, UsageSpeed>();
500 for (const [request, speed] of resolved) {
501 const record = requests.get(request);
502 if (record !== undefined) speeds.set(record, speed);
503 }
504 return speeds;
505 }),
506 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
507 if (config === undefined) return [];
508 const path = yield* Path.Path;
509 const environmentHome = environment.CODEX_HOME?.trim();
510 const layout = yield* resolveCodexHomeLayout(
511 config.setupMode !== "managed" &&
512 !config.homePath.trim() &&
513 !config.shadowHomePath.trim() &&
514 environmentHome
515 ? { ...config, homePath: environmentHome }
516 : config,
517 );
518 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
519 }),
520};