@yaag/runtime 0.26.0 → 0.27.0

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 (54) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent.ts +29 -17
  3. package/src/agent/fork.ts +40 -12
  4. package/src/agent/host-fork.ts +85 -0
  5. package/src/agent/spawn-definition-request.ts +38 -3
  6. package/src/agent/spawn-open.ts +43 -103
  7. package/src/agent/spawn-plan.ts +114 -0
  8. package/src/agent/spawn-request.ts +16 -2
  9. package/src/agent/spawn.ts +20 -3
  10. package/src/ask/ask-exchange-options.ts +3 -6
  11. package/src/ask/ask-exchange.ts +48 -108
  12. package/src/ask/ask-guard.ts +207 -0
  13. package/src/ask/ask-timing.ts +12 -0
  14. package/src/ask/index.ts +1 -0
  15. package/src/cassette/cassette-loader.ts +9 -20
  16. package/src/cassette/cassette-schema.ts +10 -1
  17. package/src/cassette/cassette.ts +11 -34
  18. package/src/cassette/checkpoint.ts +306 -0
  19. package/src/cassette/index.ts +16 -7
  20. package/src/cassette/parked-asks.ts +38 -0
  21. package/src/cassette/replay-divergence.ts +7 -102
  22. package/src/cassette/resume-identity.ts +5 -1
  23. package/src/cassette/resume-preconditions.ts +14 -0
  24. package/src/cassette/resume-transport.ts +26 -32
  25. package/src/cassette/run-identity.ts +109 -0
  26. package/src/cassette/session-answer.ts +51 -114
  27. package/src/cassette/spawn-identity.ts +318 -0
  28. package/src/contract/error-codes.ts +1 -0
  29. package/src/contract/index.ts +1 -0
  30. package/src/contract/spawn-options.ts +33 -2
  31. package/src/error-factories.ts +8 -0
  32. package/src/events.ts +4 -2
  33. package/src/index.ts +4 -0
  34. package/src/pi-session/append-tool-result.ts +165 -0
  35. package/src/pi-session/index.ts +30 -0
  36. package/src/pi-session/pi-session-error.ts +34 -0
  37. package/src/pi-session/session-copy.ts +113 -0
  38. package/src/pi-session/session-entries.ts +130 -0
  39. package/src/question-summary/index.ts +4 -8
  40. package/src/question-summary/summarize-question.ts +1 -1
  41. package/src/question-summary/summary-policy.ts +5 -2
  42. package/src/run/agent-questions.ts +82 -0
  43. package/src/run/answers.ts +22 -1
  44. package/src/run/host-session.ts +233 -0
  45. package/src/run/index.ts +7 -0
  46. package/src/run/run-context.ts +3 -0
  47. package/src/run/run.ts +191 -181
  48. package/src/transport/live-transport.ts +19 -0
  49. package/src/transport/pi-state.ts +10 -1
  50. package/src/transport/transport.ts +13 -9
  51. package/src/types.ts +1 -0
  52. package/src/cassette/checkpoint-flush.ts +0 -101
  53. package/src/cassette/run-checkpoint.ts +0 -272
  54. package/src/question-summary/session-copy.ts +0 -169
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The Spawn Plan: the one open request built for one spawn.
3
+ *
4
+ * The peek a Cassette-backed factory reads and every model attempt read from
5
+ * this value. Before it, the same field list was spread at three sites and
6
+ * mirrored by a fourth type, and only a comment said the three must agree.
7
+ */
8
+ import type { SpawnOrigin } from "../events.ts";
9
+ import type { ModelSelection } from "../model/index.ts";
10
+ import type { OpenOptions } from "../transport/index.ts";
11
+ import type { ResolvedSpawnOptions } from "../types.ts";
12
+ import type { ForkIdentity } from "./fork.ts";
13
+ import {
14
+ type OpenRequestOptions,
15
+ openRequest,
16
+ type RenderedSpawnOptions,
17
+ withSelection,
18
+ } from "./spawn-request.ts";
19
+
20
+ /** What one spawn knows before a model settles. */
21
+ export interface SpawnPlanInput {
22
+ readonly name: string;
23
+ readonly runName: string;
24
+ readonly cwd: string;
25
+ /** The Prompt Definition, rendered once above the plan (ADR-0064). */
26
+ readonly rendered: RenderedSpawnOptions;
27
+ /** Resolved and declared extension paths, or nothing when the Agent runs none. */
28
+ readonly extensions?: {
29
+ readonly resolvedPaths: readonly string[];
30
+ readonly declared: readonly string[];
31
+ };
32
+ /** Fork facts, present only for a fork of an Agent or of the Host Session. */
33
+ readonly fork?: ForkIdentity;
34
+ readonly parent?: string;
35
+ readonly sessionDir: string | undefined;
36
+ readonly sessionFile?: string;
37
+ }
38
+
39
+ /** One attempt's open request and the settled options the Agent records. */
40
+ export interface SpawnAttempt {
41
+ readonly request: OpenOptions;
42
+ readonly spawnOptions: ResolvedSpawnOptions;
43
+ }
44
+
45
+ /** The open requests of one spawn: the peek, and one per model attempt. */
46
+ export interface SpawnPlan {
47
+ /**
48
+ * The request a Cassette-backed factory peeks at, with the caller's unsettled
49
+ * `model`/`thinking` forms (ADR-0039).
50
+ */
51
+ peek(): OpenOptions;
52
+ /** The origin this spawn records, absent for an ordinary spawn. */
53
+ readonly origin?: SpawnOrigin;
54
+ /** The same request with one settled selection applied, and nothing else changed. */
55
+ attempt(selection: ModelSelection): SpawnAttempt;
56
+ }
57
+
58
+ /**
59
+ * The open-request fields of one fork. An Agent fork names its source; a Host
60
+ * Fork names the Host Session hash instead, and carries no `forkOf`/`forkAsks`.
61
+ */
62
+ function forkFields(
63
+ fork: ForkIdentity,
64
+ origin: SpawnOrigin | undefined,
65
+ ): Partial<OpenRequestOptions> {
66
+ if (fork.kind === "host") {
67
+ return {
68
+ origin,
69
+ ...(fork.forkSession === undefined ? {} : { forkSession: fork.forkSession }),
70
+ hostHash: fork.hostHash,
71
+ };
72
+ }
73
+ return {
74
+ origin,
75
+ forkOf: fork.forkOf,
76
+ forkAsks: fork.forkAsks,
77
+ forkSession: fork.forkSession,
78
+ ...(fork.worktreeFrom === undefined ? {} : { worktreeFrom: fork.worktreeFrom }),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Builds one spawn's plan. The base below is the single field roster of the
84
+ * open path: `peek()` and `attempt()` differ only in the spawn options they
85
+ * pass, so the peek and every attempt cannot drift apart (ADR-0013).
86
+ */
87
+ export function createSpawnPlan(input: SpawnPlanInput): SpawnPlan {
88
+ const origin: SpawnOrigin | undefined =
89
+ input.fork === undefined ? undefined : input.fork.kind === "host" ? "host-fork" : "fork";
90
+ const base = {
91
+ name: input.name,
92
+ runName: input.runName,
93
+ cwd: input.cwd,
94
+ ...(input.extensions === undefined
95
+ ? {}
96
+ : {
97
+ resolvedExtensionPaths: input.extensions.resolvedPaths,
98
+ declaredExtensions: input.extensions.declared,
99
+ }),
100
+ ...(input.fork === undefined ? {} : forkFields(input.fork, origin)),
101
+ ...(input.parent === undefined ? {} : { parent: input.parent }),
102
+ sessionDir: input.sessionDir,
103
+ ...(input.sessionFile === undefined ? {} : { sessionFile: input.sessionFile }),
104
+ } satisfies Omit<OpenRequestOptions, "spawnOptions">;
105
+
106
+ return {
107
+ ...(origin === undefined ? {} : { origin }),
108
+ peek: () => openRequest({ ...base, spawnOptions: input.rendered }),
109
+ attempt: (selection) => {
110
+ const spawnOptions = withSelection(input.rendered, selection);
111
+ return { request: openRequest({ ...base, spawnOptions }), spawnOptions };
112
+ },
113
+ };
114
+ }
@@ -1,6 +1,7 @@
1
1
  import { REQUEST_USER_INPUT_PROTOCOL } from "../ask-contract/index.ts";
2
2
  import type { SystemPromptAgent } from "../contract/index.ts";
3
3
  import { YaagError } from "../errors.ts";
4
+ import type { SpawnOrigin } from "../events.ts";
4
5
  import type { ModelSelection } from "../model/index.ts";
5
6
  import {
6
7
  assertKnownSentinels,
@@ -106,10 +107,12 @@ export interface OpenRequestOptions {
106
107
  /** Resolved parent Agent name (Parent Link); spawn identity only, never argv. */
107
108
  readonly parent?: string;
108
109
  /** Fork facts (ADR-0044); the first three are spawn identity, the rest are not. */
109
- readonly origin?: "fork";
110
+ readonly origin?: SpawnOrigin;
110
111
  readonly forkOf?: string;
111
112
  readonly forkAsks?: number;
112
113
  readonly forkSession?: string;
114
+ /** Host Session identity of a Host Fork; a launch field, never argv (ADR-0068). */
115
+ readonly hostHash?: string;
113
116
  readonly worktreeFrom?: WorktreeResolution;
114
117
  readonly sessionDir: string | undefined;
115
118
  /**
@@ -200,6 +203,7 @@ export function openRequest(options: OpenRequestOptions): OpenOptions {
200
203
  ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
201
204
  ...(options.forkAsks === undefined ? {} : { forkAsks: options.forkAsks }),
202
205
  ...(options.forkSession === undefined ? {} : { forkSession: options.forkSession }),
206
+ ...(options.hostHash === undefined ? {} : { hostHash: options.hostHash }),
203
207
  ...(options.worktreeFrom === undefined ? {} : { worktreeFrom: options.worktreeFrom }),
204
208
  ...(spawnOptions.worktree === true ? { worktree: true as const } : {}),
205
209
  ...(options.sessionDir === undefined ? {} : { sessionDir: options.sessionDir }),
@@ -213,7 +217,17 @@ export function withSelection(
213
217
  selection: ModelSelection,
214
218
  ): ResolvedSpawnOptions {
215
219
  // `parent` is dropped here as well: a Handle must never reach recorded options.
216
- const { model: _model, thinking: _thinking, parent: _parent, ...rest } = options;
220
+ // `fork` and `compact` are spawn verbs, not properties of the Agent. The spawn
221
+ // gate already strips them before the render; this line is the second wall, so
222
+ // an inherited one cannot travel into a resolved or recorded spawn request.
223
+ const {
224
+ model: _model,
225
+ thinking: _thinking,
226
+ parent: _parent,
227
+ fork: _fork,
228
+ compact: _compact,
229
+ ...rest
230
+ } = options;
217
231
  return {
218
232
  ...rest,
219
233
  ...(selection.model === undefined ? {} : { model: selection.model }),
@@ -10,6 +10,7 @@ import type { Handle, SpawnOptions, SpawnOverrides } from "../types.ts";
10
10
  import type { Agent } from "./agent.ts";
11
11
  import { type AgentDefinition, isAgentDefinition } from "./define-agent.ts";
12
12
  import { type ForkSpawner, forkRequest } from "./fork.ts";
13
+ import { hostForkRequest } from "./host-fork.ts";
13
14
  import { resolveRequest } from "./spawn-definition-request.ts";
14
15
  import { type OpenAgentContext, type OpenAgentRequest, openAgent } from "./spawn-open.ts";
15
16
  import { profiledRequest } from "./spawn-profiled.ts";
@@ -88,12 +89,28 @@ export function makeSpawn(deps: SpawnDependencies): SpawnGate {
88
89
  // The Agent Definition branch is explicit, although `resolveRequest` takes
89
90
  // a plain options object too: it states the three accepted shapes in order.
90
91
  if (isAgentDefinition(definitionOrOptions)) {
91
- return openAgent(context, resolveRequest(definitionOrOptions, overrides));
92
+ return openRequested(resolveRequest(definitionOrOptions, overrides));
92
93
  }
93
94
  if (isProfiledDefinition(definitionOrOptions)) {
94
- return openAgent(context, profiledRequest(deps.profile, definitionOrOptions, overrides));
95
+ return openRequested(profiledRequest(deps.profile, definitionOrOptions, overrides));
95
96
  }
96
- return openAgent(context, resolveRequest(definitionOrOptions, overrides));
97
+ return openRequested(resolveRequest(definitionOrOptions, overrides));
98
+ };
99
+ /**
100
+ * Opens one requested Agent, as a Host Fork when the options carry `ctx.host`.
101
+ * A Host Fork gets no default Parent Link: `parent` stays the program's to
102
+ * give. `compact` is the ADR-0043 sugar — spawn, compact, hand the Handle back.
103
+ */
104
+ const openRequested = async (request: OpenAgentRequest): Promise<Handle> => {
105
+ const host = hostForkRequest(request.spawnOptions);
106
+ const handle = await openAgent(context, {
107
+ ...request,
108
+ ...(host.fork === undefined ? {} : { fork: host.fork }),
109
+ });
110
+ if (host.compact !== undefined && host.compact !== false) {
111
+ await handle.compact(typeof host.compact === "string" ? host.compact : undefined);
112
+ }
113
+ return handle;
97
114
  };
98
115
  return {
99
116
  spawn,
@@ -5,6 +5,7 @@ import type { AgentQuestions } from "../run/index.ts";
5
5
  import type { AgentTransport, Connection, Frame } from "../transport/index.ts";
6
6
  import type { ResolvedSpawnOptions } from "../types.ts";
7
7
  import type { EffectiveAskOptions } from "./ask-hash.ts";
8
+ import type { AskTiming } from "./ask-timing.ts";
8
9
 
9
10
  /** A frame consumer whose lifetime exceeds one Ask; the Agent's AgentUsage satisfies it. */
10
11
  export interface FrameObserver {
@@ -41,12 +42,8 @@ export interface AskExchangeOptions {
41
42
  readonly modelFallback: AskModelFallback | undefined;
42
43
  /** Kills the Agent on ASK_TIMEOUT and destructive stalls — the one upward capability. */
43
44
  readonly close: () => void;
44
- /** Test-only override for the fixed duration-limit grace. */
45
- readonly askLimitGraceMs: number | undefined;
46
- /** Test-only override for the bounded settle wait after an idle abort. */
47
- readonly idleAbortSettleMs: number | undefined;
48
- /** Test-only override for the bounded wait for the Stall Watchdog probe. */
49
- readonly stallProbeSettleMs: number | undefined;
45
+ /** Test-only waits of the Ask Guard's controls; absent in production. */
46
+ readonly timing?: AskTiming;
50
47
  /** Records one parked question and raises the Run pause; absent when the Agent cannot ask. */
51
48
  readonly questions?: AgentQuestions;
52
49
  /** Marks this Ask parked, so the pause drain skips it (ADR-0022 §3, ADR-0023). */
@@ -1,7 +1,6 @@
1
1
  import type { TSchema } from "typebox";
2
2
  import type { AskOutputContract } from "../ask-contract/index.ts";
3
3
  import {
4
- AskLimit,
5
4
  LEGACY_ASK_OUTPUT_EXTRACTION_POLICY,
6
5
  REPORT_RESULT_WRAP_UP,
7
6
  ReportResultCall,
@@ -19,18 +18,13 @@ import { FrameGapTracker } from "../transport/index.ts";
19
18
  import { AskActivityTracker } from "./ask-activity.ts";
20
19
  import { type AskEndOutcome, AskEvents } from "./ask-exchange-events.ts";
21
20
  import type { AskExchangeOptions } from "./ask-exchange-options.ts";
21
+ import { AskGuard } from "./ask-guard.ts";
22
22
  import { askHash, askMarkerContext, structuredOutputContract } from "./ask-hash.ts";
23
23
  import { AskOutputSteering } from "./ask-output-steering.ts";
24
24
  import { AskOutputTail } from "./ask-output-tail.ts";
25
25
  import { awaitAskSettlement } from "./ask-settlement.ts";
26
26
  import { AskTurn } from "./ask-turn.ts";
27
- import { IdleKillSignal, IdleWatch } from "./idle-watch.ts";
28
- import {
29
- type SettlementCause,
30
- StallSignal,
31
- StallWatchdog,
32
- stallBudgetMs,
33
- } from "./stall-watchdog.ts";
27
+ import type { SettlementCause } from "./stall-watchdog.ts";
34
28
 
35
29
  export type { AskExchangeOptions } from "./ask-exchange-options.ts";
36
30
  /** Runs one Ask's transport exchange, including controls and structured-output correction. */
@@ -41,9 +35,13 @@ class AskExchange {
41
35
  readonly #options: AskExchangeOptions;
42
36
  #turn = new AskTurn();
43
37
  readonly #events: AskEvents;
44
- #limit: AskLimit | null = null;
45
- #idle: IdleWatch | null = null;
46
- #stall: StallWatchdog | null = null;
38
+ #guard: AskGuard | null = null;
39
+ /**
40
+ * The failure of an Ask with no guard: a replayed Ask has no control. It is
41
+ * per-exchange, so the reaction every settlement race registers on it dies
42
+ * with this Ask instead of accruing for the life of the process.
43
+ */
44
+ readonly #noFailure: Promise<never> = new Promise<never>(() => {});
47
45
  #gap: FrameGapTracker | null = null;
48
46
  #activity: AskActivityTracker | null = null;
49
47
  #output: AskOutputTail | null = null;
@@ -57,7 +55,6 @@ class AskExchange {
57
55
  #stalled: AskStalledOutcome | undefined;
58
56
  #invalidOutput: { readonly kind: "invalid_output"; readonly steeringEfforts: number } | undefined;
59
57
  #onSettled: () => void = () => {};
60
- #controlFailure: Promise<never> = new Promise<never>(() => {});
61
58
  #timeoutDeadline: number | undefined;
62
59
  #isParked = false;
63
60
  /** The parked `request_user_input` call of this Ask, when it parked (ADR-0021). */
@@ -68,7 +65,6 @@ class AskExchange {
68
65
  });
69
66
  #maxFrameGapMs: number | undefined;
70
67
  #cause: SettlementCause = "normal";
71
- #drainStaleFrames = false;
72
68
  constructor(options: AskExchangeOptions) {
73
69
  this.#options = options;
74
70
  this.#events = new AskEvents(options.emit, options.agent, options.index);
@@ -221,23 +217,25 @@ class AskExchange {
221
217
  // Playback reads the recorded call from the Cassette instead, so its value
222
218
  // cannot depend on how far the replayed frame stream has drained.
223
219
  this.#call = playback === undefined ? new ReportResultCall() : null;
224
- this.#limit = playback === undefined ? this.#createLimit() : null;
225
- this.#idle = playback === undefined ? this.#createIdleWatch() : null;
226
- this.#stall = playback === undefined ? this.#createStallWatchdog() : null;
220
+ // One guard per attempt: a failed attempt's trip may never settle the next
221
+ // one (ADR-0038). Playback builds none and reads the Cassette instead.
222
+ this.#guard = playback === undefined ? this.#createGuard() : null;
227
223
  this.#observe();
228
- this.#limit?.start();
229
- this.#idle?.start();
230
- this.#stall?.start();
224
+ this.#guard?.start();
231
225
  this.#gap?.start();
232
- this.#controlFailure = this.#createControlFailure();
233
226
  }
234
227
 
235
- #createLimit(): AskLimit {
236
- return new AskLimit({
228
+ #createGuard(): AskGuard {
229
+ return new AskGuard({
230
+ agent: this.#options.agent,
237
231
  ask: this.#options.ask,
238
- durationGraceMs: this.#options.askLimitGraceMs,
239
- command: async (frame) => (await this.#options.connection.command(frame)).success,
232
+ command: async (frame) => await this.#options.connection.command(frame),
233
+ terminal: () => this.#turn.terminal,
240
234
  ...(this.#reportsResult() ? { wrapUpSuffix: REPORT_RESULT_WRAP_UP } : {}),
235
+ ...(this.#options.timing === undefined ? {} : { timing: this.#options.timing }),
236
+ // The guard owns `cause` and `drainStaleFrames`; the exchange copies both
237
+ // at cleanup, so this hook only settles the turn.
238
+ onRecovered: () => this.#onSettled(),
241
239
  });
242
240
  }
243
241
 
@@ -266,44 +264,11 @@ class AskExchange {
266
264
  return recorded === LEGACY_ASK_OUTPUT_EXTRACTION_POLICY;
267
265
  }
268
266
 
269
- #createIdleWatch(): IdleWatch | null {
270
- if (this.#options.ask.idleMs === undefined) return null;
271
- return new IdleWatch({
272
- idleMs: this.#options.ask.idleMs,
273
- ...(this.#options.idleAbortSettleMs === undefined
274
- ? {}
275
- : { abortSettleMs: this.#options.idleAbortSettleMs }),
276
- command: async (frame) => (await this.#options.connection.command(frame)).success,
277
- });
278
- }
279
-
280
- #createStallWatchdog(): StallWatchdog | null {
281
- const stallMs = stallBudgetMs(this.#options.ask.stallMs);
282
- if (stallMs === null) return null;
283
- return new StallWatchdog({
284
- stallMs,
285
- ...(this.#options.stallProbeSettleMs === undefined
286
- ? {}
287
- : { probeSettleMs: this.#options.stallProbeSettleMs }),
288
- command: async (frame) => await this.#options.connection.command(frame),
289
- terminal: () => this.#turn.terminal,
290
- recover: () => {
291
- this.#cause = "recovered";
292
- // The missing `agent_settled` may still arrive: it belongs to the turn
293
- // yaag just settled by hand, never to the next Ask.
294
- this.#drainStaleFrames = true;
295
- this.#onSettled();
296
- },
297
- });
298
- }
299
-
300
267
  #observe(): void {
301
268
  this.#options.connection.observe((frame) => {
302
269
  this.#turn.observe(frame);
303
- this.#limit?.observe(frame);
270
+ this.#guard?.observe(frame);
304
271
  this.#observeQuestion(frame);
305
- if (frame.type !== "agent_settled" || this.#idle?.tripped) this.#idle?.observe(frame);
306
- this.#stall?.observe(frame);
307
272
  this.#gap?.observe();
308
273
  this.#activity?.observe(frame);
309
274
  this.#output?.observe(frame);
@@ -317,7 +282,7 @@ class AskExchange {
317
282
  this.#onSettled();
318
283
  }
319
284
  if (this.#turn.settled) {
320
- this.#stall?.settled();
285
+ this.#guard?.settled();
321
286
  this.#onSettled();
322
287
  }
323
288
  });
@@ -335,11 +300,8 @@ class AskExchange {
335
300
  if (this.#isParked) return;
336
301
  const call = readQuestionFrame(frame);
337
302
  if (call === null) return;
338
- if (this.#limit?.tripped === true) return;
303
+ if (this.#guard !== null && !this.#guard.suspend()) return;
339
304
  this.#isParked = true;
340
- this.#limit?.suspend();
341
- this.#idle?.suspend();
342
- this.#stall?.suspend();
343
305
  // Suspends the Ask's hard timeout: the wait is the human's from here.
344
306
  this.#resolveParked();
345
307
  this.#options.park?.();
@@ -350,50 +312,29 @@ class AskExchange {
350
312
  }
351
313
 
352
314
  /**
353
- * Re-opens the Question of a recorded parked Ask this resume did not answer
354
- * (ADR-0023). No live Agent exists, so nothing can park again by itself: the
355
- * Ask raises the same Question and stays open, and the Run pauses with it.
315
+ * Parks a recorded Ask this resume did not answer (ADR-0023). The Question is
316
+ * the Checkpoint's: the Run seeded the registry from its run block before the
317
+ * first Agent started, so this branch raises no Question. It marks the Ask
318
+ * parked, and the Run pauses with the same Question still open (ADR-0022).
356
319
  */
357
320
  #reopenParked(parked: NonNullable<AskPlayback["parked"]>): void {
358
321
  this.#isParked = true;
359
322
  this.#resolveParked();
360
323
  this.#options.park?.();
361
324
  // The registry's own id wins: the Question the Run advertises and the
362
- // incomplete marker the successor records must name one id (ADR-0022).
325
+ // incomplete marker the successor records must name one id (ADR-0022). An
326
+ // Agent with no ask-user capability still records a faithful marker.
363
327
  const questionId =
364
- this.#options.questions?.raise({
328
+ this.#options.questions?.park({
365
329
  agent: this.#options.agent,
366
330
  toolCallId: parked.toolCallId,
367
- question: parked.question,
368
- ...(parked.context === undefined ? {} : { context: parked.context }),
369
331
  }) ?? parked.questionId;
370
332
  this.#parkedCall = { toolCallId: parked.toolCallId, questionId };
371
333
  }
372
334
 
373
- #createControlFailure(): Promise<never> {
374
- const controls = [
375
- this.#limit?.failed,
376
- this.#idle?.failed,
377
- this.#idle?.killed,
378
- this.#stall?.failed,
379
- ].filter((promise): promise is Promise<never> => promise !== undefined);
380
- return Promise.race(controls.length === 0 ? [new Promise<never>(() => {})] : controls).catch(
381
- (error: unknown) => {
382
- if (error instanceof IdleKillSignal)
383
- throw askStalledError(this.#options.agent, error.outcome);
384
- if (error instanceof StallSignal) {
385
- this.#cause = "stalled";
386
- this.#drainStaleFrames = !error.outcome.destructive;
387
- throw askStalledError(this.#options.agent, error.outcome);
388
- }
389
- throw this.#failed(error instanceof Error ? error.message : "limit control command failed");
390
- },
391
- );
392
- }
393
-
394
335
  #armSettlement(): Promise<void> {
395
336
  this.#turn.rearm();
396
- this.#stall?.rearm();
337
+ this.#guard?.rearm();
397
338
  return new Promise<void>((resolve) => {
398
339
  this.#onSettled = resolve;
399
340
  });
@@ -460,14 +401,14 @@ class AskExchange {
460
401
  this.#timeoutDeadline === undefined
461
402
  ? undefined
462
403
  : Math.max(0, this.#timeoutDeadline - Date.now()),
463
- controlFailure: this.#controlFailure,
404
+ controlFailure: this.#guard?.failure ?? this.#noFailure,
464
405
  error: (code, message) => agentError(this.#options.agent, code, message),
465
406
  close: this.#options.close,
466
407
  parked: this.#parked,
467
408
  });
468
- this.#outcome = this.#playback?.limit ?? this.#limit?.abortOutcome ?? undefined;
409
+ this.#outcome = this.#playback?.limit ?? this.#guard?.limit ?? undefined;
469
410
  if (this.#outcome !== undefined) throw askLimitError(this.#options.agent, this.#outcome);
470
- this.#stalled = this.#playback?.stalled ?? this.#idle?.result ?? undefined;
411
+ this.#stalled = this.#playback?.stalled ?? this.#guard?.settlementStall() ?? undefined;
471
412
  if (this.#stalled !== undefined) throw askStalledError(this.#options.agent, this.#stalled);
472
413
  const failure = this.#turn.failure();
473
414
  if (failure !== null && !ignoreAbortFailure) throw this.#failed(failure);
@@ -508,8 +449,8 @@ class AskExchange {
508
449
  schema,
509
450
  maxSteers: this.#maxSteers(),
510
451
  reported: () => this.#call?.reported,
511
- beginCorrection: () => this.#limit?.enterOutputCorrection() ?? true,
512
- wrappingUp: () => this.#limit?.tripped ?? false,
452
+ beginCorrection: () => this.#guard?.beginCorrection() ?? true,
453
+ wrappingUp: () => this.#guard?.wrappingUp ?? false,
513
454
  correct: async (message) => this.#correct(message),
514
455
  abort: async () => this.#abort(),
515
456
  }).resolve();
@@ -525,8 +466,8 @@ class AskExchange {
525
466
  agent: this.#options.agent,
526
467
  schema,
527
468
  maxSteers: this.#maxSteers(),
528
- beginCorrection: () => this.#limit?.enterOutputCorrection() ?? true,
529
- wrappingUp: () => this.#limit?.tripped ?? false,
469
+ beginCorrection: () => this.#guard?.beginCorrection() ?? true,
470
+ wrappingUp: () => this.#guard?.wrappingUp ?? false,
530
471
  correct: async (message) => {
531
472
  await this.#correct(message);
532
473
  return await this.#lastAssistantText();
@@ -544,7 +485,7 @@ class AskExchange {
544
485
  if (!response.success) throw this.#failed(response.error ?? "correction prompt was rejected");
545
486
  await this.#verify(settled);
546
487
  } finally {
547
- this.#limit?.leaveOutputCorrection();
488
+ this.#guard?.leaveCorrection();
548
489
  }
549
490
  }
550
491
 
@@ -563,15 +504,14 @@ class AskExchange {
563
504
  /** Ends one attempt; the envelope stays open, so a retry can arm the next one. */
564
505
  #cleanupAttempt(): void {
565
506
  this.#maxFrameGapMs = maxGap(this.#maxFrameGapMs, this.#gap?.maxGapMs);
566
- this.#stalled ??= this.#idle?.result ?? this.#stall?.result ?? undefined;
567
- this.#limit?.cleanup();
568
- this.#idle?.cleanup();
569
- this.#stall?.cleanup();
507
+ this.#stalled ??= this.#guard?.stalled ?? undefined;
508
+ // The guard is the single writer of both while it exists; playback sets
509
+ // `#cause` itself and has no guard, so a guard-absent attempt copies nothing.
510
+ this.#cause = this.#guard?.cause ?? this.#cause;
511
+ this.#guard?.cleanup();
570
512
  this.#output?.close();
571
- if (this.#drainStaleFrames) {
572
- this.#options.connection.drainStaleTurn();
573
- this.#drainStaleFrames = false;
574
- }
513
+ // Only a live guard can leave a stale turn behind; a replayed Ask cannot.
514
+ if (this.#guard?.drainStaleFrames === true) this.#options.connection.drainStaleTurn();
575
515
  }
576
516
 
577
517
  /** Closes the Ask envelope: one `finishAsk` for the whole Ask, retries included. */