@zvada/agent-server 0.3.16 → 0.3.18

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +30 -2
  3. package/docs/consuming.md +9 -2
  4. package/docs/harnesses.md +19 -6
  5. package/docs/sync-experiment.md +190 -0
  6. package/docs/sync-history.md +181 -0
  7. package/docs/sync-integration.md +133 -0
  8. package/package.json +14 -2
  9. package/src/client/client.ts +138 -33
  10. package/src/client/history.ts +88 -0
  11. package/src/client/index.ts +1 -1
  12. package/src/client/request.ts +19 -0
  13. package/src/core/agents/codex-app-server/adapter.ts +31 -3
  14. package/src/core/agents/codex-sdk/adapter.ts +45 -15
  15. package/src/core/agents/codex-sdk/codex-sdk-agent.ts +25 -1
  16. package/src/core/agents/types.ts +2 -1
  17. package/src/core/index.ts +2 -0
  18. package/src/core/provision/pins.ts +2 -1
  19. package/src/core/runtime/agent-runtime.ts +53 -23
  20. package/src/core/runtime/event-processor.ts +10 -5
  21. package/src/core/runtime/event-sink.ts +45 -2
  22. package/src/core/runtime/model-lists.ts +24 -9
  23. package/src/protocol/history.ts +267 -0
  24. package/src/protocol/ids.ts +4 -5
  25. package/src/protocol/index.ts +1 -0
  26. package/src/protocol/wire.ts +82 -1
  27. package/src/server/agent-server.ts +167 -94
  28. package/src/server/bin.ts +22 -1
  29. package/src/server/history.ts +166 -0
  30. package/src/server/index.ts +1 -0
  31. package/src/server/session-store.ts +225 -0
  32. package/src/server/wire-error.ts +52 -0
  33. package/src/sync/event-log.ts +132 -0
  34. package/src/sync/fit.ts +124 -0
  35. package/src/sync/history-reader.ts +52 -0
  36. package/src/sync/history-sqlite.ts +344 -0
  37. package/src/sync/history.ts +226 -0
  38. package/src/sync/index.ts +6 -0
  39. package/src/sync/journal-sqlite.ts +353 -0
  40. package/src/sync/journal.ts +73 -0
  41. package/src/sync/node-sqlite.ts +20 -0
  42. package/src/sync/recovery.ts +112 -0
  43. package/src/sync/retry.ts +49 -0
  44. package/src/sync/schema.ts +56 -0
  45. package/src/sync/sql.ts +106 -0
  46. package/src/sync/sqlite-file.ts +38 -0
  47. package/src/sync/sqlite.ts +21 -0
  48. package/src/sync/worker.ts +259 -0
@@ -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
package/src/core/index.ts CHANGED
@@ -5,8 +5,10 @@ export { AgentRuntime, type RunSummary, type TurnAdmission } from "./runtime/age
5
5
  export { type DiagnosticHandler, type EngineDiagnostic, emitDiagnostic } from "./diagnostics.ts";
6
6
  export {
7
7
  type EventSink,
8
+ EventSinkError,
8
9
  callbackSink,
9
10
  CollectingSink,
11
+ serialSink,
10
12
  teeSink,
11
13
  } from "./runtime/event-sink.ts";
12
14
  export { EventProcessor, endedExecution } from "./runtime/event-processor.ts";
