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

codexUsage.ts

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