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

codexUsage.ts

261 lines10.1 KB

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