@yaag/runtime 0.25.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 (56) 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 +2 -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 +21 -2
  8. package/src/ask/ask-exchange-options.ts +5 -0
  9. package/src/ask/ask-exchange.ts +67 -2
  10. package/src/ask/ask-settlement.ts +8 -0
  11. package/src/ask/idle-watch.ts +12 -2
  12. package/src/ask/stall-watchdog.ts +13 -3
  13. package/src/ask-contract/ask-limit.ts +24 -6
  14. package/src/ask-contract/index.ts +8 -0
  15. package/src/ask-contract/request-user-input-extension.ts +105 -0
  16. package/src/ask-contract/request-user-input.ts +58 -0
  17. package/src/cassette/cassette-loader.ts +50 -1
  18. package/src/cassette/cassette-schema.ts +27 -0
  19. package/src/cassette/cassette.ts +49 -0
  20. package/src/cassette/index.ts +10 -1
  21. package/src/cassette/replay-divergence.ts +5 -0
  22. package/src/cassette/resume-preconditions.ts +10 -0
  23. package/src/cassette/resume-transport.ts +111 -6
  24. package/src/cassette/run-checkpoint.ts +52 -3
  25. package/src/cassette/session-answer.ts +163 -0
  26. package/src/catalog/registry-reader.ts +1 -1
  27. package/src/config/config-schema.ts +33 -0
  28. package/src/config/effective-config.ts +53 -0
  29. package/src/config/index.ts +4 -0
  30. package/src/contract/agent-policy.ts +9 -0
  31. package/src/contract/error-codes.ts +2 -2
  32. package/src/control/index.ts +2 -0
  33. package/src/control/pause-drain.ts +81 -24
  34. package/src/events.ts +6 -0
  35. package/src/index.ts +11 -1
  36. package/src/model/index.ts +1 -1
  37. package/src/public-api.ts +1 -0
  38. package/src/question-summary/index.ts +22 -0
  39. package/src/question-summary/session-copy.ts +169 -0
  40. package/src/question-summary/summarize-question.ts +129 -0
  41. package/src/question-summary/summary-policy.ts +25 -0
  42. package/src/run/agent-questions.ts +75 -0
  43. package/src/run/answers.ts +70 -0
  44. package/src/run/index.ts +5 -0
  45. package/src/run/pause-questions.ts +98 -0
  46. package/src/run/pause-signal.ts +32 -0
  47. package/src/run/question-id.ts +18 -0
  48. package/src/run/questions.ts +31 -0
  49. package/src/run/run-context.ts +18 -0
  50. package/src/run/run-result.ts +21 -0
  51. package/src/run/run-settlement.ts +36 -4
  52. package/src/run/run.ts +119 -20
  53. package/src/system-prompt/agent-system-prompt.ts +1 -1
  54. package/src/transport/pi-state.ts +21 -4
  55. package/src/transport/tool-probe.ts +4 -0
  56. package/src/transport/transport.ts +26 -0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The answer ledger of one resume (ADR-0022).
