@zvada/agent-server 0.3.15 → 0.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,20 +4,17 @@ import { isAbsolute, resolve } from "node:path";
4
4
  import type {
5
5
  AgentCapabilities,
6
6
  AgentInput,
7
+ ModelDescriptor,
7
8
  PermissionMode,
8
9
  PermissionToolCall,
9
10
  ThinkingLevel,
10
11
  } from "../../../protocol/index.ts";
11
- import {
12
- AsyncQueue,
13
- codexReasoningEffort,
14
- isThinkingLevel,
15
- modelThinkingLevels,
16
- } from "../../../protocol/index.ts";
12
+ import { AsyncQueue, codexReasoningEffort, modelThinkingLevels } from "../../../protocol/index.ts";
17
13
  import { SessionResumeError } from "../../utils/errors.ts";
18
14
  import type {
19
15
  AgentExecuteOptions,
20
16
  CancelResult,
17
+ ListModelsOptions,
21
18
  PermissionRequestHandler,
22
19
  RawAgentEvent,
23
20
  } from "../base.ts";
@@ -36,8 +33,19 @@ import {
36
33
  codexMcpServers,
37
34
  writeCodexMcpServers,
38
35
  } from "./mcp.ts";
36
+ import {
37
+ type CodexModelThinking,
38
+ codexModelDescriptors,
39
+ codexModelThinking,
40
+ codexThinkingLevel,
41
+ listCodexModels,
42
+ readCodexListing,
43
+ readCodexModels,
44
+ } from "./models.ts";
39
45
  import { CodexTurnSubagents } from "./subagents.ts";
40
46
 
