@zvada/agent-server 0.3.16 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.17
4
+
5
+ - Codex token usage counts each turn. Both Codex harnesses reported Codex's
6
+ totals for the whole thread as `turn.ended.tokens`, so every turn after the
7
+ first also counted all the turns before it: a third turn reported 38.3k
8
+ input tokens where it used 17k, and summing turns over-counted. Each turn
9
+ now reports what the thread's totals grew by during it, and the turns add up
10
+ to Codex's thread total. The `codex-app-server` context gauge now shows the
11
+ latest request's context rather than the thread total. `codex exec` gives
12
+ only thread totals, so a `codex-sdk` turn reports no `tokens` when its
13
+ starting point is unknown: on a thread resumed from another process, or after
14
+ a turn that stopped before completing (cancelled or crashed), whose requests
15
+ the totals now include. Such an incomplete turn also reports no `tokens`
16
+ instead of zero.
17
+ - `TransformResult.usage` is optional for an adapter that cannot tell a turn's
18
+ usage; `turn.ended` then carries no `tokens`.
19
+
3
20
  ## 0.3.16
4
21
 
5
22
  - List each harness's models live: `runtime.models({ harness, cwd })`, wire
package/docs/harnesses.md CHANGED
@@ -175,9 +175,14 @@ The protocol was checked against Codex CLI 0.160.0 and the
175
175
 
176
176
  ## Token and cache accounting
177
177
 
178
- Every adapter uses the same `TokenUsage` on `turn.ended.tokens`. A custom
179
- adapter maps its provider's counts into this contract; storage and consumers
180
- do not need a new schema for each harness.
178
+ Every adapter uses the same `TokenUsage` on `turn.ended.tokens`, counting that
179
+ turn only. A custom adapter maps its provider's counts into this contract;
180
+ storage and consumers do not need a new schema for each harness. Codex reports
181
+ totals for the whole thread, so both Codex adapters report how much the totals
182
+ grew during the turn. `codex exec` gives only thread totals, so a `codex-sdk`
183
+ turn reports no `tokens` when its starting point is unknown: on a thread
184
+ resumed from another process, or after a turn that stopped before completing. The `codex-app-server` context gauge
185
+ (`session.usage`) is the latest request's context.
181
186
 
182
187
  | Field | Meaning |
183
188
  | --- | --- |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvada/agent-server",
3
- "version": "0.3.16",
3
+ "version": "0.3.17",
4
4
  "description": "Harness-agnostic agent execution engine: run Claude Code, Codex (SDK/CLI + app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -49,7 +49,8 @@ interface Notification {
49
49
  last?: Record<string, number>;
50
50
  modelContextWindow?: number;
51
51
  };
52
- turn?: { error?: { message?: string } | null };
52
+ turn?: { id?: string; error?: { message?: string } | null };
53
+ turnId?: string;
53
54
  error?: { message?: string; additionalDetails?: string | null };
54
55
  willRetry?: boolean;
55
56
  message?: string;
@@ -62,6 +63,9 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
62
63
  private readonly partByItem = new Map<string, Part>();
63
64
 
64
65
  private usage: TokenUsage = { ...DEFAULT_TOKEN_USAGE };
66
+ /** The thread's totals when this turn began: Codex's `total` counts the whole thread. */
67
+ private baseline?: Record<string, number>;
68
+ private turnId?: string;
65
69
  private readonly reportedModels = new Set<string>();
66
70
  private stopReason?: StopReason;
67
71
  private finishReason?: string;
@@ -86,11 +90,24 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
86
90
  case "item/reasoning/textDelta":
87
91
  case "item/reasoning/summaryTextDelta":
88
92
  return this.textDelta(params.itemId, params.delta, "reasoning");
93
+ case "turn/started":
94
+ this.turnId ??= params.turn?.id;
95
+ return [];
89
96
  case "thread/tokenUsage/updated": {
90
- this.captureUsage(params.tokenUsage?.total);
91
97
  const total = params.tokenUsage?.total;
92
98
  if (!total) return [];
93
- const used = total.totalTokens ?? (total.inputTokens ?? 0) + (total.outputTokens ?? 0);
99
+ // A resumed thread first restates the previous turn's totals, before
100
+ // `turn/started` names this turn: count only this turn's updates.
101
+ if (params.turnId && params.turnId !== this.turnId) return [];
102
+ // This turn used what the thread's totals grew by. Its first update's
103
+ // `last` is the turn's first request, so the totals before it are the
104
+ // turn's starting point.
105
+ const last = params.tokenUsage?.last;
106
+ this.baseline ??= last ? subtractUsage(total, last) : {};
107
+ this.captureUsage(subtractUsage(total, this.baseline));
108
+ // The context in use is the latest request's.
109
+ const latest = last ?? total;
110
+ const used = latest.totalTokens ?? (latest.inputTokens ?? 0) + (latest.outputTokens ?? 0);
94
111
  const size = params.tokenUsage?.modelContextWindow;
95
112
  return [{ kind: "usage", used, ...(size !== undefined && { size }) }];
96
113
  }
