@yaag/runtime 0.25.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 (79) hide show
  1. package/package.json +2 -3
  2. package/src/agent/agent.ts +75 -23
  3. package/src/agent/ask-user-capability.ts +36 -0
  4. package/src/agent/fork.ts +40 -12
  5. package/src/agent/host-fork.ts +85 -0
  6. package/src/agent/index.ts +2 -1
  7. package/src/agent/spawn-definition-request.ts +38 -3
  8. package/src/agent/spawn-open.ts +59 -100
  9. package/src/agent/spawn-plan.ts +114 -0
  10. package/src/agent/spawn-request.ts +34 -3
  11. package/src/agent/spawn.ts +41 -5
  12. package/src/ask/ask-exchange-options.ts +8 -6
  13. package/src/ask/ask-exchange.ts +102 -97
  14. package/src/ask/ask-guard.ts +207 -0
  15. package/src/ask/ask-settlement.ts +8 -0
  16. package/src/ask/ask-timing.ts +12 -0
  17. package/src/ask/idle-watch.ts +12 -2
  18. package/src/ask/index.ts +1 -0
  19. package/src/ask/stall-watchdog.ts +13 -3
  20. package/src/ask-contract/ask-limit.ts +24 -6
  21. package/src/ask-contract/index.ts +8 -0
  22. package/src/ask-contract/request-user-input-extension.ts +105 -0
  23. package/src/ask-contract/request-user-input.ts +58 -0
  24. package/src/cassette/cassette-loader.ts +56 -18
  25. package/src/cassette/cassette-schema.ts +37 -1
  26. package/src/cassette/cassette.ts +58 -32
  27. package/src/cassette/checkpoint.ts +306 -0
  28. package/src/cassette/index.ts +25 -7
  29. package/src/cassette/parked-asks.ts +38 -0
  30. package/src/cassette/replay-divergence.ts +7 -97
  31. package/src/cassette/resume-identity.ts +5 -1
  32. package/src/cassette/resume-preconditions.ts +24 -0
  33. package/src/cassette/resume-transport.ts +112 -13
  34. package/src/cassette/run-identity.ts +109 -0
  35. package/src/cassette/session-answer.ts +100 -0
  36. package/src/cassette/spawn-identity.ts +318 -0
  37. package/src/catalog/registry-reader.ts +1 -1
  38. package/src/config/config-schema.ts +33 -0
  39. package/src/config/effective-config.ts +53 -0
  40. package/src/config/index.ts +4 -0
  41. package/src/contract/agent-policy.ts +9 -0
  42. package/src/contract/error-codes.ts +3 -2
  43. package/src/contract/index.ts +1 -0
  44. package/src/contract/spawn-options.ts +33 -2
  45. package/src/control/index.ts +2 -0
  46. package/src/control/pause-drain.ts +81 -24
  47. package/src/error-factories.ts +8 -0
  48. package/src/events.ts +10 -2
  49. package/src/index.ts +15 -1
  50. package/src/model/index.ts +1 -1
  51. package/src/pi-session/append-tool-result.ts +165 -0
  52. package/src/pi-session/index.ts +30 -0
  53. package/src/pi-session/pi-session-error.ts +34 -0
  54. package/src/pi-session/session-copy.ts +113 -0
  55. package/src/pi-session/session-entries.ts +130 -0
  56. package/src/public-api.ts +1 -0
  57. package/src/question-summary/index.ts +18 -0
  58. package/src/question-summary/summarize-question.ts +129 -0
  59. package/src/question-summary/summary-policy.ts +28 -0
  60. package/src/run/agent-questions.ts +157 -0
  61. package/src/run/answers.ts +91 -0
  62. package/src/run/host-session.ts +233 -0
  63. package/src/run/index.ts +12 -0
  64. package/src/run/pause-questions.ts +98 -0
  65. package/src/run/pause-signal.ts +32 -0
  66. package/src/run/question-id.ts +18 -0
  67. package/src/run/questions.ts +31 -0
  68. package/src/run/run-context.ts +21 -0
  69. package/src/run/run-result.ts +21 -0
  70. package/src/run/run-settlement.ts +36 -4
  71. package/src/run/run.ts +248 -139
  72. package/src/system-prompt/agent-system-prompt.ts +1 -1
  73. package/src/transport/live-transport.ts +19 -0
  74. package/src/transport/pi-state.ts +31 -5
  75. package/src/transport/tool-probe.ts +4 -0
  76. package/src/transport/transport.ts +31 -1
  77. package/src/types.ts +1 -0
  78. package/src/cassette/checkpoint-flush.ts +0 -101
  79. package/src/cassette/run-checkpoint.ts +0 -223