47
+ export type { CodexModelThinking } from "./models.ts";
48
+
41
49
  const CAPABILITIES: AgentCapabilities = {
42
50
  multiTurn: true,
43
51
  sessionResume: true,
@@ -68,16 +76,14 @@ export interface AppServerSession {
68
76
  idleTimer?: ReturnType<typeof setTimeout>;
69
77
  /** The thread's model, as Codex resolved it (config.toml included). */
70
78
  model?: string;
79
+ /** The model Codex reported for the thread, until a turn selects another. */
80
+ reportedModel?: string;
81
+ /** The thread's reasoning effort: Codex's own, then the last one a turn sent (they persist). */
82
+ effort?: string;
71
83
  /** What each model accepts, from this process's `model/list`; read once. */
72
84
  modelEfforts?: Promise<ReadonlyMap<string, CodexModelThinking> | undefined>;
73
85
  }
74
86
 
75
- /** A model's thinking levels, and the native effort that `off` means for it. */
76
- export interface CodexModelThinking {
77
- levels: readonly ThinkingLevel[];
78
- off?: "none" | "minimal";
79
- }
80
-
81
87
  interface AppServerTurn {
82
88
  auth?: CodexAppServerAuth;
83
89
  permissionHandler?: PermissionRequestHandler;
@@ -203,6 +209,17 @@ export interface CodexChatGptAuth {
203
209
 
204
210
  export type CodexAppServerAuth = { type: "apiKey"; apiKey: string } | CodexChatGptAuth;
205
211
 
212
+ function loginParams(auth: CodexAppServerAuth): Record<string, unknown> {
213
+ return auth.type === "apiKey"
214
+ ? { type: "apiKey", apiKey: auth.apiKey }
215
+ : {
216
+ type: "chatgptAuthTokens",
217
+ accessToken: auth.tokens.accessToken,
218
+ chatgptAccountId: auth.tokens.chatgptAccountId,
219
+ chatgptPlanType: auth.tokens.chatgptPlanType ?? null,
220
+ };
221
+ }
222
+
206
223
  function authFingerprint(auth: CodexAppServerAuth | undefined): string | undefined {
207
224
  if (!auth) return undefined;
208
225
  return configFingerprint(
@@ -241,56 +258,21 @@ export function appServerNotificationEndsTurn(notification: CodexNotification):
241
258
  );
242
259
  }
243
260
 
244
- const MODEL_LIST_TIMEOUT_MS = 5_000;
245
-
246
261
  /**
247
262
  * The thinking levels each model the logged-in account can run accepts, from
248
- * `model/list`. Codex's `none` or `minimal` is `off`, and is remembered so
249
- * `off` sends the value the model advertised (`none` when it offers both).
250
- * `undefined` when the CLI cannot answer; callers fall back to `MODEL_CATALOG`.
263
+ * `model/list`. `undefined` when the CLI cannot answer; callers fall back to
264
+ * `MODEL_CATALOG`.
251
265
  */
252
266
  export async function listModelThinking(
253
267
  client: Pick<CodexAppServerClient, "request">,
254
268
  ): Promise<ReadonlyMap<string, CodexModelThinking> | undefined> {
255
- const models = new Map<string, CodexModelThinking>();
256
- let cursor: string | undefined;
257
269
  try {
258
- for (let page = 0; page < 10; page++) {
259
- const result = (await client.request(
260
- "model/list",
261
- { includeHidden: true, ...(cursor && { cursor }) },
262
- MODEL_LIST_TIMEOUT_MS,
263
- )) as { data?: unknown; nextCursor?: unknown } | undefined;
264
- if (!Array.isArray(result?.data)) break;
265
- for (const entry of result.data as Array<Record<string, unknown>>) {
266
- const efforts = Array.isArray(entry.supportedReasoningEfforts)
267
- ? (entry.supportedReasoningEfforts as Array<{ reasoningEffort?: unknown }>).map(
268
- ({ reasoningEffort }) => reasoningEffort,
269
- )
270
- : [];
271
- const off = efforts.includes("none")
272
- ? "none"
273
- : efforts.includes("minimal")
274
- ? "minimal"
275
- : undefined;
276
- const levels: ThinkingLevel[] = [
277
- ...(off ? (["off"] as const) : []),
278
- ...efforts.filter(
279
- (effort): effort is ThinkingLevel =>
280
- typeof effort === "string" && effort !== "off" && isThinkingLevel(effort),
281
- ),
282
- ];
283
- for (const name of [entry.model, entry.id])
284
- if (typeof name === "string" && levels.length)
285
- models.set(name, { levels, ...(off && { off }) });
286
- }
287
- cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;
288
- if (!cursor) break;
289
- }
270
+ const thinking = codexModelThinking(await readCodexModels(client));
271
+ return thinking.size ? thinking : undefined;
290
272
  } catch {
291
273
  // An older CLI, a slow answer or a closed process: the catalog decides.
274
+ return undefined;
292
275
  }
293
- return models.size ? models : undefined;
294
276
  }
295
277
 
296
278
  /**
@@ -317,6 +299,11 @@ export class CodexAppServerAgent extends SessionAgent {
317
299
  super();
318
300
  }
319
301
 
302
+ /** With host-managed auth, each session may list as a different account. */
303
+ get modelsPerSession(): boolean {
304
+ return Boolean(this.agentOptions.resolveAuth);
305
+ }
306
+
320
307
  private async resolveSession(
321
308
  options: AgentExecuteOptions,
322
309
  turn: AppServerTurn,
@@ -427,7 +414,7 @@ export class CodexAppServerAgent extends SessionAgent {
427
414
  cause instanceof Error ? cause.message : String(cause),
428
415
  { cause },
429
416
  );
430
- })) as { thread?: { id?: string }; model?: unknown };
417
+ })) as { thread?: { id?: string }; model?: unknown; reasoningEffort?: unknown };
431
418
  const threadId = result?.thread?.id;