3
+ *
4
+ * It holds what `--answers` supplied, what the resume source left open, and
5
+ * what an earlier resume already resolved. Every refusal happens here, at
6
+ * construction, before the first Agent starts.
7
+ */
8
+ import type { CassetteAnswer, CassetteQuestion } from "../cassette/index.ts";
9
+ import { YaagError } from "../errors.ts";
10
+
11
+ /** What one resume knows about its answers. */
12
+ export interface AnswerLedger {
13
+ /** The answer for this Question id, or undefined when it stays open. */
14
+ take(id: string): string | undefined;
15
+ /** Every resolved step the successor Cassette must carry. */
16
+ resolved(): readonly CassetteAnswer[];
17
+ }
18
+
19
+ export interface AnswerLedgerOptions {
20
+ /** What `--answers` supplied, keyed by Question id. */
21
+ readonly supplied: Readonly<Record<string, string>>;
22
+ /** The open Questions of the resume source. */
23
+ readonly questions: readonly CassetteQuestion[];
24
+ /** The answers the resume source already resolved. */
25
+ readonly inherited: readonly CassetteAnswer[];
26
+ }
27
+
28
+ /**
29
+ * Builds the ledger, and refuses the resume when an answer names nothing open
30
+ * or contradicts an inherited answer. A repeated `--answers` of the same text
31
+ * is accepted, so retrying one resume is safe.
32
+ */
33
+ export function createAnswerLedger(options: AnswerLedgerOptions): AnswerLedger {
34
+ const open = new Set(options.questions.map((question) => question.id));
35
+ const resolved = new Map<string, string>(
36
+ options.inherited.map((answer) => [answer.id, answer.answer] as const),
37
+ );
38
+ for (const [id, answer] of Object.entries(options.supplied)) {
39
+ const known = resolved.get(id);
40
+ if (known !== undefined) {
41
+ // Idempotent: the same answer again resolves the same step.
42
+ if (known === answer) continue;
43
+ throw new YaagError(
44
+ "RESUME_REFUSED",
45
+ `the question "${id}" is already answered with "${known}" — ` +
46
+ `it cannot be answered with "${answer}" as well`,
47
+ );
48
+ }
49
+ if (!open.has(id)) {
50
+ throw new YaagError(
51
+ "RESUME_REFUSED",
52
+ `the answer key "${id}" names no open question of this checkpoint`,
53
+ );
54
+ }
55
+ resolved.set(id, answer);
56
+ }
57
+ return {
58
+ take(id: string): string | undefined {
59
+ return resolved.get(id);
60
+ },
61
+ resolved(): readonly CassetteAnswer[] {
62
+ return [...resolved].map(([id, answer]) => ({ id, answer }));
63
+ },
64
+ };
65
+ }
66
+
67
+ /** The empty ledger of a Run that resumes nothing: it answers no question. */
68
+ export function emptyAnswerLedger(): AnswerLedger {
69
+ return createAnswerLedger({ supplied: {}, questions: [], inherited: [] });
70
+ }
package/src/run/index.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  * Public surface of the `run/` module: the Run lifecycle.
3
3
  * Files inside this directory import each other directly.
4
4
  */
