@yaag/runtime 0.24.0 → 0.26.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 (62) hide show
  1. package/package.json +2 -3
  2. package/src/agent/agent.ts +46 -6
  3. package/src/agent/ask-user-capability.ts +36 -0
  4. package/src/agent/index.ts +3 -1
  5. package/src/agent/spawn-open.ts +24 -5
  6. package/src/agent/spawn-request.ts +18 -1
  7. package/src/agent/spawn.ts +31 -9
  8. package/src/agent/spawnable-definition.ts +9 -0
  9. package/src/ask/ask-exchange-options.ts +5 -0
  10. package/src/ask/ask-exchange.ts +67 -2
  11. package/src/ask/ask-settlement.ts +8 -0
  12. package/src/ask/idle-watch.ts +12 -2
  13. package/src/ask/stall-watchdog.ts +13 -3
  14. package/src/ask-contract/ask-limit.ts +24 -6
  15. package/src/ask-contract/index.ts +8 -0
  16. package/src/ask-contract/request-user-input-extension.ts +105 -0
  17. package/src/ask-contract/request-user-input.ts +58 -0
  18. package/src/cassette/cassette-loader.ts +50 -1
  19. package/src/cassette/cassette-schema.ts +27 -0
  20. package/src/cassette/cassette.ts +49 -0
  21. package/src/cassette/index.ts +10 -1
  22. package/src/cassette/replay-divergence.ts +5 -0
  23. package/src/cassette/resume-preconditions.ts +10 -0
  24. package/src/cassette/resume-transport.ts +111 -6
  25. package/src/cassette/run-checkpoint.ts +52 -3
  26. package/src/cassette/session-answer.ts +163 -0
  27. package/src/catalog/index.ts +5 -3
  28. package/src/catalog/registry-reader.ts +1 -1
  29. package/src/catalog/resolve.ts +184 -0
  30. package/src/config/config-schema.ts +33 -0
  31. package/src/config/effective-config.ts +53 -0
  32. package/src/config/index.ts +4 -0
  33. package/src/contract/agent-policy.ts +9 -0
  34. package/src/contract/catalog-resolve.ts +33 -0
  35. package/src/contract/error-codes.ts +5 -2
  36. package/src/contract/index.ts +10 -2
  37. package/src/control/index.ts +2 -0
  38. package/src/control/pause-drain.ts +81 -24
  39. package/src/errors.ts +8 -2
  40. package/src/events.ts +6 -0
  41. package/src/index.ts +18 -2
  42. package/src/model/index.ts +1 -1
  43. package/src/public-api.ts +7 -0
  44. package/src/question-summary/index.ts +22 -0
  45. package/src/question-summary/session-copy.ts +169 -0
  46. package/src/question-summary/summarize-question.ts +129 -0
  47. package/src/question-summary/summary-policy.ts +25 -0
  48. package/src/run/agent-questions.ts +75 -0
  49. package/src/run/answers.ts +70 -0
  50. package/src/run/index.ts +5 -0
  51. package/src/run/pause-questions.ts +98 -0
  52. package/src/run/pause-signal.ts +32 -0
  53. package/src/run/question-id.ts +18 -0
  54. package/src/run/questions.ts +31 -0
  55. package/src/run/run-context.ts +26 -1
  56. package/src/run/run-result.ts +21 -0
  57. package/src/run/run-settlement.ts +36 -4
  58. package/src/run/run.ts +119 -20
  59. package/src/system-prompt/agent-system-prompt.ts +1 -1
  60. package/src/transport/pi-state.ts +21 -4
  61. package/src/transport/tool-probe.ts +4 -0
  62. package/src/transport/transport.ts +26 -0
@@ -1,8 +1,14 @@
1
1
  // `../agent/define-agent.ts` is a deep import on purpose: the author
2
2
  // declaration tree must not pull the `agent/` barrel (ADR-0045).
3
3
  import type { AgentDefinition } from "../agent/define-agent.ts";
4
- import type { Handle, SpawnOptions, SpawnOverrides } from "../contract/index.ts";
4
+ import type {
5
+ Handle,
6
+ SpawnableDefinition,
7
+ SpawnOptions,
8
+ SpawnOverrides,
9
+ } from "../contract/index.ts";
5
10
  import type { ProfiledDefinition } from "../profile/use-profile.ts";
