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 tokenCount,
9 totalTokens,
10 type ProviderUsageReader,
11 type TranscriptUsageFormat,
12 type UsageRecord,
13 type UsageSpeed,
14} from "@t3tools/provider-core/server/usage";
15import type { UsageTokenTotals } from "@t3tools/contracts";
16
17import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts";
18
19/**
20 * Codex `token_count` events carry no model or service tier, so both are carried forward: the model
21 * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`.
22 */
23export const CodexScanState = Schema.Struct({
24 model: Schema.mutableKey(Schema.String),
25 speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])),
26 sessionId: Schema.mutableKey(Schema.String),
27 lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
28 sawSessionMeta: Schema.mutableKey(Schema.Boolean),
29 suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
30 forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
31});
32export type CodexScanState = typeof CodexScanState.Type;
33
34export function initialCodexScanState(): CodexScanState {
35 return {
36 model: "",
37 speed: "standard",
38 sessionId: "",
39 lastUsageSignature: null,
40 sawSessionMeta: false,
41 suppressingForkCopies: false,
42 forkCopyAnchorMs: 0,
43 };
44}
45
46/**
47 * A forked or subagent rollout opens with the parent's full history copied in,
48 * every line re-stamped to the fork instant. Those copies are written in one
49 * synchronous burst (observed gaps 0-40ms), while the child's first genuine
50 * usage event only lands after a real model turn (observed 5s+).
51 */
52const FORK_COPY_MAX_GAP_MS = 1000;
53
54function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
55 if (typeof payload["forked_from_id"] === "string") return true;
56 const source = payload["source"];
57 if (typeof source !== "object" || source === null) return false;
58 const subagent = (source as Record<string, unknown>)["subagent"];
59 if (typeof subagent !== "object" || subagent === null) return false;
60 const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
61 if (typeof spawn !== "object" || spawn === null) return false;
62 return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
63}
64
65/**
66 * Deltas come from `last_token_usage`. Summing those across a session reconciles with the session's
67 * final `total_token_usage`, provided consecutive duplicate events are dropped, which this does.
68 */
69export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
70 let parsed: unknown;
71 try {
72 parsed = JSON.parse(line);
73 } catch {
74 return null;
75 }
76 return parseCodexRecord(parsed, state);
77}
78
79function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | null {
80 if (typeof parsed !== "object" || parsed === null) return null;
81
82 const record = parsed as Record<string, unknown>;
83 const payload = record["payload"];
84 if (typeof payload !== "object" || payload === null) return null;
85 const payloadRecord = payload as Record<string, unknown>;
86 const payloadType = payloadRecord["type"];
87
88 if (record["type"] === "session_meta") {
89 // Only the first meta describes this file's own session. A forked rollout
90 // repeats the ancestors' metas right after it; letting those through would
91 // reassign every subsequent record to an ancestor session.
92 if (state.sawSessionMeta) return null;
93 state.sawSessionMeta = true;
94 const id = payloadRecord["id"] ?? payloadRecord["session_id"];
95 if (typeof id === "string") state.sessionId = id;
96 const metaTimestampMs = parseTimestampMs(record["timestamp"]);
97 if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
98 state.suppressingForkCopies = true;
99 state.forkCopyAnchorMs = metaTimestampMs;
100 }
101 return null;
102 }
103
104 if (record["type"] === "turn_context") {
105 if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"];
106 return null;
107 }
108
109 if (payloadType === "thread_settings_applied") {
110 const settings = payloadRecord["thread_settings"];
111 if (typeof settings === "object" && settings !== null) {
112 state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
113 }
114 return null;
115 }
116
117 if (payloadType !== "token_count") return null;
118
119 const info = payloadRecord["info"];
120 if (typeof info !== "object" || info === null) return null;
121 const last = (info as Record<string, unknown>)["last_token_usage"];
122 if (typeof last !== "object" || last === null) return null;
123 const lastRecord = last as Record<string, unknown>;
124
125 // Only an event that is otherwise eligible may consume the duplicate
126 // signature. A token_count arriving before its turn_context (no model yet)
127 // must not poison it, or the re-emitted copy after the model is known would
128 // be skipped as a duplicate and those tokens never counted.
129 const timestampMs = parseTimestampMs(record["timestamp"]);
130 if (timestampMs === null) return null;
131 if (state.model.length === 0) return null;
132
133 // Codex re-emits an unchanged token_count on some stream boundaries. Summing
134 // those would double count, so identical consecutive payloads are skipped.
135 const signature = JSON.stringify(lastRecord);
136 if (signature === state.lastUsageSignature) return null;
137 state.lastUsageSignature = signature;
138
139 if (state.suppressingForkCopies) {
140 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
141 state.forkCopyAnchorMs = timestampMs;
142 return null;
143 }
144 state.suppressingForkCopies = false;
145 }
146
147 const inputTokens = tokenCount(lastRecord["input_tokens"]);
148 const cachedInputTokens = tokenCount(lastRecord["cached_input_tokens"]);
149 const cacheCreationTokens = tokenCount(lastRecord["cache_write_input_tokens"]);
150 const outputTokens = tokenCount(lastRecord["output_tokens"]);
151
152 const totals: UsageTokenTotals = {
153 // Codex reports `input_tokens` inclusive of the cached portion.
154 uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
155 cachedInputTokens,
156 cacheCreationTokens,
157 outputTokens,
158 // Reported inside output_tokens, surfaced separately for the token mix.
159 reasoningTokens: Math.min(outputTokens, tokenCount(lastRecord["reasoning_output_tokens"])),
160 };
161
162 if (totalTokens(totals) === 0) return null;
163
164 return {
165 provider: "codex",
166 timestampMs,
167 model: state.model,
168 sessionId: state.sessionId,
169 totals,
170 reportedCostUsd: null,
171 speed: state.speed,
172 dedupeKey: null,
173 };
174}
175
176/**
177 * Codex omits the field when no tier was requested, which bills as standard, as
178 * do `default` and `standard`. `fast` is accepted as an alias of `priority`.
179 */
180function codexSpeed(serviceTier: unknown): UsageSpeed {
181 if (serviceTier === "priority" || serviceTier === "fast") return "fast";
182 if (serviceTier === "ultrafast") return "ultrafast";
183 return "standard";
184}
185
186const orEmpty = (record: UsageRecord | null): readonly UsageRecord[] =>
187 record === null ? [] : [record];
188
189export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
190 selectFields: {
191 type: true,
192 timestamp: true,
193 payload: {
194 type: true,
195 id: true,
196 session_id: true,
197 model: true,
198 thread_settings: { service_tier: true },
199 forked_from_id: true,
200 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
201 info: { last_token_usage: true },
202 },
203 },
204 // `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
205 // usage, but they carry the model, tier and session the reducer needs.
206 usageMarkers: ['"token_count"', '"turn_context"', '"thread_settings_applied"', '"session_meta"'],
207 parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
208 parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
209 state: { initial: initialCodexScanState, schema: CodexScanState },
210 // A rollout that moved after it was read leaves a copy in both places.
211 sharedSessionsAcrossFiles: true,
212};
213
214export const codexUsageReader: ProviderUsageReader<CodexSettings, Path.Path> = {
215 kind: "transcripts",
216 provider: "codex",
217 format: codexUsageFormat,
218 directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) {
219 if (config === undefined) return [];
220 const path = yield* Path.Path;
221 const environmentHome = environment.CODEX_HOME?.trim();
222 const layout = yield* resolveCodexHomeLayout(
223 config.setupMode !== "managed" &&
224 !config.homePath.trim() &&
225 !config.shadowHomePath.trim() &&
226 environmentHome
227 ? { ...config, homePath: environmentHome }
228 : config,
229 );
230 return [{ dir: path.resolve(layout.sharedHomePath, "sessions") }];
231 }),
232};