5
+ export { type AgentQuestions, createAgentQuestions } from "./agent-questions.ts";
6
+ export { type AnswerLedger, createAnswerLedger } from "./answers.ts";
5
7
  export {
6
8
  defineRun,
7
9
  isOrchestrationProgram,
@@ -9,5 +11,8 @@ export {
9
11
  type ProgramDefinition,
10
12
  programDefinition,
11
13
  } from "./define-run.ts";
14
+ export { isPauseSignal, RunPauseSignal } from "./pause-signal.ts";
15
+ export type { AskUserOptions, Question } from "./questions.ts";
12
16
  export { executeRun, type RunOptions } from "./run.ts";
13
17
  export type { RunContext } from "./run-context.ts";
18
+ export type { RunResult } from "./run-result.ts";
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The question registry behind `ctx.askUser` and `ctx.pause` (ADR-0022).
3
+ *
4
+ * Every verb records what it wants to know, then throws the pause signal, so
5
+ * the Run unwinds to `executeRun` and drains. A resume supplies an answer
6
+ * ledger: a step whose answer it holds resolves instead (ADR-0022).
7
+ */
8
+ import type { CassetteQuestion } from "../cassette/index.ts";
9
+ import { YaagError } from "../errors.ts";
10
+ import type { AnswerLedger } from "./answers.ts";
11
+ import { RunPauseSignal } from "./pause-signal.ts";
12
+ import { programQuestionId } from "./question-id.ts";
13
+ import type { AskUserOptions, Question } from "./questions.ts";
14
+
15
+ /**
16
+ * Compile-time drift guard: the author-facing `Question` and the durable
17
+ * `CassetteQuestion` must stay the same shape. The two types live apart
18
+ * because `cassette/` must not import the author declaration tree (ADR-0045),
19
+ * and this file may import both.
20
+ *
21
+ * Assignability alone would let one side gain an optional field, because every
22
+ * field but `id` and `question` is optional, so the field names are asserted
23
+ * mutually assignable as well.
24
+ */
25
+ type AssertAssignable<T extends Base, Base> = T;
26
+ export type QuestionMatchesCassette = AssertAssignable<Question, CassetteQuestion>;
27
+ export type CassetteMatchesQuestion = AssertAssignable<CassetteQuestion, Question>;
28
+ export type QuestionFieldsMatchCassette = AssertAssignable<keyof Question, keyof CassetteQuestion>;
29
+ export type CassetteFieldsMatchQuestion = AssertAssignable<keyof CassetteQuestion, keyof Question>;
30
+
31
+ /** The pause verbs of one Run, and what they recorded. */
32
+ export interface PauseRequests {
33
+ askUser(question: string, options?: AskUserOptions): Promise<string>;
34
+ pause(reason?: string): Promise<void>;
35
+ readonly questions: readonly Question[];
36
+ readonly reason: string | undefined;
37
+ }
38
+
39
+ /**
40
+ * Builds the pause verbs of one Run. Every registry is Run-scoped. The ledger
41
+ * of a resume answers a matching step; without one, every step pauses.
42
+ */
43
+ export function createPauseRequests(answers?: AnswerLedger): PauseRequests {
44
+ const byId = new Map<string, Question>();
45
+ // Remembers which ids came from a key, so a repeated keyed question is a
46
+ // repeat and an id collision between two keys is a refusal.
47
+ const keyed = new Map<string, string>();
48
+ let reason: string | undefined;
49
+
50
+ const record = (question: string, options: AskUserOptions | undefined): void => {
51
+ const key = options?.key;
52
+ const id = programQuestionId(question, key);
53
+ const known = byId.get(id);
54
+ if (known !== undefined) {
55
+ // The same keyed question again is the same question: the program simply
56
+ // ran to this line a second time. Everything else is a refusal.
57
+ if (key !== undefined && keyed.get(key) === question) return;
58
+ throw new YaagError("PAUSE_REFUSED", refusalMessage(key, question));
59
+ }
60
+ if (key !== undefined) keyed.set(key, question);
61
+ byId.set(id, {
62
+ id,
63
+ question,
64
+ ...(options?.context === undefined ? {} : { context: options.context }),
65
+ });
66
+ };
67
+
68
+ return {
69
+ async askUser(question: string, options?: AskUserOptions): Promise<string> {
70
+ // Matching is by key when the author gave one, else by the question hash:
71
+ // the id function is that rule (ADR-0022).
72
+ const answer = answers?.take(programQuestionId(question, options?.key));
73
+ // A re-executed step whose answer the ledger holds resolves, and records
74
+ // no Question: lenient re-execution repeats it as often as it runs.
75
+ if (answer !== undefined) return answer;
76
+ record(question, options);
77
+ throw new RunPauseSignal();
78
+ },
79
+ async pause(text?: string): Promise<void> {
80
+ // The first reason wins: it is the reason the Run stopped its work.
81
+ if (reason === undefined && text !== undefined) reason = text;
82
+ throw new RunPauseSignal();
83
+ },
84
+ get questions(): readonly Question[] {
85
+ return [...byId.values()];
86
+ },
87
+ get reason(): string | undefined {
88
+ return reason;
89
+ },
90
+ };
91
+ }
92
+
93
+ /** Says which duplicate was refused, and how to fix it. */
94
+ function refusalMessage(key: string | undefined, question: string): string {
95
+ if (key !== undefined)
96
+ return `two questions use the key "${key}" — give each question its own key`;
97
+ return `two questions ask "${question}" and neither has a key — give each askUser call its own key`;
98
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The internal pause control signal (ADR-0022).
3
+ *
4
+ * It is deliberately NOT a `YaagError`: `isYaagError()` returns false for it,
5
+ * so no `catch` block in an Orchestration Program, an extension, or a helper
6
+ * can mistake a pause for a failure and "handle" it.
7
+ */
8
+
9
+ /** Cross-realm brand, so a signal that crosses a module copy is still a signal. */
10
+ const PAUSE_SIGNAL = Symbol.for("yaag.pause-signal");
11
+
12
+ /**
13
+ * Thrown by `ctx.askUser` and `ctx.pause` to unwind the Orchestration Program
14
+ * body. `executeRun` recognizes it and drains the Run for a pause.
15
+ */
16
+ export class RunPauseSignal extends Error {
17
+ readonly [PAUSE_SIGNAL] = true;
18
+
19
+ constructor() {
20
+ super("run paused: ctx.askUser or ctx.pause was called");
21
+ this.name = "RunPauseSignal";
22
+ }
23
+ }
24
+
25
+ /** True when the value is a pause signal, also across module realms. */
26
+ export function isPauseSignal(value: unknown): value is RunPauseSignal {
27
+ return (
28
+ typeof value === "object" &&
29
+ value !== null &&
30
+ (value as Record<symbol, unknown>)[PAUSE_SIGNAL] === true
31
+ );
32
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The one id minter of both Question families (ADR-0022).
3
+ *
4
+ * A resume addresses a Question by id, so the live path and the recorded path
5
+ * must mint the same string. Two families share one namespace: the program's
6
+ * own `askUser`, keyed or hashed, and an Agent's parked `request_user_input`.
7
+ */
8
+ import { sha256Hex } from "../cassette/program-hash.ts";
9
+
10
+ /** The id of one `ctx.askUser` step: the author key, else the question hash. */
11
+ export function programQuestionId(question: string, key?: string): string {
12
+ return key ?? sha256Hex(question).slice(0, 16);
13
+ }
14
+
15
+ /** The id of one parked Agent Question: `<agent>#<toolCallId>` (ADR-0023). */
16
+ export function agentQuestionId(agent: string, toolCallId: string): string {
17
+ return `${agent}#${toolCallId}`;
18
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The author-facing shapes of the pause verbs (ADR-0022). They live apart from
3
+ * the registry that implements them, so the author declaration tree stays free
4
+ * of runtime imports (ADR-0045).
5
+ */
6
+
7
+ /**
8
+ * One question the Run asks its user. The durable twin of this shape is
9
+ * `CassetteQuestion` in `cassette/cassette.ts`: this type stays here because
10
+ * the author declaration tree must stay free of runtime imports (ADR-0045),
11
+ * and `cassette/` must not import it back. The two shapes are held together by
12
+ * the compile-time assertions in `run/pause-questions.ts`.
13
+ */
14
+ export interface Question {
15
+ /** Stable identity: the given `key`, or a hash of the question text. */
16
+ readonly id: string;
17
+ /** The Agent that asked; absent for a program Question (ADR-0022). */
18
+ readonly agent?: string;
19
+ readonly question: string;
20
+ /** Free text that helps the user answer. */
21
+ readonly context?: string;
22
+ /** Short restatement of the question: the Question Summary (ADR-0022). */
23
+ readonly summary?: string;
24
+ }
25
+
26
+ export interface AskUserOptions {
27
+ /** Stable id for this question; it survives a changed question text. */
28
+ readonly key?: string;
29
+ /** Free text that helps the user answer. */
30
+ readonly context?: string;
31
+ }
@@ -8,6 +8,7 @@ import type {
8
8
  SpawnOverrides,
9
9
  } from "../contract/index.ts";
10
10
  import type { ProfiledDefinition } from "../profile/use-profile.ts";
11
+ import type { AskUserOptions } from "./questions.ts";
11
12
 
12
13
  /** What an Orchestration Program is handed. */
13
14
  export interface RunContext<Args = unknown> {
@@ -27,6 +28,23 @@ export interface RunContext<Args = unknown> {
27
28
  spawn(profiled: ProfiledDefinition, overrides?: SpawnOverrides): Promise<Handle>;
28
29
  /** Last on purpose: a union-typed value, e.g. what a Catalog Resolve gave back (ADR-0053). */
29
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>;
30
48
  /**
31
49
  * The Profile this Run activated (ADR-0052). Defined when the program
32
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
  /**