11
+ import type { AskUserOptions } from "./questions.ts";
6
12
 
7
13
  /** What an Orchestration Program is handed. */
8
14
  export interface RunContext<Args = unknown> {
@@ -20,6 +26,25 @@ export interface RunContext<Args = unknown> {
20
26
  spawn(options?: SpawnOptions): Promise<Handle>;
21
27
  spawn(definition: AgentDefinition, overrides?: SpawnOverrides): Promise<Handle>;
22
28
  spawn(profiled: ProfiledDefinition, overrides?: SpawnOverrides): Promise<Handle>;
29
+ /** Last on purpose: a union-typed value, e.g. what a Catalog Resolve gave back (ADR-0053). */
30
+ spawn(definition: SpawnableDefinition, overrides?: SpawnOverrides): Promise<Handle>;
31
+ /**
32
+ * Asks the user one question and pauses the Run (ADR-0022).
33
+ *
34
+ * The call never resolves in this Run: it records the question, then unwinds
35
+ * the program with the pause control signal. The Run drains, publishes a
36
+ * Checkpoint, and ends with the `paused` outcome. A resume answers the
37
+ * question (ticket 05). Two questions must not claim one id: give each one a
38
+ * `key`, or `PAUSE_REFUSED` is thrown.
39
+ */
40
+ askUser(question: string, options?: AskUserOptions): Promise<string>;
41
+ /**
42
+ * Pauses the Run without a question (ADR-0022).
43
+ *
44
+ * The call never resolves in this Run, the same way `askUser` does not. The
45
+ * first `reason` is the reason the Run reports.
46
+ */
47
+ pause(reason?: string): Promise<void>;
23
48
  /**
24
49
  * The Profile this Run activated (ADR-0052). Defined when the program
25
50
  * declares Profiles, undefined otherwise.
@@ -0,0 +1,21 @@
1
+ /**
2
+ * What one Run gives back (ADR-0022). A completed Run carries the program's
3
+ * value; a paused Run carries what it needs to be resumed. A failed Run and a
4
+ * stopped Run keep rejecting with a `YaagError`, so no caller has to read an
5
+ * outcome to know that something went wrong.
6
+ */
7
+ import type { Question } from "./questions.ts";
8
+
9
+ export type RunResult<Result> =
10
+ | { readonly outcome: "completed"; readonly value: Result }
11
+ | {
12
+ readonly outcome: "paused";
13
+ /** Every question the program asked its user. */
14
+ readonly questions: readonly Question[];
15
+ /** The reason the first `ctx.pause` gave, when it gave one. */
16
+ readonly reason?: string;
17
+ /** Path of the published Checkpoint the Run resumes from (ADR-0021). */
18
+ readonly checkpoint: string;
19
+ /** Ask rejections observed during the drain; they never change the outcome. */
20
+ readonly warnings?: readonly string[];
21
+ };
@@ -1,11 +1,17 @@
1
1
  import type { ControlRequests, DrainableAgent } from "../control/index.ts";
2
2
  import { drainForPause } from "../control/index.ts";
3
+ import { isPauseSignal } from "./pause-signal.ts";
3
4
 
4
5
  /** How one Run settled, before it reaps its Agents and publishes its Checkpoint. */
5
6
  export type RunSettlement<Result> =
6
7
  | { readonly outcome: "completed"; readonly value: Result }
7
8
  | { readonly outcome: "failed"; readonly error: unknown }
8
- | { readonly outcome: "paused"; readonly cutShort: readonly string[] }
9
+ | {
10
+ readonly outcome: "paused";
11
+ readonly cutShort: readonly string[];
12
+ /** Ask rejections observed during the drain; they never change the outcome. */
13
+ readonly warnings: readonly string[];
14
+ }
9
15
  | { readonly outcome: "stopped" };
10
16
 
11
17
  export interface RunSettlementOptions<Result> {
@@ -17,6 +23,8 @@ export interface RunSettlementOptions<Result> {
17
23
  readonly agents: readonly DrainableAgent[];
18
24
  /** Closes Ask and spawn admission; the drain calls it before its first steer. */
19
25
  readonly closeAdmission: () => void;
26
+ /** Resolves at the first question an Agent asked its human (ADR-0023). */
27
+ readonly questionRaised: Promise<void>;
20
28
  }
21
29
 
22
30
  /**
@@ -29,6 +37,10 @@ export interface RunSettlementOptions<Result> {
29
37
  * absorbed: the rejection is a consequence of the closed admission or the
30
38
  * cut-short Ask, so the Run stays `paused`. The rule reads a settlement latch
31
39
  * rather than error codes, so no failure vocabulary decides an outcome.
40
+ *
41
+ * A question an Agent asked its human is a third entrant: the program never
42
+ * sees it, because the program awaits an `ask()` the parked turn never settles,
43
+ * so the pause can only arrive as its own signal (ADR-0023).
32
44
  */
33
45
  export async function settleRun<Result>(
34
46
  options: RunSettlementOptions<Result>,
@@ -55,8 +67,28 @@ export async function settleRun<Result>(
55
67
  () => "program" as const,
56
68
  ),
57
69
  options.requests.first.then(() => "control" as const),
70
+ options.questionRaised.then(() => "question" as const),
58
71
  ]);
59
- if (first === "program") return settledLatch(latch.settled);
72
+ // One drain policy for both natural pauses: nothing is cut short, and the
73
+ // settlement latch is never read, because the program is still running.
74
+ const naturalDrain = async (): Promise<RunSettlement<Result>> => {
75
+ const drained = await drainForPause({
76
+ agents: options.agents,
77
+ grace: { kind: "natural" },
78
+ closeAdmission: options.closeAdmission,
79
+ stopped: options.requests.stopped,
80
+ });
81
+ if (drained.kind === "stopped") return { outcome: "stopped" };
82
+ return { outcome: "paused", cutShort: drained.cutShort, warnings: drained.warnings };
83
+ };
84
+ if (first === "question") return naturalDrain();
85
+ if (first === "program") {
86
+ const settled = settledLatch(latch.settled);
87
+ // The program asked its user a question (ADR-0022). It is a pause, not a
88
+ // failure, so the Run drains naturally: no wrap-up steer, and no deadline.
89
+ if (settled.outcome === "failed" && isPauseSignal(settled.error)) return naturalDrain();
90
+ return settled;
91
+ }
60
92
  const control = await options.requests.first;
61
93
  if (control.kind === "stop") {
62
94
  options.closeAdmission();
@@ -64,14 +96,14 @@ export async function settleRun<Result>(
64
96
  }
65
97
  const drained = await drainForPause({
66
98
  agents: options.agents,
67
- deadlineMs: control.deadlineMs,
99
+ grace: { kind: "bounded", deadlineMs: control.deadlineMs },
68
100
  closeAdmission: options.closeAdmission,
69
101
  stopped: options.requests.stopped,
70
102
  });
71
103
  const settled = latch.settled;
72
104
  if (settled !== null && settled.outcome === "completed") return settled;
73
105
  if (drained.kind === "stopped") return { outcome: "stopped" };
74
- return { outcome: "paused", cutShort: drained.cutShort };
106
+ return { outcome: "paused", cutShort: drained.cutShort, warnings: drained.warnings };
75
107
  }
76
108
 
77
109
  /**
package/src/run/run.ts CHANGED
@@ -25,14 +25,20 @@ import {
25
25
  replayTransport,
26
26
  resolveCheckpointDirectory,
27
27
  resolveRunIdentity,
28
+ restoreSessionAnswers,
28
29
  resumeTransport,
29
30
  writeRecordingDiagnostic,
30
31
  } from "../cassette/index.ts";
31
- import { type EffectiveConfig, EMPTY_EFFECTIVE_CONFIG } from "../config/index.ts";
32
+ import {
33
+ type EffectiveConfig,
34
+ EMPTY_EFFECTIVE_CONFIG,
35
+ questionSummaryOf,
36
+ } from "../config/index.ts";
32
37
  import { controlRequests, createAskAdmission, type RunController } from "../control/index.ts";
33
38
  import { YaagError } from "../errors.ts";
34
39
  import type { EventSink, LifecycleEvent, RunOutcome, StampedEventSink } from "../events.ts";
35
40
  import { selectProfile } from "../profile/index.ts";
41
+ import { summarizeQuestions } from "../question-summary/index.ts";
36
42
  import { applyEvent, initialSummary, type RunSummary } from "../summary/index.ts";
37
43
  import type { TransportFactory } from "../transport/index.ts";
38
44
  import {
@@ -42,9 +48,13 @@ import {
42
48
  skillRestrictionTransport,
43
49
  worktreeTransport,
44
50
  } from "../transport/index.ts";
51
+ import { createAgentQuestions } from "./agent-questions.ts";
52
+ import { type AnswerLedger, createAnswerLedger, emptyAnswerLedger } from "./answers.ts";
45
53
  import { validateArgs } from "./args-validation.ts";
46
54
  import { type OrchestrationProgram, programDefinition } from "./define-run.ts";
55
+ import { createPauseRequests } from "./pause-questions.ts";
47
56
  import type { RunContext } from "./run-context.ts";
57
+ import type { RunResult } from "./run-result.ts";
48
58
  import { type RunSettlement, settleRun } from "./run-settlement.ts";
49
59
 
50
60
  export interface RunOptions {
@@ -73,6 +83,12 @@ export interface RunOptions {
73
83
  readonly replay?: string;
74
84
  /** Replay a matching Cassette prefix, then continue live from its session. */
75
85
  readonly resume?: string;
86
+ /**
87
+ * The human's answers of one resume, keyed by Question id (ADR-0022). Every
88
+ * answer resolves one recorded Question; an unmatched Question stays open and
89
+ * the Run pauses again.
90
+ */
91
+ readonly answers?: Readonly<Record<string, string>>;
76
92
  /** Ends the Run early; every Agent is still reaped and costed. */
77
93
  readonly signal?: AbortSignal;
78
94
  /**
@@ -98,22 +114,28 @@ export interface RunOptions {
98
114
  }
99
115
 
100
116
  /**
101
- * Executes one Orchestration Program and resolves with its return value.
117
+ * Executes one Orchestration Program and resolves with its outcome: the
118
+ * program's value, or a paused Run with its questions and its Checkpoint
119
+ * (ADR-0022).
102
120
  *
103
121
  * Every Agent is dead by the time this settles — on success, on failure, and on
104
- * abort (ADR-0002) — and every Agent's cost has been emitted. Rejects with
105
- * ARGS_INVALID before emitting an event when declared argument schema validation fails.
122
+ * abort (ADR-0002) — and every Agent's cost has been emitted. A failed Run and
123
+ * a stopped Run reject with a `YaagError`. Rejects with ARGS_INVALID before
124
+ * emitting an event when declared argument schema validation fails.
106
125
  */
107
126
  export async function executeRun<Args, Result>(
108
127
  program: OrchestrationProgram<Args, Result>,
109
128
  options: RunOptions = {},
110
- ): Promise<Result> {
129
+ ): Promise<RunResult<Result>> {
111
130
  if (options.record !== undefined && options.replay !== undefined) {
112
131
  throw new YaagError("OPTIONS_CONFLICT", "cannot use record and replay together");
113
132
  }
114
133
  if (options.resume !== undefined && options.replay !== undefined) {
115
134
  throw new YaagError("OPTIONS_CONFLICT", "cannot use resume and replay together");
116
135
  }
136
+ if (options.answers !== undefined && options.resume === undefined) {
137
+ throw new YaagError("OPTIONS_CONFLICT", "cannot use answers without resume");
138
+ }
117
139
  const checkpointDir = options.checkpointDir ?? resolveCheckpointDirectory();
118
140
  try {
119
141
  // Best-effort, and emits no event, so the ARGS_INVALID "no events before
@@ -188,20 +210,36 @@ export async function executeRun<Args, Result>(
188
210
  sink(event);
189
211
  };
190
212
  const flusher = createCheckpointFlusher(checkpoint);
213
+ // Built before the first Agent starts, so every refusal of the answer
214
+ // contract precedes the Run's work (ADR-0022).
215
+ const answers: AnswerLedger =
216
+ resume === null
217
+ ? emptyAnswerLedger()
218
+ : createAnswerLedger({
219
+ supplied: options.answers ?? {},
220
+ questions: resume.run.questions ?? [],
221
+ inherited: resume.run.answers ?? [],
222
+ });
223
+ // Every answered park is restored into its session before the first Agent
224
+ // starts, so a conflicting answer refuses the resume before any work (ADR-0023).
225
+ if (resume !== null) await restoreSessionAnswers(resume, (id) => answers.take(id));
191
226
  const factory = selectFactory({
192
227
  options,
193
228
  collector: flushingSink(collector, flusher),
194
229
  replay,
195
230
  resume,
231
+ answers,
196
232
  });
197
233
  const agents: Agent[] = [];
198
234
  const startedAt = Date.now();
199
235
  const askAdmission = createAskAdmission();
236
+ const agentQuestions = createAgentQuestions();
200
237
  const spawnGate = makeSpawn({
201
238
  factory,
202
239
  agents,
203
240
  emit,
204
241
  askAdmission,
242
+ questions: agentQuestions,
205
243
  sessionDir: options.sessionDir,
206
244
  programFile: options.programFile,
207
245
  // The same value `run_start.program` carries, so an Agent's prompt names
@@ -211,9 +249,12 @@ export async function executeRun<Args, Result>(
211
249
  ...(profile === undefined ? {} : { profile }),
212
250
  });
213
251
 
252
+ const pauseRequests = createPauseRequests(answers);
214
253
  const ctx: RunContext<Args> = {
215
254
  args,
216
255
  spawn: spawnGate.spawn,
256
+ askUser: pauseRequests.askUser,
257
+ pause: pauseRequests.pause,
217
258
  ...(profile === undefined ? {} : { profile: { id: profile.id } }),
218
259
  };
219
260
  emit({
@@ -233,6 +274,7 @@ export async function executeRun<Args, Result>(
233
274
  askAdmission.close();
234
275
  spawnGate.close();
235
276
  },
277
+ questionRaised: agentQuestions.raised,
236
278
  });
237
279
  const outcome: RunOutcome = settlement.outcome;
238
280
  const settled = heldSettlement(settlement);
@@ -243,18 +285,62 @@ export async function executeRun<Args, Result>(
243
285
  // No flush may land after the settled artifact, or an acknowledged Run would
244
286
  // be overwritten by an `interrupted` one.
245
287
  await flusher.quiesce();
288
+ // The summarizer runs here and nowhere else: after quiescence and after every
289
+ // Agent is reaped, so it reads a session file pi has finished writing, and
290
+ // before publication, so each summary is durable in the Cassette (ADR-0022).
291
+ const summarized =
292
+ outcome === "paused"
293
+ ? await summarizeQuestions({
294
+ questions: agentQuestions,
295
+ agents,
296
+ policy: questionSummaryOf(options.config),
297
+ openAgent: spawnGate.openInternal,
298
+ ...(options.replay === undefined ? {} : { replaying: true }),
299
+ })
300
+ : { warnings: [] };
301
+ // Built once, after the summaries landed, so the wake payload and the returned
302
+ // result carry the same questions. The program's own questions come first;
303
+ // both registries are Run-scoped and neither can key a question of the other.
304
+ const openQuestions = [...pauseRequests.questions, ...agentQuestions.questions];
305
+ const pausedWarnings = [
306
+ ...(settled.ok === "paused" ? settled.warnings : []),
307
+ ...summarized.warnings,
308
+ ];
246
309
  // run_end is the acknowledgement: nothing may report an outcome before the
247
310
  // checkpoint's destination-directory fsync has landed (ADR-0021).
248
- const publication = await publishRunCheckpoint({ outcome, ...checkpoint });
311
+ const publication = await publishRunCheckpoint({
312
+ outcome,
313
+ ...checkpoint,
314
+ wake: {
315
+ // The program's own Questions first, then the Agents': the same order the
316
+ // RunResult carries, so an artifact and a reader agree (ADR-0022).
317
+ questions: openQuestions,
318
+ answers: answers.resolved(),
319
+ ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
320
+ },
321
+ });
322
+ const ending = endingFrom({ publication, outcome, destination, record: options.record });
249
323
  emitRunEnd({
250
324
  emit,
251
325
  durationMs: Date.now() - startedAt,
252
326
  summary,
253
- ...endingFrom({ publication, outcome, destination, record: options.record }),
327
+ ...ending,
328
+ ...(settled.ok === "paused" && pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
254
329
  });
255
330
  if (publication.kind === "displaced") throw publication.error;
331
+ if (settled.ok === "paused") {
332
+ // Built after publication, so `checkpoint` always names a file that is on
333
+ // disk and fsynced (ADR-0021).
334
+ return {
335
+ outcome: "paused",
336
+ questions: openQuestions,
337
+ ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
338
+ checkpoint: destination,
339
+ ...(pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
340
+ };
341
+ }
256
342
  if (!settled.ok) throw settled.error;
257
- return settled.value;
343
+ return { outcome: "completed", value: settled.value };
258
344
  }
259
345
 
260
346
  /**
@@ -299,12 +385,14 @@ function warnOnIdentity(cassette: Cassette, path: string, program: ProgramIdenti
299
385
  /** What the Orchestration Program body produced, before the Run acknowledges it. */
300
386
  type Settlement<Result> =
301
387
  | { readonly ok: true; readonly value: Result }
302
- | { readonly ok: false; readonly error: unknown };
388
+ | { readonly ok: false; readonly error: unknown }
389
+ | { readonly ok: "paused"; readonly warnings: readonly string[] };
303
390
 
304
391
  /**
305
392
  * Turns one settlement into the result the Run holds until its Checkpoint has
306
- * landed. A stopped or paused Run rejects with its own code, so the caller can
307
- * tell an ended Run from a failed one (ADR-0024).
393
+ * landed. A stopped Run rejects with its own code (ADR-0024); a paused Run is
394
+ * a third state, and becomes a return value once the Checkpoint is on disk
395
+ * (ADR-0022).
308
396
  */
309
397
  function heldSettlement<Result>(settlement: RunSettlement<Result>): Settlement<Result> {
310
398
  switch (settlement.outcome) {
@@ -313,19 +401,20 @@ function heldSettlement<Result>(settlement: RunSettlement<Result>): Settlement<R
313
401
  case "failed":
314
402
  return { ok: false, error: settlement.error };
315
403
  case "paused":
316
- // The cut-short Agents are named here, so the rejection says which Asks
317
- // the deadline ended rather than leaving that to the Checkpoint alone.
318
- return { ok: false, error: new YaagError("RUN_PAUSED", pauseMessage(settlement.cutShort)) };
404
+ // The cut-short Agents ride as warnings, so the paused result says which
405
+ // Asks a deadline ended rather than leaving that to the Checkpoint alone.
406
+ return {
407
+ ok: "paused",
408
+ warnings: [
409
+ ...settlement.warnings,
410
+ ...settlement.cutShort.map((agent) => `${agent}: Ask cut short by the pause deadline`),
411
+ ],
412
+ };
319
413
  case "stopped":
320
414
  return { ok: false, error: new YaagError("RUN_STOPPED", "run stopped") };
321
415
  }
322
416
  }
323
417
 
324
- /** Names the Asks a pause deadline cut short, or reports a clean drain. */
325
- function pauseMessage(cutShort: readonly string[]): string {
326
- return cutShort.length === 0 ? "run paused" : `run paused, cutting short: ${cutShort.join(", ")}`;
327
- }
328
-
329
418
  /**
330
419
  * Narrows the Run's incoming args to the program's declared Args at the one
331
420
  * boundary where untyped input enters typed code. Schema programs are proven
@@ -348,6 +437,8 @@ export interface FactorySelection {
348
437
  readonly collector: CassetteSink;
349
438
  readonly replay: Cassette | null;
350
439
  readonly resume: Cassette | null;
440
+ /** The answers of this resume; a recorded parked Ask reads its own here. */
441
+ readonly answers?: AnswerLedger;
351
442
  }
352
443
 
353
444
  /**
@@ -371,7 +462,11 @@ function selectLiveFactory(selection: FactorySelection): TransportFactory {
371
462
  selection.options.skillProbe ?? liveSkillProbe,
372
463
  );
373
464
  const live = worktreeTransport(restricted);
374
- return selection.resume === null ? live : resumeTransport(selection.resume, live);
465
+ if (selection.resume === null) return live;
466
+ const answers = selection.answers;
467
+ return resumeTransport(selection.resume, live, {
468
+ answerFor: (questionId) => answers?.take(questionId),
469
+ });
375
470
  }
376
471
 
377
472
  interface ReapOptions {
@@ -413,6 +508,8 @@ interface RunEndOptions {
413
508
  readonly checkpointLost?: string;
414
509
  /** Path of the published Checkpoint a paused or stopped Run resumes from (ADR-0054). */
415
510
  readonly checkpoint?: string;
511
+ /** Ask rejections observed during a pause drain; they never change the outcome. */
512
+ readonly warnings?: readonly string[];
416
513
  }
417
514
 
418
515
  /**
@@ -459,11 +556,13 @@ function emitRunEnd({
459
556
  summary,
460
557
  checkpointLost,
461
558
  checkpoint,
559
+ warnings,
462
560
  }: RunEndOptions): void {
463
561
  emit({
464
562
  type: "run_end",
465
563
  ...(checkpointLost === undefined ? {} : { checkpointLost }),
466
564
  ...(checkpoint === undefined ? {} : { checkpoint }),
565
+ ...(warnings === undefined ? {} : { warnings }),
467
566
  ok: outcome === "completed",
468
567
  outcome,
469
568
  durationMs,
@@ -11,7 +11,7 @@ import type { PromptAudience, PromptText, SystemPromptAgent } from "../contract/
11
11
  // `public-api.ts`, and the vendored author declaration tree follows source
12
12
  // imports, so an index import would pull `prompt/index.d.ts` and
13
13
  // `prompt-gist.d.ts` into the ADR-0045 surface that
14
- // `apps/yaag/scripts/runtime-dts.test.ts` guards.
14
+ // `apps/yaag/test/scripts/runtime-dts.test.ts` guards.
15
15
  import { prompt } from "../prompt/prompt.ts";
16
16
  import { renderSentinel } from "./render-sentinel.ts";
17
17
 
@@ -1,4 +1,9 @@
1
- import { REPORT_RESULT_EXTENSION_PATH, REPORT_RESULT_TOOL_NAME } from "../ask-contract/index.ts";
1
+ import {
2
+ REPORT_RESULT_EXTENSION_PATH,
3
+ REPORT_RESULT_TOOL_NAME,
4
+ REQUEST_USER_INPUT_EXTENSION_PATH,
5
+ REQUEST_USER_INPUT_TOOL_NAME,
6
+ } from "../ask-contract/index.ts";
2
7
  import type { AgentProgress } from "../contract/index.ts";
3
8
  import { isThinkingLevel, type ThinkingLevel } from "../model/index.ts";
4
9
  import {
@@ -72,7 +77,8 @@ function appendCapabilities(
72
77
  cmd.push("--no-extensions", "--no-context-files", "--no-prompt-templates");
73
78
  }
74
79
  // Load order is fixed (ADR-0063): the prompt extension first, then the
75
- // program extensions, `report_result`, the tool probe, and the recorder last.
80
+ // program extensions, `report_result`, `request_user_input`, the tool probe,
81
+ // and the recorder last.
76
82
  // `before_agent_start` handlers chain in load order, so first means a program
77
83
  // extension appends to the already assembled Agent System Prompt.
78
84
  //
@@ -87,6 +93,9 @@ function appendCapabilities(
87
93
  // output schema long after the process started and pi loads extensions only
88
94
  // at startup (ADR-0032).
89
95
  cmd.push("-e", REPORT_RESULT_EXTENSION_PATH);
96
+ // The user-question tool loads before the probe, so the probe reports it: it
97
+ // registers at startup and is a required tool of this spawn (ADR-0023).
98
+ if (options.canAskUser === true) cmd.push("-e", REQUEST_USER_INPUT_EXTENSION_PATH);
90
99
  // The caller decides whether the probe runs: it loads the extension only when
91
100
  // the spawn flags promised something verifiable (see toolContract).
92
101
  if (toolProbeExtensionPath !== undefined) cmd.push("-e", toolProbeExtensionPath);
@@ -108,6 +117,7 @@ function appendCapabilities(
108
117
  export interface ToolSelection {
109
118
  readonly tools?: readonly string[] | undefined;
110
119
  readonly inherit?: boolean | undefined;
120
+ readonly canAskUser?: boolean | undefined;
111
121
  }
112
122
 
113
123
  /**
@@ -125,10 +135,17 @@ export interface ToolSelection {
125
135
  */
126
136
  export function toolAllowlist(options: ToolSelection): readonly string[] | null {
127
137
  const { tools } = options;
138
+ // Note the asymmetry with `report_result`: this name is added to yaag's own
139
+ // implicit list, or to a list the spawn guard already proved names it, so no
140
+ // program's allowlist is ever widened behind its back (ADR-0023).
141
+ const asked = options.canAskUser === true ? [REQUEST_USER_INPUT_TOOL_NAME] : [];
128
142
  if (tools === undefined) {
129
- return options.inherit === true ? null : [REPORT_RESULT_TOOL_NAME];
143
+ // An inheriting spawn emits no allowlist, also when it may ask: pi composes
144
+ // the toolset itself and keeps every extension tool.
145
+ if (options.inherit === true) return null;
146
+ return [REPORT_RESULT_TOOL_NAME, ...asked];
130
147
  }
131
- return [...new Set([...tools, REPORT_RESULT_TOOL_NAME])];
148
+ return [...new Set([...tools, REPORT_RESULT_TOOL_NAME, ...asked])];
132
149
  }
133
150
 
134
151
  function appendTools(cmd: string[], options: OpenOptions): void {
@@ -56,6 +56,10 @@ function dedupe(names: Iterable<string>): string[] {
56
56
  * `report_result` is allowed but never required: report-result-extension.ts
57
57
  * registers the tool when a schema-bearing Ask activates it, long after startup
58
58
  * (ADR-0032), so at startup the probe reports it as inactive.
59
+ *
60
+ * `request_user_input` is required whenever the spawn may ask its human: that
61
+ * extension registers its tool at startup, so a lost capability fails the spawn
62
+ * instead of surfacing as a silent inability to ask (ADR-0023).
59
63
  */
60
64
  export function toolContract(options: ToolContractOptions): ToolContract | null {
61
65
  // pi-state.ts strips this name from `--exclude-tools`, so it is never denied.
@@ -90,6 +90,11 @@ export interface AskCompletion {
90
90
  readonly invalidOutput?: AskInvalidOutputPlayback;
91
91
  /** The Stall Watchdog settled this Ask from observed state (ADR-0029). */
92
92
  readonly recovered?: true;
93
+ /**
94
+ * The turn parked on `request_user_input` and never settled (ADR-0023).
95
+ * The collector records it as the incomplete-Ask marker of the Ask (ADR-0021).
96
+ */
97
+ readonly parked?: { readonly toolCallId: string; readonly questionId: string };
93
98
  }
94
99
 
95
100
  /**
@@ -141,6 +146,17 @@ export interface AskPlayback {
141
146
  * Cassette does not contain.
142
147
  */
143
148
  readonly settles?: false;
149
+ /**
150
+ * The recorded Ask parked on `request_user_input` and this resume holds no
151
+ * answer for it (ADR-0023). The Ask re-opens the same Question and parks
152
+ * again, so the Run pauses with it still open.
153
+ */
154
+ readonly parked?: {
155
+ readonly toolCallId: string;
156
+ readonly questionId: string;
157
+ readonly question: string;
158
+ readonly context?: string;
159
+ };
144
160
  }
145
161
 
146
162
  /** One Agent, as the layer above sees it. */
@@ -223,6 +239,16 @@ export interface OpenOptions {
223
239
  * Spawn identity only: it never becomes argv, and it is absent when empty.
224
240
  */
225
241
  readonly declaredExtensions?: readonly string[];
242
+ /**
243
+ * Loads the injected `request_user_input` extension (ADR-0023). Only ever
244
+ * true, so an Agent that never asks keeps a byte-identical open request.
245
+ */
246
+ readonly canAskUser?: true;
247
+ /**
248
+ * The protocol the injected extension declares. Spawn identity only: it never
249
+ * becomes argv, and it is compared when a recorded Agent reactivates.
250
+ */
251
+ readonly askUserProtocol?: number;
226
252
  /**
227
253
  * Resolved name of the Agent named as this Agent's parent (Parent Link).
228
254
  * Spawn identity only: it never becomes argv.