432
419
  if (resumeThreadId && threadId !== resumeThreadId) {
433
420
  throw new SessionResumeError(
@@ -439,6 +426,8 @@ export class CodexAppServerAgent extends SessionAgent {
439
426
  signal.throwIfAborted();
440
427
  session.threadId = threadId;
441
428
  session.model = typeof result.model === "string" ? result.model : options.model;
429
+ if (typeof result.model === "string") session.reportedModel = result.model;
430
+ if (typeof result.reasoningEffort === "string") session.effort = result.reasoningEffort;
442
431
  this.sessions.set(options.sessionId, session);
443
432
  return session;
444
433
  } catch (error) {
@@ -491,32 +480,61 @@ export class CodexAppServerAgent extends SessionAgent {
491
480
  session.mcpFingerprint = fingerprint;
492
481
  }
493
482
 
494
- /** What the thread's model accepts: live from this process, else the catalog. */
495
- private async modelThinking(session: AppServerSession): Promise<CodexModelThinking | undefined> {
483
+ /** What the thread's model accepts: live from this process, else what the engine knows. */
484
+ private async modelThinking(
485
+ session: AppServerSession,
486
+ known?: readonly ThinkingLevel[],
487
+ ): Promise<CodexModelThinking | undefined> {
496
488
  if (!session.model) return undefined;
497
489
  session.modelEfforts ??= listModelThinking(session.client);
498
490
  const live = (await session.modelEfforts)?.get(session.model);
499
491
  if (live) return live;
500
- const levels = modelThinkingLevels("codex-app-server", session.model);
492
+ const levels = known ?? modelThinkingLevels("codex-app-server", session.model);
501
493
  return levels && { levels };
502
494
  }
503
495
 
496
+ /**
497
+ * The models Codex offers this login. Reuses the session's process when
498
+ * `sessionId` has one started with the same `env` (its `CODEX_HOME` decides
499
+ * the login and config); otherwise starts `codex app-server` just to ask,
500
+ * with the account `resolveAuth` selects for that session.
501
+ */
502
+ async listModels(options: ListModelsOptions): Promise<ModelDescriptor[]> {
503
+ const live = options.sessionId ? this.sessions.get(options.sessionId) : undefined;
504
+ if (live && !live.client.closed && live.envFingerprint === configFingerprint(options.env)) {
505
+ const listing = await readCodexListing(live.client, options.cwd);
506
+ return codexModelDescriptors(listing.models, this.harness, listing.configuredModel);
507
+ }
508
+ const auth =
509
+ options.sessionId && this.agentOptions.resolveAuth
510
+ ? await this.agentOptions.resolveAuth(options.sessionId)
511
+ : undefined;
512
+ options.signal?.throwIfAborted();
513
+ const listing = await listCodexModels(
514
+ {
515
+ codexPath:
516
+ (await this.agentOptions.resolveCliPath?.()) ?? process.env.CODEX_CLI_PATH ?? "codex",
517
+ cwd: options.cwd,
518
+ env: options.env ? ({ ...process.env, ...options.env } as NodeJS.ProcessEnv) : process.env,
519
+ ...(auth?.type === "chatgptAuthTokens" && { experimentalApi: true }),
520
+ },
521
+ {
522
+ signal: options.signal,
523
+ ...(this.agentOptions.createClient && { createClient: this.agentOptions.createClient }),
524
+ ...(auth && {
525
+ login: async (client) => {
526
+ await client.request("account/login/start", loginParams(auth));
527
+ },
528
+ }),
529
+ },
530
+ );
531
+ return codexModelDescriptors(listing.models, this.harness, listing.configuredModel);
532
+ }
533
+
504
534
  private async authenticate(session: AppServerSession): Promise<void> {
505
535
  session.turn?.signal.throwIfAborted();
506
536
  const auth = session.turn?.auth;
507
- if (auth) {
508
- await session.client.request(
509
- "account/login/start",
510
- auth.type === "apiKey"
511
- ? { type: "apiKey", apiKey: auth.apiKey }
512
- : {
513
- type: "chatgptAuthTokens",
514
- accessToken: auth.tokens.accessToken,
515
- chatgptAccountId: auth.tokens.chatgptAccountId,
516
- chatgptPlanType: auth.tokens.chatgptPlanType ?? null,
517
- },
518
- );
519
- }
537
+ if (auth) await session.client.request("account/login/start", loginParams(auth));
520
538
  session.turn?.signal.throwIfAborted();
521
539
  }
522
540
 
@@ -793,18 +811,51 @@ export class CodexAppServerAgent extends SessionAgent {
793
811
  threadId,
794
812
  input: toUserInput(input),
795
813
  };
814
+ // A refused turn/start changes nothing on the thread.
815
+ const before = {
816
+ model: session.model,
817
+ reportedModel: session.reportedModel,
818
+ effort: session.effort,
819
+ };
820
+ const switched = Boolean(options.model) && options.model !== session.model;
796
821
  if (options.model) {
797
822
  turnParams.model = options.model;
798
823
  session.model = options.model;
824
+ // A model this turn selects is requested, not reported.
825
+ if (options.model !== session.reportedModel) session.reportedModel = undefined;
799
826
  }
800
827
  if (options.thinkingLevel) {
801
- const accepts = await this.modelThinking(session);
828
+ const accepts = await this.modelThinking(
829
+ session,
830
+ options.model ? options.modelThinking : undefined,
831
+ );
802
832
  turnParams.effort = codexReasoningEffort(
803
833
  options.thinkingLevel,
804
834
  accepts?.levels,
805
835
  accepts?.off,
806
836
  );
837
+ session.effort = turnParams.effort as string;
838
+ } else if (switched && session.effort) {
839
+ // The thread keeps its effort across a model switch. Fit it to the new
840
+ // model, so Codex is not asked for a level that model lacks.
841
+ const kept = codexThinkingLevel(session.effort);
842
+ const accepts = await this.modelThinking(session, options.modelThinking);
843
+ if (kept && accepts?.levels.length) {
844
+ const effort = codexReasoningEffort(kept, accepts.levels, accepts.off);
845
+ if (effort !== session.effort) {
846
+ turnParams.effort = effort;
847
+ session.effort = effort;
848
+ }
849
+ }
807
850
  }
851
+ // Codex runs the effort it is given, and overrides persist on the
852
+ // thread, so the thread's effort is the one this turn runs.
853
+ const applied = codexThinkingLevel(session.effort);
854
+ if (applied || session.reportedModel)
855
+ options.onExecution?.({
856
+ ...(applied && { thinkingLevel: applied }),
857
+ ...(session.reportedModel && { model: session.reportedModel }),
858
+ });
808
859
 
809
860
  if (controller.signal.aborted) throw new Error("turn aborted");
810
861
  if (this.invalidatedClients.has(client)) {
@@ -812,6 +863,7 @@ export class CodexAppServerAgent extends SessionAgent {
812
863
  throw new Error("Codex process was invalidated before turn admission");
813
864
  }
814
865
  client.request("turn/start", turnParams).catch((err: unknown) => {
866
+ if (session) Object.assign(session, before);
815
867
  if (controller.signal.aborted) {
816
868
  if (turn.subagents) void finishManaged();
817
869
  else forceCancel();
@@ -0,0 +1,177 @@
1
+ import type { AgentHarness, ModelDescriptor, ThinkingLevel } from "../../../protocol/index.ts";
2
+ import { isThinkingLevel } from "../../../protocol/index.ts";
3
+ import { knownThinkingLevels } from "../thinking-levels.ts";
4
+ import { CodexAppServerClient, type CodexAppServerClientOptions } from "./client.ts";
5
+
6
+ const MODEL_LIST_TIMEOUT_MS = 5_000;
7
+
8
+ /** One `model/list` entry, as far as agent-server reads it. */
9
+ export type CodexModel = Record<string, unknown>;
10
+
11
+ /** A model's thinking levels, and the native effort that `off` means for it. */
12
+ export interface CodexModelThinking {
13
+ levels: readonly ThinkingLevel[];
14
+ off?: "none" | "minimal";
15
+ }
16
+
17
+ /** The level a native Codex effort is: `none` and `minimal` are `off`. */
18
+ export function codexThinkingLevel(effort: unknown): ThinkingLevel | undefined {
19
+ if (effort === "none" || effort === "minimal") return "off";
20
+ return typeof effort === "string" && effort !== "off" && isThinkingLevel(effort)
21
+ ? effort
22
+ : undefined;
23
+ }
24
+
25
+ function efforts(model: CodexModel): unknown[] {
26
+ return Array.isArray(model.supportedReasoningEfforts)
27
+ ? (model.supportedReasoningEfforts as Array<{ reasoningEffort?: unknown }>).map(
28
+ (option) => option?.reasoningEffort,
29
+ )
30
+ : [];
31
+ }
32
+
33
+ /** Every page of `model/list`, hidden models included. Throws when the CLI cannot answer. */
34
+ export async function readCodexModels(
35
+ client: Pick<CodexAppServerClient, "request">,
36
+ ): Promise<CodexModel[]> {
37
+ const models: CodexModel[] = [];
38
+ let cursor: string | undefined;
39
+ for (let page = 0; page < 10; page++) {
40
+ const result = (await client.request(
41
+ "model/list",
42
+ { includeHidden: true, ...(cursor && { cursor }) },
43
+ MODEL_LIST_TIMEOUT_MS,
44
+ )) as { data?: unknown; nextCursor?: unknown } | undefined;
45
+ if (!Array.isArray(result?.data)) throw new Error("codex model/list returned no models");
46
+ models.push(...(result.data as CodexModel[]));
47
+ cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;
48
+ if (!cursor) break;
49
+ }
50
+ return models;
51
+ }
52
+
53
+ /**
54
+ * What each model accepts, by its `model` and `id`. Codex's `none` or
55
+ * `minimal` is `off`, remembered so `off` sends the value the model
56
+ * advertised (`none` when it offers both).
57
+ */
58
+ export function codexModelThinking(models: readonly CodexModel[]): Map<string, CodexModelThinking> {
59
+ const thinking = new Map<string, CodexModelThinking>();
60
+ for (const model of models) {
61
+ const native = efforts(model);
62
+ const off = native.includes("none")
63
+ ? "none"
64
+ : native.includes("minimal")
65
+ ? "minimal"
66
+ : undefined;
67
+ const levels = knownThinkingLevels(native.map(codexThinkingLevel));
68
+ if (!levels.length) continue;
69
+ for (const name of [model.model, model.id])
70
+ if (typeof name === "string") thinking.set(name, { levels, ...(off && { off }) });
71
+ }
72
+ return thinking;
73
+ }
74
+
75
+ /**
76
+ * The model a new thread in `cwd` runs when the turn names none, when Codex's
77
+ * configuration (`~/.codex/config.toml`, a project layer) selects one. Codex's
78
+ * own `isDefault` ignores it.
79
+ */
80
+ export async function readCodexConfiguredModel(
81
+ client: Pick<CodexAppServerClient, "request">,
82
+ cwd: string,
83
+ ): Promise<string | undefined> {
84
+ try {
85
+ const result = (await client.request("config/read", { cwd }, MODEL_LIST_TIMEOUT_MS)) as
86
+ | { config?: { model?: unknown } }
87
+ | undefined;
88
+ return typeof result?.config?.model === "string" ? result.config.model : undefined;
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * The models Codex offers in a picker, in the shared shape. Hidden models are
96
+ * left out. `configuredModel` (see `readCodexConfiguredModel`) is the default
97
+ * when given; otherwise Codex's own default is.
98
+ */
99
+ export function codexModelDescriptors(
100
+ models: readonly CodexModel[],
101
+ harness: Extract<AgentHarness, "codex-sdk" | "codex-app-server">,
102
+ configuredModel?: string,
103
+ ): ModelDescriptor[] {
104
+ return models.flatMap((model) => {
105
+ const id = typeof model.model === "string" ? model.model : model.id;
106
+ if (typeof id !== "string" || model.hidden === true) return [];
107
+ const levels = knownThinkingLevels(efforts(model).map(codexThinkingLevel));
108
+ const fallback = codexThinkingLevel(model.defaultReasoningEffort);
109
+ return [
110
+ {
111
+ id,
112
+ harness,
113
+ label: typeof model.displayName === "string" && model.displayName ? model.displayName : id,
114
+ ...(typeof model.description === "string" &&
115
+ model.description && { description: model.description }),
116
+ ...((configuredModel ? id === configuredModel : model.isDefault === true) && {
117
+ isDefault: true,
118
+ }),
119
+ thinking: {
120
+ levels,
121
+ ...(fallback && levels.includes(fallback) && { default: fallback }),
122
+ },
123
+ ...(Array.isArray(model.inputModalities) && {
124
+ images: model.inputModalities.includes("image"),
125
+ }),
126
+ },
127
+ ];
128
+ });
129
+ }
130
+
131
+ /** What one `codex app-server` says about its models. */
132
+ export interface CodexModelListing {
133
+ models: CodexModel[];
134
+ /** The model new threads in the listing's folder run by default (see `readCodexConfiguredModel`). */
135
+ configuredModel?: string;
136
+ }
137
+
138
+ /** Read the models and the configured default from a running app-server. */
139
+ export async function readCodexListing(
140
+ client: Pick<CodexAppServerClient, "request">,
141
+ cwd: string,
142
+ ): Promise<CodexModelListing> {
143
+ const models = await readCodexModels(client);
144
+ const configuredModel = await readCodexConfiguredModel(client, cwd);
145
+ return { models, ...(configuredModel && { configuredModel }) };
146
+ }
147
+
148
+ /**
149
+ * Start `codex app-server` only to list its models, for the login its
150
+ * environment selects (or `login` performs). No thread is started.
151
+ */
152
+ export async function listCodexModels(
153
+ options: CodexAppServerClientOptions & { cwd: string },
154
+ {
155
+ signal,
156
+ createClient = (clientOptions) => new CodexAppServerClient(clientOptions),
157
+ login,
158
+ }: {
159
+ signal?: AbortSignal;
160
+ createClient?: (options: CodexAppServerClientOptions) => CodexAppServerClient;
161
+ login?: (client: CodexAppServerClient) => Promise<void>;
162
+ } = {},
163
+ ): Promise<CodexModelListing> {
164
+ signal?.throwIfAborted();
165
+ const client = createClient(options);
166
+ const stop = () => client.close();
167
+ signal?.addEventListener("abort", stop, { once: true });
168
+ try {
169
+ await client.initialize();
170
+ await login?.(client);
171
+ signal?.throwIfAborted();
172
+ return await readCodexListing(client, options.cwd);
173
+ } finally {
174
+ signal?.removeEventListener("abort", stop);
175
+ client.close();
176
+ }
177
+ }
@@ -1,5 +1,4 @@
1
1
  import {
2
- DEFAULT_TOKEN_USAGE,
3
2
  type Part,
4
3
  type ReasoningPart,
5
4
  type StopReason,
@@ -37,27 +36,48 @@ interface ThreadItem extends CodexToolItem {
37
36
  text?: string;
38
37
  message?: string;
39
38
  }
39
+ /** `codex exec` usage: totals for the whole thread so far, not for one turn. */
40
+ export interface CodexExecUsage {
41
+ input_tokens?: number;
42
+ cached_input_tokens?: number;
43
+ cache_write_input_tokens?: number;
44
+ output_tokens?: number;
45
+ reasoning_output_tokens?: number;
46
+ }
47
+
48
+ /**
49
+ * Sent by `CodexSdkAgent` before a turn's events: the thread's usage when the
50
+ * turn began, or `null` when it is unknown (a thread resumed in this process).
51
+ */
52
+ export const USAGE_BASELINE_EVENT = "agent_server.usage_baseline";
53
+
40
54
  interface CodexEvent {
41
55
  type: string;
42
56
  thread_id?: string;
43
57
  item?: ThreadItem;
44
- usage?: {
45
- input_tokens?: number;
46
- cached_input_tokens?: number;
47
- cache_write_input_tokens?: number;
48
- output_tokens?: number;
49
- reasoning_output_tokens?: number;
50
- };
58
+ usage?: CodexExecUsage | null;
51
59
  error?: { message?: string };
52
60
  message?: string;
53
61
  }
54
62
 
63
+ function subtractExecUsage(a: CodexExecUsage, b: CodexExecUsage): CodexExecUsage {
64
+ const out: CodexExecUsage = {};
65
+ for (const key of Object.keys(a) as Array<keyof CodexExecUsage>) {
66
+ const value = a[key];
67
+ if (typeof value === "number") out[key] = Math.max(value - (b[key] ?? 0), 0);
68
+ }
69
+ return out;
70
+ }
71
+
55
72
  export class CodexSdkTransformer implements EventTransformer<unknown> {
56
73
  private readonly ctx: StreamContext;
57
74
  private readonly partByItem = new Map<string, Part>();
58
75
  private readonly textLenByItem = new Map<string, number>();
59
76
 
60
- private usage: TokenUsage = { ...DEFAULT_TOKEN_USAGE };
77
+ /** Known only once Codex reports the turn complete. */
78
+ private usage?: TokenUsage;
79
+ /** The thread's usage before this turn; `null` when unknown. Without one, zero. */
80
+ private baseline: CodexExecUsage | null = {};
61
81
  private stopReason?: StopReason;
62
82
  private finishReason?: string;
63
83
  private error?: string;
@@ -75,6 +95,9 @@ export class CodexSdkTransformer implements EventTransformer<unknown> {
75
95
  return ev.item ? this.handleItem(ev.item, "updated") : [];
76
96
  case "item.completed":
77
97
  return ev.item ? this.handleItem(ev.item, "completed") : [];
98
+ case USAGE_BASELINE_EVENT:
99
+ this.baseline = ev.usage ?? null;
100
+ return [];
78
101
  case "turn.completed": {
79
102
  // Completion supersedes earlier stream notices: codex emits non-fatal
80
103
  // diagnostics (retry / skills-context-budget notices) as `error`
@@ -84,17 +107,24 @@ export class CodexSdkTransformer implements EventTransformer<unknown> {
84
107
  this.finishReason = "completed";
85
108
  this.stopReason = "end_turn";
86
109
  if (!ev.usage) return [];
87
- const totalInput = ev.usage.input_tokens ?? 0;
88
- const cached = ev.usage.cached_input_tokens ?? 0;
89
- const written = ev.usage.cache_write_input_tokens ?? 0;
110
+ // Codex reports the thread's totals; this turn used their growth.
111
+ // With the starting totals unknown, so is this turn's usage.
112
+ if (!this.baseline) {
113
+ this.usage = undefined;
114
+ return [];
115
+ }
116
+ const turn = subtractExecUsage(ev.usage, this.baseline);
117
+ const totalInput = turn.input_tokens ?? 0;
118
+ const cached = turn.cached_input_tokens ?? 0;
119
+ const written = turn.cache_write_input_tokens ?? 0;
90
120
  this.usage = {
91
121
  // Input and cache buckets are disjoint in the normalized protocol.
92
122
  input: Math.max(totalInput - cached - written, 0),
93
- output: ev.usage.output_tokens ?? 0,
94
- reasoning: ev.usage.reasoning_output_tokens ?? 0,
123
+ output: turn.output_tokens ?? 0,
124
+ reasoning: turn.reasoning_output_tokens ?? 0,
95
125
  cache: { read: cached, write: written },
96
126
  };
97
- const used = totalInput + (ev.usage.output_tokens ?? 0);
127
+ const used = totalInput + (turn.output_tokens ?? 0);
98
128
  return [{ kind: "usage", used }];
99
129
  }
100
130
  case "turn.failed":