@@ -37,7 +37,8 @@ export const DEFAULT_PINS: Record<CliTool, string> = {
37
37
  claude: "0.3.288",
38
38
  // 0.160.0 re-verified 2026-10-03 against generate-ts: thread/turn/item
39
39
  // methods, token usage, approvals, and host-managed ChatGPT auth changed
40
- // only additively since 0.153.4. The GPT-6 family needs 0.159 or newer.
40
+ // only additively since 0.153.4. Of the GPT-6 family, 0.153.4 lists only
41
+ // gpt-6-astra; the rest needs 0.159 or newer.
41
42
  // Since 0.160 a thread has one writer: resuming it from a second process
42
43
  // fails until the first releases it.
43
44
  codex: "0.160.0",
@@ -29,7 +29,7 @@ import type { AgentRegistry } from "../agents/registry.ts";
29
29
  import { type DiagnosticHandler, emitDiagnostic } from "../diagnostics.ts";
30
30
  import { TurnConflictError } from "../utils/errors.ts";
31
31
  import { EventProcessor, endedExecution } from "./event-processor.ts";
32
- import type { EventSink } from "./event-sink.ts";
32
+ import { type EventSink, EventSinkError } from "./event-sink.ts";
33
33
  import { ModelLists, type ModelsQuery } from "./model-lists.ts";
34
34
 
35
35
  /** What a completed turn reports back to the caller (in addition to the streamed events). */
@@ -75,8 +75,8 @@ function canonicalJson(value: unknown): string {
75
75
  return `{${entries.join(",")}}`;
76
76
  }
77
77
 
78
- // `:` cannot appear in either UUID, so the key is collision-free.
79
- const turnKeyOf = (sessionId: string, turnId: string) => `${sessionId}:${turnId}`;
78
+ // Caller-supplied IDs need not be UUIDs; encode the tuple without delimiter collisions.
79
+ const turnKeyOf = (sessionId: string, turnId: string) => JSON.stringify([sessionId, turnId]);
80
80
  const inputKeyOf = (request: RunRequest) =>
81
81
  canonicalJson({ input: request.input, config: request.config });
82
82
 
@@ -114,14 +114,18 @@ export class AgentRuntime {
114
114
  string,
115
115
  { inputKey: string; promise: Promise<RunSummary> }
116
116
  >();
117
- /** Recently completed turns per session (bounded LRU) — retries converge on the stored summary. */
117
+ /** Recently settled turns per session (bounded LRU). Retries converge on the
118
+ * stored summary, or on the sink failure that stopped the turn mid-execution. */
118
119
  private readonly completedTurns = new Map<
119
120
  string,
120
- Map<string, { inputKey: string; summary: RunSummary }>
121
+ Map<string, { inputKey: string } & ({ summary: RunSummary } | { failure: EventSinkError })>
121
122
  >();
122
123
  /** Per-session convergence window; old turns fall out and a stale retry would re-execute. */
123
124
  private static readonly COMPLETED_TURN_MEMORY = 16;
124
125
  private shutdownPromise?: Promise<void>;
126
+ /** Aborted as shutdown begins, and part of every run's signal: a run still
127
+ * setting up then, which its harness has not yet tracked, stops too. */
128
+ private readonly stopping = new AbortController();
125
129
  private readonly modelLists = new ModelLists();
126
130
 
127
131
  constructor(
@@ -163,7 +167,8 @@ export class AgentRuntime {
163
167
  * Probe how `run()` would admit this request WITHOUT executing anything:
164
168
  * `new` (would run), `inflight`/`completed` (an identical request was
165
169
  * already admitted — a retry must converge, not re-execute). Throws
166
- * `TurnConflictError` when this turnId was admitted with DIFFERENT input.
170
+ * `TurnConflictError` when this turnId was admitted with DIFFERENT input,
171
+ * and the turn's `EventSinkError` when its durable sink stopped it.
167
172
  * Wire seats use this to quick-ack a duplicate instead of starting it.
168
173
  */
169
174
  admission(request: RunRequest): TurnAdmission {
@@ -179,6 +184,8 @@ export class AgentRuntime {
179
184
  if (done.inputKey !== inputKeyOf(request)) {
180
185
  throw new TurnConflictError(request.sessionId, request.turnId);
181
186
  }
187
+ // It may have run tools before its sink failed: never run it again.
188
+ if ("failure" in done) throw done.failure;
182
189
  return { status: "completed", summary: done.summary };
183
190
  }
184
191
  return { status: "new" };
@@ -220,13 +227,16 @@ export class AgentRuntime {
220
227
  // probe could observe the settled turn as still inflight.
221
228
  running.then(
222
229
  (summary) => {
223
- this.rememberTurn(request.sessionId, request.turnId, inputKey, summary);
230
+ this.rememberTurn(request.sessionId, request.turnId, { inputKey, summary });
224
231
  this.inflightTurns.delete(turnKey);
225
232
  this.activeRuns.delete(running);
226
233
  },
227
234
  // A rejected run is NOT memoized: it died before executing the turn
228
- // loop (registry/setup), so a retry is allowed to try again.
229
- () => {
235
+ // loop (registry/setup), so a retry is allowed to try again. Unless its
236
+ // durable sink stopped it, possibly after it had run tools.
237
+ (error) => {
238
+ if (error instanceof EventSinkError)
239
+ this.rememberTurn(request.sessionId, request.turnId, { inputKey, failure: error });
230
240
  this.inflightTurns.delete(turnKey);
231
241
  this.activeRuns.delete(running);
232
242
  },
@@ -237,15 +247,14 @@ export class AgentRuntime {
237
247
  private rememberTurn(
238
248
  sessionId: string,
239
249
  turnId: string,
240
- inputKey: string,
241
- summary: RunSummary,
250
+ settled: { inputKey: string } & ({ summary: RunSummary } | { failure: EventSinkError }),
242
251
  ): void {
243
252
  let perSession = this.completedTurns.get(sessionId);
244
253
  if (!perSession) {
245
254
  perSession = new Map();
246
255
  this.completedTurns.set(sessionId, perSession);
247
256
  }
248
- perSession.set(turnId, { inputKey, summary });
257
+ perSession.set(turnId, settled);
249
258
  while (perSession.size > AgentRuntime.COMPLETED_TURN_MEMORY) {
250
259
  const oldest = perSession.keys().next().value;
251
260
  if (oldest === undefined) break;
@@ -283,11 +292,22 @@ export class AgentRuntime {
283
292
  let applied: AppliedExecution | undefined;
284
293
 
285
294
  // Isolate sink failures: a misbehaving transport must never break the
286
- // turn's lifecycle bracketing (turn.started ... turn.ended).
295
+ // turn's lifecycle bracketing (turn.started ... turn.ended). Except a
296
+ // sink's EventSinkError: its writes are a durability boundary, so the turn
297
+ // stops rather than run on unrecorded, and every later emit fails with it.
298
+ let fatal: EventSinkError | undefined;
287
299
  const emit = async (e: LifecycleEvent) => {
300
+ if (fatal) throw fatal;
288
301
  try {
289
302
  await sink.emit(e);
290
303
  } catch (err) {
304
+ if (err instanceof EventSinkError) {
305
+ fatal = err;
306
+ // Refuses pending permissions and interrupts the harness. Whether
307
+ // the native execution stopped stays unconfirmed.
308
+ void this.cancel(config.harness, sessionId).catch(() => {});
309
+ throw err;
310
+ }
291
311
  // The turn must not fail on a misbehaving sink — but the host gets
292
312
  // to know its sink dropped an event.
293
313
  emitDiagnostic(this.options.onDiagnostic, {
@@ -328,7 +348,7 @@ export class AgentRuntime {
328
348
  toolCall: PermissionToolCall,
329
349
  permOpts?: { signal?: AbortSignal },
330
350
  ): Promise<PermissionDecision> => {
331
- if (permOpts?.signal?.aborted) return { decision: "cancel" };
351
+ if (fatal || permOpts?.signal?.aborted) return { decision: "cancel" };
332
352
  // A standing `*_always` rule from an earlier prompt in this session
333
353
  // answers without a round-trip (and without fake prompt events). The
334
354
  // rule carries the verdict only — an `updatedInput` edit belongs to the
@@ -349,20 +369,24 @@ export class AgentRuntime {
349
369
  const settle = (o: PermissionOutcome): Promise<void> | void => {
350
370
  if (!this.pendingPermissions.delete(requestId)) return;
351
371
  turnRequestIds.delete(requestId);
352
- resolveOutcome(o);
353
- // Recorded so the in-run drain sequences it before turn.ended no
354
- // matter WHO settled (broker, respondPermission, cancel) — external
355
- // callers themselves ignore the returned promise.
356
- const emitted = emit({
372
+ // The harness gets the decision once `permission.resolved` is
373
+ // written, so a durable sink records an approval before its tool
374
+ // runs and a failed write refuses it. Recorded so the in-run drain
375
+ // sequences it before turn.ended no matter WHO settled (broker,
376
+ // respondPermission, cancel) — external callers ignore the promise.
377
+ const settled = emit({
357
378
  type: "permission.resolved",
358
379
  sessionId,
359
380
  turnId,
360
381
  requestId,
361
382
  outcome: o,
362
383
  timestamp: Date.now(),
363
- });
364
- settleEmits.push(emitted);
365
- return emitted;
384
+ }).then(
385
+ () => resolveOutcome(o),
386
+ () => resolveOutcome({ outcome: "cancelled" }),
387
+ );
388
+ settleEmits.push(settled);
389
+ return settled;
366
390
  };
367
391
  this.pendingPermissions.set(requestId, { sessionId, settle });
368
392
  turnRequestIds.add(requestId);
@@ -440,7 +464,9 @@ export class AgentRuntime {
440
464
  apiKey: config.apiKey,
441
465
  disableTools: config.disableTools,
442
466
  ...(modelThinking && { modelThinking }),
443
- signal: opts.signal,
467
+ signal: opts.signal
468
+ ? AbortSignal.any([opts.signal, this.stopping.signal])
469
+ : this.stopping.signal,
444
470
  onNativeSession: (id, info) => {
445
471
  // Agents report once the native conversation is confirmed; guard against a
446
472
  // misbehaving harness re-reporting after emission. Agents always pass
@@ -571,6 +597,9 @@ export class AgentRuntime {
571
597
  .filter((pending) => pending.sessionId === sessionId)
572
598
  .map((pending) => pending.settle({ outcome: "cancelled" })),
573
599
  );
600
+ // A harness this runtime does not run (a session restored from a journal
601
+ // written with another registry) holds nothing here to release.
602
+ if (!this.registry.has(harness)) return;
574
603
  const agent = this.registry.getAgent(harness);
575
604
  if (agent.release) await agent.release(sessionId);
576
605
  else await agent.cancel(sessionId);
@@ -588,6 +617,7 @@ export class AgentRuntime {
588
617
  }
589
618
 
590
619
  private async performShutdown(drainTimeoutMs: number): Promise<void> {
620
+ this.stopping.abort();
591
621
  await Promise.all(
592
622
  [...this.pendingPermissions.values()].map((pending) =>
593
623
  pending.settle({ outcome: "cancelled" }),
@@ -131,21 +131,23 @@ export class EventProcessor {
131
131
  timestamp: Date.now(),
132
132
  };
133
133
  return;
134
- case "compacted":
134
+ case "compacted": {
135
135
  // Harnesses report compaction after the fact — a single completed
136
136
  // upsert of the positional entity (its first appearance anchors it).
137
+ const at = Date.now();
137
138
  yield {
138
139
  type: "session.compaction",
139
140
  sessionId: this.sessionId,
140
141
  turnId: this.turnId,
141
- compactionId: generateUUIDv7(),
142
+ compactionId: generateUUIDv7(at),
142
143
  status: "completed",
143
144
  ...(ev.trigger && { trigger: ev.trigger }),
144
145
  ...(ev.preTokens !== undefined && { preTokens: ev.preTokens }),
145
146
  ...(ev.postTokens !== undefined && { postTokens: ev.postTokens }),
146
- timestamp: Date.now(),
147
+ timestamp: at,
147
148
  };
148
149
  return;
150
+ }
149
151
  }
150
152
  }
151
153
 
@@ -186,7 +188,10 @@ export class EventProcessor {
186
188
  ): Generator<LifecycleEvent> {
187
189
  if (this.openMessageId) yield* this.closeMessage();
188
190
  if (role === "assistant") this.answered = true;
189
- const messageId = id ?? generateUUIDv7();
191
+ // One clock reading: a consumer that dates a message by its id agrees
192
+ // with one that dates it by this event.
193
+ const startedAt = Date.now();
194
+ const messageId = id ?? generateUUIDv7(startedAt);
190
195
  this.openMessageId = messageId;
191
196
  this.openMessageParent = parentToolCallId;
192
197
  this.currentOutputIndex = this.nextOutputIndex++;
@@ -207,7 +212,7 @@ export class EventProcessor {
207
212
  // assistant message (top-level AND parented sub-agent output) keeps it,
208
213
  // since `config.model` is the only per-turn model signal available.
209
214
  ...(role === "assistant" && this.execution?.model && { model: this.execution?.model }),
210
- timestamp: Date.now(),
215
+ timestamp: startedAt,
211
216
  };
212
217
  }
213
218
 
@@ -9,6 +9,19 @@ export interface EventSink {
9
9
  emit(event: LifecycleEvent): void | Promise<void>;
10
10
  }
11
11
 
12
+ /**
13
+ * Throw this FROM a sink whose writes are a durability boundary, such as a
14
+ * journal: the turn stops rather than run on unrecorded, its harness is
15
+ * cancelled, and a retry of the same turn converges on this failure instead of
16
+ * running it again. Anything else a sink throws is isolated (a diagnostic).
17
+ */
18
+ export class EventSinkError extends Error {
19
+ override readonly name = "EventSinkError";
20
+ constructor(cause: unknown) {
21
+ super("Required event sink failed; execution needs recovery", { cause });
22
+ }
23
+ }
24
+
12
25
  /** Build a sink from a plain callback. */
13
26
  export function callbackSink(fn: (event: LifecycleEvent) => void | Promise<void>): EventSink {
14
27
  return { emit: fn };
@@ -27,11 +40,41 @@ export class CollectingSink implements EventSink {
27
40
  }
28
41
  }
29
42
 
30
- /** Fan out to several sinks at once. */
43
+ /**
44
+ * Write one event at a time, in the order they were emitted. A permission
45
+ * response can arrive while its request is still being written (from inside
46
+ * the sink, or from another caller), so an async sink that must record the
47
+ * request before the response wraps itself in this.
48
+ */
49
+ export function serialSink(sink: EventSink): EventSink {
50
+ let tail: Promise<void> = Promise.resolve();
51
+ return {
52
+ emit(event) {
53
+ const write = tail.then(() => sink.emit(event));
54
+ tail = write.catch(() => {});
55
+ return write;
56
+ },
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Fan out to several sinks at once. Every sink gets every event, whichever
62
+ * throws; a durability failure (`EventSinkError`) outranks an ordinary one.
63
+ * A sink that answers a permission during `emit` reenters the tee: place it
64
+ * after the durable sink, or wrap the tee in `serialSink`.
65
+ */
31
66
  export function teeSink(...sinks: EventSink[]): EventSink {
32
67
  return {
33
68
  async emit(event) {
34
- for (const sink of sinks) await sink.emit(event);
69
+ const errors: unknown[] = [];
70
+ for (const sink of sinks) {
71
+ try {
72
+ await sink.emit(event);
73
+ } catch (error) {
74
+ errors.push(error);
75
+ }
76
+ }
77
+ if (errors.length) throw errors.find((error) => error instanceof EventSinkError) ?? errors[0];
35
78
  },
36
79
  };
37
80
  }
@@ -53,6 +53,22 @@ export function catalogModelList(harness: AgentHarness, fetchedAt = Date.now()):
53
53
  /** An alias (Claude `opus`, `default`) runs a model that depends on the account. */
54
54
  const isAlias = (model: ModelDescriptor) => model.resolvedId !== undefined;
55
55
 
56
+ /**
57
+ * The row of `models` for `model`: the row with that id, else a row that runs
58
+ * it as an alias. Without `aliases`, a row whose own id is an alias does not
59
+ * match by id, since another login's alias may run another model.
60
+ */
61
+ function rowFor(
62
+ models: readonly ModelDescriptor[],
63
+ model: string,
64
+ { aliases }: { aliases: boolean },
65
+ ): ModelDescriptor | undefined {
66
+ return (
67
+ models.find((row) => row.id === model && (aliases || !isAlias(row))) ??
68
+ models.find((row) => row.resolvedId === model)
69
+ );
70
+ }
71
+
56
72
  /**
57
73
  * Model lists per harness, login and folder. Concurrent reads of one key share
58
74
  * a single CLI read, and a result is stored only if no newer read started
@@ -142,7 +158,9 @@ export class ModelLists {
142
158
  * The levels `model` runs on a turn with this login and folder. First the
143
159
  * list read for that login; failing that, any login's list or the catalog,
144
160
  * but only for a model id that is not an alias: an alias such as Claude's
145
- * `opus` runs a model that depends on the account and provider.
161
+ * `opus` runs a model that depends on the account and provider. A full id
162
+ * that a list names only through an alias (Claude lists Opus 5.5 as `opus`)
163
+ * takes that row's levels, which are the levels of the model it runs.
146
164
  * `undefined` when nothing known applies.
147
165
  */
148
166
  thinkingFor(
@@ -154,22 +172,19 @@ export class ModelLists {
154
172
  );
155
173
  for (const key of own) {
156
174
  const list = this.entries.get(key)?.list;
157
- const found = list?.source === "live" && list.models.find((m) => m.id === model);
175
+ const found = list?.source === "live" && rowFor(list.models, model, { aliases: true });
158
176
  if (found) return found.thinking.levels;
159
177
  }
160
178
  let newest: { levels: readonly ThinkingLevel[]; fetchedAt: number } | undefined;
161
179
  for (const { list } of this.entries.values()) {
162
180
  if (list.harness !== query.harness || list.source !== "live") continue;
163
181
  if (newest && newest.fetchedAt >= list.fetchedAt) continue;
164
- const found = list.models.find((candidate) => candidate.id === model);
165
- if (found && !isAlias(found))
166
- newest = { levels: found.thinking.levels, fetchedAt: list.fetchedAt };
182
+ const found = rowFor(list.models, model, { aliases: false });
183
+ if (found) newest = { levels: found.thinking.levels, fetchedAt: list.fetchedAt };
167
184
  }
168
185
  if (newest) return newest.levels;
169
- const listed = CATALOG_MODELS.find(
170
- (candidate) => candidate.harness === query.harness && candidate.id === model,
171
- );
172
- return listed && !isAlias(listed) ? listed.thinking.levels : undefined;
186
+ const catalog = CATALOG_MODELS.filter((candidate) => candidate.harness === query.harness);
187
+ return rowFor(catalog, model, { aliases: false })?.thinking.levels;
173
188
  }
174
189
 
175
190
  private async read(