@@ -256,6 +273,17 @@ export class CodexAppServerTransformer implements EventTransformer<unknown> {
256
273
  }
257
274
  }
258
275
 
276
+ /** Field-by-field `a - b` of two Codex usage breakdowns, never below zero. */
277
+ export function subtractUsage(
278
+ a: Record<string, number>,
279
+ b: Record<string, number>,
280
+ ): Record<string, number> {
281
+ const out: Record<string, number> = {};
282
+ for (const [key, value] of Object.entries(a))
283
+ if (typeof value === "number") out[key] = Math.max(value - (b[key] ?? 0), 0);
284
+ return out;
285
+ }
286
+
259
287
  export function createCodexAppServerTransformer(ctx: { sessionId: string }): EventTransformer {
260
288
  return new CodexAppServerTransformer(ctx);
261
289
  }
@@ -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":
@@ -15,6 +15,7 @@ import {
15
15
  } from "../codex-app-server/models.ts";
16
16
  import { configFingerprint } from "../config-fingerprint.ts";
17
17
  import { SessionAgent } from "../session-agent.ts";
18
+ import { type CodexExecUsage, USAGE_BASELINE_EVENT } from "./adapter.ts";
18
19
 
19
20
  const CAPABILITIES: AgentCapabilities = {
20
21
  multiTurn: true,
@@ -35,6 +36,8 @@ export interface LiveThread {
35
36
  thinkingLevel?: string;
36
37
  /** The effort the thread was started with; `codex exec` keeps it for the thread's life. */
37
38
  effort?: string;
39
+ /** The thread's usage totals after its last turn; absent or `null` when unknown. */
40
+ usage?: CodexExecUsage | null;
38
41
  cwd: string;
39
42
  permissionMode?: PermissionMode;
40
43
  credentialsFingerprint: string;
@@ -216,6 +219,8 @@ export class CodexSdkAgent extends SessionAgent {
216
219
  model: options.model,
217
220
  thinkingLevel: effort,
218
221
  effort: settings.modelReasoningEffort,
222
+ // A thread restarted here keeps its totals; one resumed from elsewhere has unknown ones.
223
+ usage: !resumeThreadId ? {} : existing?.thread.id === resumeThreadId ? existing.usage : null,
219
224
  cwd: options.cwd,
220
225
  permissionMode: options.permissionMode,
221
226
  credentialsFingerprint: fingerprint,
@@ -241,12 +246,21 @@ export class CodexSdkAgent extends SessionAgent {
241
246
  const { events } = await live.thread.runStreamed(toCodexInput(input), {
242
247
  signal: controller.signal,
243
248
  });
249
+ let baselineSent = false;
250
+ let completed = false;
244
251
  // `codex exec` reports a fatal turn on its stream, then exits non-zero; the
245
252
  // SDK throws for that exit with only stderr. Keep the reported cause.
246
253
  let failure: string | undefined;
247
254
  try {
248
255
  for await (const event of events as AsyncGenerator<ThreadEvent>) {
249
- if (event.type === "turn.failed") failure = event.error.message;
256
+ if (event.type === "turn.failed") {
257
+ failure = event.error.message;
258
+ live.usage = null;
259
+ }
260
+ if (event.type === "turn.completed") {
261
+ completed = true;
262
+ live.usage = event.usage;
263
+ }
250
264
  if (event.type === "thread.started") {
251
265
  if (options.resumeSessionId && event.thread_id !== options.resumeSessionId) {
252
266
  // The SDK mutates Thread.id before yielding this event. Discard
@@ -266,11 +280,21 @@ export class CodexSdkAgent extends SessionAgent {
266
280
  });
267
281
  }
268
282
  }
283
+ if (!baselineSent) {
284
+ baselineSent = true;
285
+ // `codex exec` reports thread totals; the adapter needs the turn's
286
+ // starting point. Sent with the first event, so nothing precedes it.
287
+ yield { type: USAGE_BASELINE_EVENT, usage: live.usage ?? null } as RawAgentEvent;
288
+ }
269
289
  yield event as RawAgentEvent;
270
290
  }
271
291
  } catch (error) {
272
292
  if (failure === undefined || controller.signal.aborted) throw error;
273
293
  throw new Error(failure, { cause: error });
294
+ } finally {
295
+ // A turn that started and did not complete (cancelled, or the CLI died)
296
+ // may have spent tokens the thread's totals now include, unseen here.
297
+ if (baselineSent && !completed) live.usage = null;
274
298
  }
275
299
  }
276
300
 
@@ -31,7 +31,8 @@ export type AdapterEvent =
31
31
 
32
32
  /** Terminal result of a turn, surfaced on `turn.ended`. */
33
33
  export interface TransformResult {
34
- usage: TokenUsage;
34
+ /** This turn's usage. Absent when the harness cannot tell it apart from earlier turns. */
35
+ usage?: TokenUsage;
35
36
  /** Models observed on the primary run, excluding subagents and configured defaults. */
36
37
  reportedModels?: string[];
37
38
  /** Normalized terminal status, when the harness reported one. The engine