@@ -1,11 +1,11 @@
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,
8
7
  ReportResultSteering,
8
+ readQuestionFrame,
9
9
  resolvePlaybackAskOutput,
10
10
  resolvePlaybackReportedResult,
11
11
  } from "../ask-contract/index.ts";
@@ -13,23 +13,18 @@ import { agentError, askLimitError, askStalledError } from "../error-factories.t
13
13
  import { type AskLimitOutcome, type AskStalledOutcome, isYaagError } from "../errors.ts";
14
14
  import { retryOnModelFailure, swapModel } from "../model/index.ts";
15
15
  import { NodeTracker } from "../node/index.ts";
16
- import type { AskPlayback } from "../transport/index.ts";
16
+ import type { AskPlayback, Frame } from "../transport/index.ts";
17
17
  import { FrameGapTracker } from "../transport/index.ts";
18
18
  import { AskActivityTracker } from "./ask-activity.ts";
19
19
  import { type AskEndOutcome, AskEvents } from "./ask-exchange-events.ts";
20
20
  import type { AskExchangeOptions } from "./ask-exchange-options.ts";
21
+ import { AskGuard } from "./ask-guard.ts";
21
22
  import { askHash, askMarkerContext, structuredOutputContract } from "./ask-hash.ts";
22
23
  import { AskOutputSteering } from "./ask-output-steering.ts";
23
24
  import { AskOutputTail } from "./ask-output-tail.ts";
24
25
  import { awaitAskSettlement } from "./ask-settlement.ts";
25
26
  import { AskTurn } from "./ask-turn.ts";
26
- import { IdleKillSignal, IdleWatch } from "./idle-watch.ts";
27
- import {
28
- type SettlementCause,
29
- StallSignal,
30
- StallWatchdog,
31
- stallBudgetMs,
32
- } from "./stall-watchdog.ts";
27
+ import type { SettlementCause } from "./stall-watchdog.ts";
33
28
 
34
29
  export type { AskExchangeOptions } from "./ask-exchange-options.ts";
35
30
  /** Runs one Ask's transport exchange, including controls and structured-output correction. */
@@ -40,9 +35,13 @@ class AskExchange {
40
35
  readonly #options: AskExchangeOptions;
41
36
  #turn = new AskTurn();
42
37
  readonly #events: AskEvents;
43
- #limit: AskLimit | null = null;
44
- #idle: IdleWatch | null = null;
45
- #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>(() => {});
46
45
  #gap: FrameGapTracker | null = null;
47
46
  #activity: AskActivityTracker | null = null;
48
47
  #output: AskOutputTail | null = null;
@@ -56,11 +55,16 @@ class AskExchange {
56
55
  #stalled: AskStalledOutcome | undefined;
57
56
  #invalidOutput: { readonly kind: "invalid_output"; readonly steeringEfforts: number } | undefined;
58
57
  #onSettled: () => void = () => {};
59
- #controlFailure: Promise<never> = new Promise<never>(() => {});
60
58
  #timeoutDeadline: number | undefined;
59
+ #isParked = false;
60
+ /** The parked `request_user_input` call of this Ask, when it parked (ADR-0021). */
61
+ #parkedCall: { readonly toolCallId: string; readonly questionId: string } | undefined;
62
+ #resolveParked: () => void = () => {};
63
+ readonly #parked: Promise<void> = new Promise<void>((resolve) => {
64
+ this.#resolveParked = resolve;
65
+ });
61
66
  #maxFrameGapMs: number | undefined;
62
67
  #cause: SettlementCause = "normal";
63
- #drainStaleFrames = false;
64
68
  constructor(options: AskExchangeOptions) {
65
69
  this.#options = options;
66
70
  this.#events = new AskEvents(options.emit, options.agent, options.index);
@@ -180,6 +184,7 @@ class AskExchange {
180
184
  });
181
185
  this.#began = true;
182
186
  this.#playback = playback;
187
+ if (playback?.parked !== undefined) this.#reopenParked(playback.parked);
183
188
  // `timeoutMs` is the Ask's hard ceiling and kills the Agent (ADR-0003), so
184
189
  // it is Ask-scoped: retries share one deadline, unlike the soft limits.
185
190
  this.#timeoutDeadline = this.#deadline();
@@ -212,23 +217,25 @@ class AskExchange {
212
217
  // Playback reads the recorded call from the Cassette instead, so its value
213
218
  // cannot depend on how far the replayed frame stream has drained.
214
219
  this.#call = playback === undefined ? new ReportResultCall() : null;
215
- this.#limit = playback === undefined ? this.#createLimit() : null;
216
- this.#idle = playback === undefined ? this.#createIdleWatch() : null;
217
- 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;
218
223
  this.#observe();
219
- this.#limit?.start();
220
- this.#idle?.start();
221
- this.#stall?.start();
224
+ this.#guard?.start();
222
225
  this.#gap?.start();
223
- this.#controlFailure = this.#createControlFailure();
224
226
  }
225
227
 
226
- #createLimit(): AskLimit {
227
- return new AskLimit({
228
+ #createGuard(): AskGuard {
229
+ return new AskGuard({
230
+ agent: this.#options.agent,
228
231
  ask: this.#options.ask,
229
- durationGraceMs: this.#options.askLimitGraceMs,
230
- 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,
231
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(),
232
239
  });
233
240
  }
234
241
 
@@ -257,43 +264,11 @@ class AskExchange {
257
264
  return recorded === LEGACY_ASK_OUTPUT_EXTRACTION_POLICY;
258
265
  }
259
266
 
260
- #createIdleWatch(): IdleWatch | null {
261
- if (this.#options.ask.idleMs === undefined) return null;
262
- return new IdleWatch({
263
- idleMs: this.#options.ask.idleMs,
264
- ...(this.#options.idleAbortSettleMs === undefined
265
- ? {}
266
- : { abortSettleMs: this.#options.idleAbortSettleMs }),
267
- command: async (frame) => (await this.#options.connection.command(frame)).success,
268
- });
269
- }
270
-
271
- #createStallWatchdog(): StallWatchdog | null {
272
- const stallMs = stallBudgetMs(this.#options.ask.stallMs);
273
- if (stallMs === null) return null;
274
- return new StallWatchdog({
275
- stallMs,
276
- ...(this.#options.stallProbeSettleMs === undefined
277
- ? {}
278
- : { probeSettleMs: this.#options.stallProbeSettleMs }),
279
- command: async (frame) => await this.#options.connection.command(frame),
280
- terminal: () => this.#turn.terminal,
281
- recover: () => {
282
- this.#cause = "recovered";
283
- // The missing `agent_settled` may still arrive: it belongs to the turn
284
- // yaag just settled by hand, never to the next Ask.
285
- this.#drainStaleFrames = true;
286
- this.#onSettled();
287
- },
288
- });
289
- }
290
-
291
267
  #observe(): void {
292
268
  this.#options.connection.observe((frame) => {
293
269
  this.#turn.observe(frame);
294
- this.#limit?.observe(frame);
295
- if (frame.type !== "agent_settled" || this.#idle?.tripped) this.#idle?.observe(frame);
296
- this.#stall?.observe(frame);
270
+ this.#guard?.observe(frame);
271
+ this.#observeQuestion(frame);
297
272
  this.#gap?.observe();
298
273
  this.#activity?.observe(frame);
299
274
  this.#output?.observe(frame);
@@ -307,36 +282,59 @@ class AskExchange {
307
282
  this.#onSettled();
308
283
  }
309
284
  if (this.#turn.settled) {
310
- this.#stall?.settled();
285
+ this.#guard?.settled();
311
286
  this.#onSettled();
312
287
  }
313
288
  });
314
289
  }
315
290
 
316
- #createControlFailure(): Promise<never> {
317
- const controls = [
318
- this.#limit?.failed,
319
- this.#idle?.failed,
320
- this.#idle?.killed,
321
- this.#stall?.failed,
322
- ].filter((promise): promise is Promise<never> => promise !== undefined);
323
- return Promise.race(controls.length === 0 ? [new Promise<never>(() => {})] : controls).catch(
324
- (error: unknown) => {
325
- if (error instanceof IdleKillSignal)
326
- throw askStalledError(this.#options.agent, error.outcome);
327
- if (error instanceof StallSignal) {
328
- this.#cause = "stalled";
329
- this.#drainStaleFrames = !error.outcome.destructive;
330
- throw askStalledError(this.#options.agent, error.outcome);
331
- }
332
- throw this.#failed(error instanceof Error ? error.message : "limit control command failed");
333
- },
334
- );
291
+ /**
292
+ * Parks this Ask on one `request_user_input` call (ADR-0023).
293
+ *
294
+ * Order matters: every budget suspends before the question is raised, so no
295
+ * limit can trip between the two. First signal wins, so an Ask whose limit
296
+ * already tripped keeps its ASK_LIMIT and raises nothing. Replay never parks.
297
+ */
298
+ #observeQuestion(frame: Frame): void {
299
+ if (this.#playback !== undefined || this.#options.questions === undefined) return;
300
+ if (this.#isParked) return;
301
+ const call = readQuestionFrame(frame);
302
+ if (call === null) return;
303
+ if (this.#guard !== null && !this.#guard.suspend()) return;
304
+ this.#isParked = true;
305
+ // Suspends the Ask's hard timeout: the wait is the human's from here.
306
+ this.#resolveParked();
307
+ this.#options.park?.();
308
+ const questionId = this.#options.questions.raise({ agent: this.#options.agent, ...call });
309
+ // The incomplete-Ask marker of the artifact: this Ask has no settlement,
310
+ // and the Question it waits for names the way back (ADR-0021/0023).
311
+ this.#parkedCall = { toolCallId: call.toolCallId, questionId };
312
+ }
313
+
314
+ /**
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).
319
+ */
320
+ #reopenParked(parked: NonNullable<AskPlayback["parked"]>): void {
321
+ this.#isParked = true;
322
+ this.#resolveParked();
323
+ this.#options.park?.();
324
+ // The registry's own id wins: the Question the Run advertises and the
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.
327
+ const questionId =
328
+ this.#options.questions?.park({
329
+ agent: this.#options.agent,
330
+ toolCallId: parked.toolCallId,
331
+ }) ?? parked.questionId;
332
+ this.#parkedCall = { toolCallId: parked.toolCallId, questionId };
335
333
  }
336
334
 
337
335
  #armSettlement(): Promise<void> {
338
336
  this.#turn.rearm();
339
- this.#stall?.rearm();
337
+ this.#guard?.rearm();
340
338
  return new Promise<void>((resolve) => {
341
339
  this.#onSettled = resolve;
342
340
  });
@@ -387,7 +385,13 @@ class AskExchange {
387
385
  // A recorded Ask that never settled has no settlement frame to wait for.
388
386
  // Waiting for one would reproduce, in replay, the exact stall this
389
387
  // watchdog exists to end.
390
- if (this.#playback?.settles === false && this.#playback.recovered !== true) {
388
+ // A re-opened parked Ask has no settlement either, and must not surface
389
+ // the recorded outcome: it waits for the human, exactly as it did before.
390
+ if (
391
+ this.#playback?.settles === false &&
392
+ this.#playback.recovered !== true &&
393
+ this.#playback.parked === undefined
394
+ ) {
391
395
  throw this.#recordedOutcome();
392
396
  }
393
397
  await awaitAskSettlement({
@@ -397,13 +401,14 @@ class AskExchange {
397
401
  this.#timeoutDeadline === undefined
398
402
  ? undefined
399
403
  : Math.max(0, this.#timeoutDeadline - Date.now()),
400
- controlFailure: this.#controlFailure,
404
+ controlFailure: this.#guard?.failure ?? this.#noFailure,
401
405
  error: (code, message) => agentError(this.#options.agent, code, message),
402
406
  close: this.#options.close,
407
+ parked: this.#parked,
403
408
  });
404
- this.#outcome = this.#playback?.limit ?? this.#limit?.abortOutcome ?? undefined;
409
+ this.#outcome = this.#playback?.limit ?? this.#guard?.limit ?? undefined;
405
410
  if (this.#outcome !== undefined) throw askLimitError(this.#options.agent, this.#outcome);
406
- this.#stalled = this.#playback?.stalled ?? this.#idle?.result ?? undefined;
411
+ this.#stalled = this.#playback?.stalled ?? this.#guard?.settlementStall() ?? undefined;
407
412
  if (this.#stalled !== undefined) throw askStalledError(this.#options.agent, this.#stalled);
408
413
  const failure = this.#turn.failure();
409
414
  if (failure !== null && !ignoreAbortFailure) throw this.#failed(failure);
@@ -444,8 +449,8 @@ class AskExchange {
444
449
  schema,
445
450
  maxSteers: this.#maxSteers(),
446
451
  reported: () => this.#call?.reported,
447
- beginCorrection: () => this.#limit?.enterOutputCorrection() ?? true,
448
- wrappingUp: () => this.#limit?.tripped ?? false,
452
+ beginCorrection: () => this.#guard?.beginCorrection() ?? true,
453
+ wrappingUp: () => this.#guard?.wrappingUp ?? false,
449
454
  correct: async (message) => this.#correct(message),
450
455
  abort: async () => this.#abort(),
451
456
  }).resolve();
@@ -461,8 +466,8 @@ class AskExchange {
461
466
  agent: this.#options.agent,
462
467
  schema,
463
468
  maxSteers: this.#maxSteers(),
464
- beginCorrection: () => this.#limit?.enterOutputCorrection() ?? true,
465
- wrappingUp: () => this.#limit?.tripped ?? false,
469
+ beginCorrection: () => this.#guard?.beginCorrection() ?? true,
470
+ wrappingUp: () => this.#guard?.wrappingUp ?? false,
466
471
  correct: async (message) => {
467
472
  await this.#correct(message);
468
473
  return await this.#lastAssistantText();
@@ -480,7 +485,7 @@ class AskExchange {
480
485
  if (!response.success) throw this.#failed(response.error ?? "correction prompt was rejected");
481
486
  await this.#verify(settled);
482
487
  } finally {
483
- this.#limit?.leaveOutputCorrection();
488
+ this.#guard?.leaveCorrection();
484
489
  }
485
490
  }
486
491
 
@@ -499,15 +504,14 @@ class AskExchange {
499
504
  /** Ends one attempt; the envelope stays open, so a retry can arm the next one. */
500
505
  #cleanupAttempt(): void {
501
506
  this.#maxFrameGapMs = maxGap(this.#maxFrameGapMs, this.#gap?.maxGapMs);
502
- this.#stalled ??= this.#idle?.result ?? this.#stall?.result ?? undefined;
503
- this.#limit?.cleanup();
504
- this.#idle?.cleanup();
505
- 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();
506
512
  this.#output?.close();
507
- if (this.#drainStaleFrames) {
508
- this.#options.connection.drainStaleTurn();
509
- this.#drainStaleFrames = false;
510
- }
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();
511
515
  }
512
516
 
513
517
  /** Closes the Ask envelope: one `finishAsk` for the whole Ask, retries included. */
@@ -520,6 +524,7 @@ class AskExchange {
520
524
  ...(this.#stalled === undefined ? {} : { stalled: this.#stalled }),
521
525
  ...(this.#invalidOutput === undefined ? {} : { invalidOutput: this.#invalidOutput }),
522
526
  ...(this.#cause === "recovered" ? { recovered: true as const } : {}),
527
+ ...(this.#parkedCall === undefined ? {} : { parked: this.#parkedCall }),
523
528
  });
524
529
  } catch {
525
530
  // Recording must not hide the Ask outcome it was observing.
@@ -0,0 +1,207 @@
1
+ import { AskLimit } from "../ask-contract/index.ts";
2
+ import { agentError, askStalledError } from "../error-factories.ts";
3
+ import type { AskLimitOutcome, AskStalledOutcome } from "../errors.ts";
4
+ import type { CommandResponse, Frame } from "../transport/index.ts";
5
+ import type { EffectiveAskOptions } from "./ask-hash.ts";
6
+ import type { AskTiming } from "./ask-timing.ts";
7
+ import { IdleKillSignal, IdleWatch } from "./idle-watch.ts";
8
+ import {
9
+ type SettlementCause,
10
+ StallSignal,
11
+ StallWatchdog,
12
+ stallBudgetMs,
13
+ } from "./stall-watchdog.ts";
14
+
15
+ export interface AskGuardOptions {
16
+ /** The Agent this Ask runs on; names every error the guard reports. */
17
+ readonly agent: string;
18
+ readonly ask: EffectiveAskOptions;
19
+ /** Sends one control frame to the Agent and resolves with its response. */
20
+ readonly command: (frame: Frame) => Promise<CommandResponse>;
21
+ /** True when this Ask already observed a terminal assistant `message_end`. */
22
+ readonly terminal: () => boolean;
23
+ /** One sentence appended to the wrap-up, present when the Ask reports a result. */
24
+ readonly wrapUpSuffix?: string;
25
+ /** Test-only waits of the controls; absent in production. */
26
+ readonly timing?: AskTiming;
27
+ /** Called once when the Stall Watchdog recovered, so the Ask settles by hand. */
28
+ readonly onRecovered: () => void;
29
+ }
30
+
31
+ /**
32
+ * Every control of one Ask attempt, behind one object (ADR-0020, ADR-0038).
33
+ *
34
+ * The guard owns the Ask limit, the idle watch and the Stall Watchdog. It is a
35
+ * composition unit only: it adds no policy and ranks nothing. "First trip wins"
36
+ * stays a race between the controls' own failure promises, and the guard
37
+ * translates whichever signal wins into a `YaagError`. One guard serves one
38
+ * attempt and is never reused.
39
+ */
40
+ export class AskGuard {
41
+ readonly #agent: string;
42
+ readonly #limit: AskLimit;
43
+ readonly #idle: IdleWatch | null;
44
+ readonly #stall: StallWatchdog | null;
45
+ readonly #failure: Promise<never>;
46
+ #cause: SettlementCause = "normal";
47
+ #drain = false;
48
+
49
+ constructor(options: AskGuardOptions) {
50
+ this.#agent = options.agent;
51
+ const command = options.command;
52
+ this.#limit = new AskLimit({
53
+ ask: options.ask,
54
+ durationGraceMs: options.timing?.askLimitGraceMs,
55
+ command: async (frame) => (await command(frame)).success,
56
+ ...(options.wrapUpSuffix === undefined ? {} : { wrapUpSuffix: options.wrapUpSuffix }),
57
+ });
58
+ this.#idle =
59
+ options.ask.idleMs === undefined
60
+ ? null
61
+ : new IdleWatch({
62
+ idleMs: options.ask.idleMs,
63
+ ...(options.timing?.idleAbortSettleMs === undefined
64
+ ? {}
65
+ : { abortSettleMs: options.timing.idleAbortSettleMs }),
66
+ command: async (frame) => (await command(frame)).success,
67
+ });
68
+ const stallMs = stallBudgetMs(options.ask.stallMs);
69
+ this.#stall =
70
+ stallMs === null
71
+ ? null
72
+ : new StallWatchdog({
73
+ stallMs,
74
+ ...(options.timing?.stallProbeSettleMs === undefined
75
+ ? {}
76
+ : { probeSettleMs: options.timing.stallProbeSettleMs }),
77
+ command,
78
+ terminal: options.terminal,
79
+ recover: () => {
80
+ this.#cause = "recovered";
81
+ // The missing `agent_settled` may still arrive: it belongs to the
82
+ // turn yaag just settled by hand, never to the next Ask.
83
+ this.#drain = true;
84
+ options.onRecovered();
85
+ },
86
+ });
87
+ this.#failure = this.#raceFailures();
88
+ // A control may trip before the Ask starts awaiting the race.
89
+ void this.#failure.catch(() => {});
90
+ }
91
+
92
+ /** Arms every control it holds. */
93
+ start(): void {
94
+ this.#limit.start();
95
+ this.#idle?.start();
96
+ this.#stall?.start();
97
+ }
98
+
99
+ /** Feeds one frame to every control. */
100
+ observe(frame: Frame): void {
101
+ this.#limit.observe(frame);
102
+ // The idle watch only cares about `agent_settled` once it escalated: before
103
+ // that the frame is the settlement the Ask itself is waiting for.
104
+ if (frame.type !== "agent_settled" || this.#idle?.tripped === true) this.#idle?.observe(frame);
105
+ this.#stall?.observe(frame);
106
+ }
107
+
108
+ /** The turn settled normally. */
109
+ settled(): void {
110
+ this.#stall?.settled();
111
+ }
112
+
113
+ /**
114
+ * Parks every control before an Agent Question is raised (ADR-0023), so no
115
+ * control can trip between the park and the Question. Returns false when a
116
+ * limit already tripped: first signal wins and the Ask raises nothing.
117
+ */
118
+ suspend(): boolean {
119
+ if (this.#limit.tripped) return false;
120
+ this.#limit.suspend();
121
+ this.#idle?.suspend();
122
+ this.#stall?.suspend();
123
+ return true;
124
+ }
125
+
126
+ /** Opens a new settlement window after a correction steer. */
127
+ rearm(): void {
128
+ this.#stall?.rearm();
129
+ }
130
+
131
+ /** Stops every timer. Idempotent. */
132
+ cleanup(): void {
133
+ this.#limit.cleanup();
134
+ this.#idle?.cleanup();
135
+ this.#stall?.cleanup();
136
+ }
137
+
138
+ /** Rejects with a `YaagError` when the first control trips destructively. */
139
+ get failure(): Promise<never> {
140
+ return this.#failure;
141
+ }
142
+
143
+ /** How this Ask settled, as reported in its `ask_end` Lifecycle Event. */
144
+ get cause(): SettlementCause {
145
+ return this.#cause;
146
+ }
147
+
148
+ /** True when the connection must drain a stale turn at cleanup. */
149
+ get drainStaleFrames(): boolean {
150
+ return this.#drain;
151
+ }
152
+
153
+ /** The limit outcome, once a limit aborted this Ask. */
154
+ get limit(): AskLimitOutcome | null {
155
+ return this.#limit.abortOutcome;
156
+ }
157
+
158
+ /** The recording view of a stall: whichever control ended the Ask. */
159
+ get stalled(): AskStalledOutcome | null {
160
+ return this.#idle?.result ?? this.#stall?.result ?? null;
161
+ }
162
+
163
+ /**
164
+ * The post-settlement check, which is the idle watch alone. A stall reaches
165
+ * the Ask through {@link failure}; reading it here too would let a stall that
166
+ * resolves together with settlement be thrown from the settled path.
167
+ */
168
+ settlementStall(): AskStalledOutcome | null {
169
+ return this.#idle?.result ?? null;
170
+ }
171
+
172
+ /** Opens one output-correction pass under the limit's budget. */
173
+ beginCorrection(): boolean {
174
+ return this.#limit.enterOutputCorrection();
175
+ }
176
+
177
+ leaveCorrection(): void {
178
+ this.#limit.leaveOutputCorrection();
179
+ }
180
+
181
+ /** True once a limit tripped and the Ask is wrapping up. */
182
+ get wrappingUp(): boolean {
183
+ return this.#limit.tripped;
184
+ }
185
+
186
+ #raceFailures(): Promise<never> {
187
+ const controls = [
188
+ this.#limit.failed,
189
+ this.#idle?.failed,
190
+ this.#idle?.killed,
191
+ this.#stall?.failed,
192
+ ].filter((promise): promise is Promise<never> => promise !== undefined);
193
+ return Promise.race(controls).catch((error: unknown) => {
194
+ if (error instanceof IdleKillSignal) throw askStalledError(this.#agent, error.outcome);
195
+ if (error instanceof StallSignal) {
196
+ this.#cause = "stalled";
197
+ this.#drain = !error.outcome.destructive;
198
+ throw askStalledError(this.#agent, error.outcome);
199
+ }
200
+ throw agentError(
201
+ this.#agent,
202
+ "AGENT_FAILED",
203
+ error instanceof Error ? error.message : "limit control command failed",
204
+ );
205
+ });
206
+ }
207
+ }
@@ -7,6 +7,11 @@ export interface AwaitAskSettlementOptions {
7
7
  readonly controlFailure: Promise<never>;
8
8
  readonly error: (code: YaagError["code"], message: string) => YaagError;
9
9
  readonly close: () => void;
10
+ /**
11
+ * Resolves when the Ask parks on a user question; the Ask's hard timeout
12
+ * suspends, because the wait is the human's, not the Agent's (ADR-0023).
13
+ */
14
+ readonly parked?: Promise<void>;
10
15
  }
11
16
 
12
17
  /** Waits for one effort's settlement while preserving the Ask-wide timeout and death semantics. */
@@ -24,6 +29,9 @@ export async function awaitAskSettlement(options: AwaitAskSettlementOptions): Pr
24
29
  options.timeoutMs,
25
30
  );
26
31
  });
32
+ void options.parked?.then(() => {
33
+ clearTimeout(timer);
34
+ });
27
35
  try {
28
36
  await Promise.race([options.settled, death, expiry, options.controlFailure]);
29
37
  } catch (error) {
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Test-only waits of the Ask Guard's controls; production passes none and every
3
+ * control applies its own fixed constant.
4
+ */
5
+ export interface AskTiming {
6
+ /** Test-only override for the fixed duration-limit grace. */
7
+ readonly askLimitGraceMs?: number;
8
+ /** Test-only override for the bounded settle wait after an idle abort. */
9
+ readonly idleAbortSettleMs?: number;
10
+ /** Test-only override for the bounded wait for the Stall Watchdog probe. */
11
+ readonly stallProbeSettleMs?: number;
12
+ }
@@ -43,6 +43,7 @@ export class IdleWatch {
43
43
  #killTimer: ReturnType<typeof setTimeout> | undefined;
44
44
  #tripped = false;
45
45
  #done = false;
46
+ #suspended = false;
46
47
  #result: AskStalledOutcome | null = null;
47
48
 
48
49
  constructor(options: IdleWatchOptions) {
@@ -67,7 +68,7 @@ export class IdleWatch {
67
68
 
68
69
  /** Resets the silence timer; after escalation, watches for `agent_settled`. */
69
70
  observe(frame: Frame): void {
70
- if (this.#done) return;
71
+ if (this.#done || this.#suspended) return;
71
72
  if (this.#tripped) {
72
73
  if (frame.type === "agent_settled") this.#finish(false);
73
74
  return;
@@ -86,6 +87,15 @@ export class IdleWatch {
86
87
  this.cleanup();
87
88
  }
88
89
 
90
+ /**
91
+ * Suspends the watch while the Ask parks on a user question (ADR-0023). The
92
+ * silence that follows is the human thinking, not a hung Agent.
93
+ */
94
+ suspend(): void {
95
+ this.#suspended = true;
96
+ this.cleanup();
97
+ }
98
+
89
99
  /** Cancels timers on every other Ask exit path. Idempotent. */
90
100
  cleanup(): void {
91
101
  clearTimeout(this.#idleTimer);
@@ -120,7 +130,7 @@ export class IdleWatch {
120
130
  }
121
131
 
122
132
  #trip(): void {
123
- if (this.#done || this.#tripped) return;
133
+ if (this.#done || this.#suspended || this.#tripped) return;
124
134
  this.#tripped = true;
125
135
  clearTimeout(this.#idleTimer);
126
136
  this.#idleTimer = undefined;
package/src/ask/index.ts CHANGED
@@ -8,5 +8,6 @@ export { exchangeAsk } from "./ask-exchange.ts";
8
8
  export type { AskModelFallback } from "./ask-exchange-options.ts";
9
9
  export { askHash, askMarkerContext, type EffectiveAskOptions } from "./ask-hash.ts";
10
10
  export { AskOutputTail } from "./ask-output-tail.ts";
11
+ export type { AskTiming } from "./ask-timing.ts";
11
12
  export { AskTurn } from "./ask-turn.ts";
12
13
  export type { SettlementCause } from "./stall-watchdog.ts";
@@ -63,6 +63,7 @@ export class StallWatchdog {
63
63
  #probeTimer: ReturnType<typeof setTimeout> | undefined;
64
64
  #tripped = false;
65
65
  #done = false;
66
+ #suspended = false;
66
67
  #cause: SettlementCause = "normal";
67
68
  #result: AskStalledOutcome | null = null;
68
69
 
@@ -86,7 +87,7 @@ export class StallWatchdog {
86
87
 
87
88
  /** Resets the silence timer. Frames that arrive after the probe are ignored. */
88
89
  observe(_frame: Frame): void {
89
- if (this.#done || this.#tripped) return;
90
+ if (this.#done || this.#suspended || this.#tripped) return;
90
91
  this.#arm();
91
92
  }
92
93
 
@@ -100,9 +101,18 @@ export class StallWatchdog {
100
101
  this.cleanup();
101
102
  }
102
103
 
104
+ /**
105
+ * Suspends the watchdog while the Ask parks on a user question (ADR-0023).
106
+ * The Agent is silent because it waits for the human, which is not a stall.
107
+ */
108
+ suspend(): void {
109
+ this.#suspended = true;
110
+ this.cleanup();
111
+ }
112
+
103
113
  /** Re-arms the timer for a further effort in the same Ask. Inert after a trip. */
104
114
  rearm(): void {
105
- if (this.#done || this.#tripped) return;
115
+ if (this.#done || this.#suspended || this.#tripped) return;
106
116
  this.#arm();
107
117
  }
108
118
 
@@ -135,7 +145,7 @@ export class StallWatchdog {
135
145
  }
136
146
 
137
147
  #trip(): void {
138
- if (this.#done || this.#tripped) return;
148
+ if (this.#done || this.#suspended || this.#tripped) return;
139
149
  this.#tripped = true;
140
150
  clearTimeout(this.#stallTimer);
141
151
  this.#stallTimer = undefined;