@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
@@ -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;
@@ -2,18 +2,22 @@ import type { AskLimitKind, AskLimitOutcome } from "../errors.ts";
2
2
  import type { Frame } from "../transport/index.ts";
3
3
  import type { AskOptions } from "../types.ts";
4
4
  import { REPORT_RESULT_TOOL_NAME } from "./report-result.ts";
5
+ import { REQUEST_USER_INPUT_TOOL_NAME } from "./request-user-input.ts";
5
6
  import { wrapUpMessage } from "./wrap-up-steer.ts";
6
7
 
7
8
  /**
8
- * True for a call to yaag's private result tool.
9
+ * True for a call to one of yaag's own private tools.
9
10
  *
10
11
  * `maxToolCalls` bounds the Agent's own work. The settling `report_result` call
11
12
  * is yaag's mechanism, and counting it would both shrink every declared budget
12
13
  * and let the settling call trip a wrap-up steer that pi parks for the next Ask
13
- * (ADR-0032).
14
+ * (ADR-0032). The parking `request_user_input` call is control plane in the
15
+ * same sense: it is a question to the human, not work (ADR-0023).
14
16
  */
15
- function isReportResult(frame: Frame): boolean {
16
- return frame.toolName === REPORT_RESULT_TOOL_NAME;
17
+ function isControlPlaneTool(frame: Frame): boolean {
18
+ return (
19
+ frame.toolName === REPORT_RESULT_TOOL_NAME || frame.toolName === REQUEST_USER_INPUT_TOOL_NAME
20
+ );
17
21
  }
18
22
 
19
23
  /** Fixed time allowed to conclude after a duration limit trips. */
@@ -53,6 +57,7 @@ export class AskLimit {
53
57
  #aborted = false;
54
58
  #durationTimer: ReturnType<typeof setTimeout> | undefined;
55
59
  #graceTimer: ReturnType<typeof setTimeout> | undefined;
60
+ #suspended = false;
56
61
 
57
62
  constructor(options: AskLimitOptions) {
58
63
  this.#ask = options.ask;
@@ -93,7 +98,7 @@ export class AskLimit {
93
98
  }
94
99
  return;
95
100
  }
96
- if (frame.type !== "tool_execution_start" || isReportResult(frame)) return;
101
+ if (frame.type !== "tool_execution_start" || isControlPlaneTool(frame)) return;
97
102
  this.#toolCalls += 1;
98
103
  if (this.#trip !== null || this.#ask.maxToolCalls === undefined) return;
99
104
  if (this.#toolCalls >= this.#ask.maxToolCalls) this.#tripLimit("toolCalls", this.#toolCalls);
@@ -132,6 +137,19 @@ export class AskLimit {
132
137
  this.settled();
133
138
  }
134
139
 
140
+ /**
141
+ * Suspends every budget while the Ask parks on a user question (ADR-0023).
142
+ * The Ask has not settled, so this is not `settled()`: it only stops the
143
+ * clocks, and nothing can trip while the Run waits for the human.
144
+ */
145
+ suspend(): void {
146
+ this.#suspended = true;
147
+ clearTimeout(this.#durationTimer);
148
+ clearTimeout(this.#graceTimer);
149
+ this.#durationTimer = undefined;
150
+ this.#graceTimer = undefined;
151
+ }
152
+
135
153
  /** Rejects when a steer or abort RPC is refused. */
136
154
  get failed(): Promise<never> {
137
155
  return this.#failure.then(
@@ -153,7 +171,7 @@ export class AskLimit {
153
171
  }
154
172
 
155
173
  #tripLimit(kind: AskLimitKind, count: number): void {
156
- if (this.#completed || this.#trip !== null) return;
174
+ if (this.#completed || this.#suspended || this.#trip !== null) return;
157
175
  this.#trip = { kind, count };
158
176
  this.#turnsAtSteer = this.#turns;
159
177
  void this.#send({ type: "steer", message: this.#wrapUpMessage() });
@@ -34,4 +34,12 @@ export {
34
34
  resolvePlaybackReportedResult,
35
35
  } from "./report-result-output.ts";
36
36
  export { ReportResultSteering } from "./report-result-steering.ts";
37
+ export {
38
+ type AgentQuestionCall,
39
+ REQUEST_USER_INPUT_EXTENSION_PATH,
40
+ REQUEST_USER_INPUT_PROTOCOL,
41
+ REQUEST_USER_INPUT_TOOL_NAME,
42
+ RESUME_NUDGE,
43
+ readQuestionFrame,
44
+ } from "./request-user-input.ts";
37
45
  export { DEFAULT_WRAP_UP_PROMPT, wrapUpMessage } from "./wrap-up-steer.ts";
@@ -0,0 +1,105 @@
1
+ /**
2
+ * yaag's private user-question tool, loaded into an Agent that may ask (ADR-0023).
3
+ *
4
+ * The tool never resolves: the call parks the turn, the runtime reads the
5
+ * `tool_execution_start` frame, and the Run pauses. The Agent process is reaped
6
+ * with the call still pending, which is the dangling-call shape the restoration
7
+ * of a resumed Agent needs.
8
+ *
9
+ * Types are declared locally rather than imported from pi: this file is passed
10
+ * to `pi -e` as a path and must load without yaag's dependency graph.
11
+ */
12
+
13
+ /** One tool result, in the shape pi's tool layer returns to the model. */
14
+ export interface RequestUserInputToolResult {
15
+ readonly content: readonly { readonly type: "text"; readonly text: string }[];
16
+ readonly isError?: boolean;
17
+ }
18
+
19
+ /** One tool definition, in the shape `pi.registerTool` accepts. */
20
+ export interface RequestUserInputToolDefinition {
21
+ readonly name: string;
22
+ readonly label: string;
23
+ readonly description: string;
24
+ readonly promptSnippet: string;
25
+ readonly promptGuidelines: readonly string[];
26
+ readonly parameters: object;
27
+ execute(toolCallId: string, params: unknown): Promise<RequestUserInputToolResult>;
28
+ }
29
+
30
+ /** The part of pi's extension API this extension uses (pi docs/extensions.md). */
31
+ export interface RequestUserInputAPI {
32
+ registerTool(definition: RequestUserInputToolDefinition): void;
33
+ }
34
+
35
+ /** The wire protocol of this tool. A resume with a different number is refused. */
36
+ export const PROTOCOL = 1;
37
+
38
+ const TOOL_NAME = "request_user_input";
39
+ const DESCRIPTION = [
40
+ "Ask the human one question.",
41
+ "This tool blocks until the human answers.",
42
+ "The answer arrives as this tool's result.",
43
+ "Call it only when you cannot continue without the answer.",
44
+ "Give `context` so the human knows why you ask.",
45
+ ].join(" ");
46
+ const SECOND_CALL = "one question per turn";
47
+ const EMPTY_QUESTION = "give a question for the human";
48
+ /**
49
+ * Guidelines name the tool, because pi appends them flat to one Guidelines
50
+ * section where "this tool" cannot be resolved (pi docs/extensions.md).
51
+ */
52
+ const GUIDELINES = [
53
+ "Call request_user_input only when you cannot continue without an answer from the human.",
54
+ "Call request_user_input one time in a turn, and give the context of your question.",
55
+ ];
56
+ const PARAMETERS = {
57
+ type: "object",
58
+ properties: {
59
+ question: { type: "string", description: "the one question for the human" },
60
+ context: { type: "string", description: "why you ask, in 1 to 3 sentences" },
61
+ },
62
+ required: ["question"],
63
+ additionalProperties: false,
64
+ };
65
+
66
+ export default function (pi: RequestUserInputAPI): void {
67
+ let pending = false;
68
+
69
+ pi.registerTool({
70
+ name: TOOL_NAME,
71
+ label: "Request User Input",
72
+ description: DESCRIPTION,
73
+ promptSnippet: "Ask the human one question and wait for the answer",
74
+ promptGuidelines: GUIDELINES,
75
+ parameters: PARAMETERS,
76
+ execute: (_toolCallId, params): Promise<RequestUserInputToolResult> => {
77
+ // The runtime drops a call with no question text, so a park on such a
78
+ // call would be a turn that waits for a question nobody can answer. The
79
+ // model gets the error and can ask again in the same turn.
80
+ if (!hasQuestion(params)) {
81
+ return Promise.resolve({
82
+ content: [{ type: "text", text: EMPTY_QUESTION }],
83
+ isError: true,
84
+ });
85
+ }
86
+ if (pending) {
87
+ return Promise.resolve({
88
+ content: [{ type: "text", text: SECOND_CALL }],
89
+ isError: true,
90
+ });
91
+ }
92
+ pending = true;
93
+ // The park: the promise never settles, so the turn never advances and
94
+ // "while pending" is exactly "this turn".
95
+ return new Promise<RequestUserInputToolResult>(() => {});
96
+ },
97
+ });
98
+ }
99
+
100
+ /** True when the arguments carry a question the human can read. */
101
+ function hasQuestion(params: unknown): boolean {
102
+ if (typeof params !== "object" || params === null) return false;
103
+ const question: unknown = (params as Record<string, unknown>).question;
104
+ return typeof question === "string" && question.trim() !== "";
105
+ }
@@ -0,0 +1,58 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import type { Frame } from "../transport/index.ts";
3
+
4
+ /** The injected tool an Agent asks its human with (ADR-0023). */
5
+ export const REQUEST_USER_INPUT_TOOL_NAME = "request_user_input";
6
+
7
+ /**
8
+ * The protocol the injected extension declares. It is spawn identity, but not
9
+ * part of the spawn hash: a bumped protocol must refuse a reactivation rather
10
+ * than read as a changed spawn.
11
+ */
12
+ export const REQUEST_USER_INPUT_PROTOCOL = 1;
13
+
14
+ /** Loadable source path for the private extension that owns `request_user_input`. */
15
+ export const REQUEST_USER_INPUT_EXTENSION_PATH = fileURLToPath(
16
+ // `fileURLToPath` decodes percent-escapes, such as a space in a parent path.
17
+ new URL("./request-user-input-extension.ts", import.meta.url),
18
+ );
19
+
20
+ /**
21
+ * The prompt a restored Agent gets in place of the Ask prompt it already saw
22
+ * (ADR-0023). The answer is in the session as the tool result of the Agent's
23
+ * own `request_user_input` call, so the nudge only tells it to go on.
24
+ */
25
+ export const RESUME_NUDGE =
26
+ "The human answered your question. The answer is the result of your " +
27
+ "request_user_input call. Continue your work.";
28
+
29
+ /** One parked question, as the Agent's frame reported it. */
30
+ export interface AgentQuestionCall {
31
+ readonly toolCallId: string;
32
+ readonly question: string;
33
+ readonly context?: string;
34
+ }
35
+
36
+ /**
37
+ * Reads one parking call from a frame, or null for every other frame.
38
+ *
39
+ * Every malformed boundary returns null: a frame that does not carry a tool
40
+ * call id and a question text cannot key a Question, so it is not one.
41
+ */
42
+ export function readQuestionFrame(frame: Frame): AgentQuestionCall | null {
43
+ if (frame.type !== "tool_execution_start") return null;
44
+ if (frame.toolName !== REQUEST_USER_INPUT_TOOL_NAME) return null;
45
+ const toolCallId: unknown = frame.toolCallId;
46
+ if (typeof toolCallId !== "string" || toolCallId === "") return null;
47
+ const args: unknown = frame.args;
48
+ if (typeof args !== "object" || args === null) return null;
49
+ const record = args as Record<string, unknown>;
50
+ const question: unknown = record.question;
51
+ if (typeof question !== "string" || question === "") return null;
52
+ const context: unknown = record.context;
53
+ return {
54
+ toolCallId,
55
+ question,
56
+ ...(typeof context === "string" && context !== "" ? { context } : {}),
57
+ };
58
+ }
@@ -14,7 +14,7 @@ import { CassetteSchema } from "./cassette-schema.ts";
14
14
  *
15
15
  * Rejects unreadable, unparsable, unsupported, and malformed artifacts at the
16
16
  * filesystem boundary; replay never receives unchecked external data. The
17
- * schema checks structure; the five named invariants below check semantics.
17
+ * schema checks structure; the seven named invariants below check semantics.
18
18
  * A version 1 artifact is upgraded in memory to version 2 (ADR-0021).
19
19
  * Unknown fields are retained, never dropped (forward tolerance).
20
20
  * The bytes are gzip-compressed JSON, or the plain JSON that older runtimes
@@ -38,6 +38,7 @@ export async function loadCassette(path: string): Promise<Cassette> {
38
38
  if (errors.length > 0) malformed(path, formatValidationErrors(value, errors).join("; "));
39
39
  const artifact = value as CassetteArtifact; // sound: CassetteSchemaIsSound (cassette-schema.ts)
40
40
  assertRunPresence(artifact, path);
41
+ assertUniqueQuestionIds(artifact, path);
41
42
  for (const [agentIndex, agent] of artifact.agents.entries()) {
42
43
  agent.asks.forEach((ask, askIndex) => {
43
44
  const label = `agents[${agentIndex}].asks[${askIndex}]`;
@@ -127,6 +128,46 @@ function assertRunPresence(artifact: CassetteArtifact, path: string): void {
127
128
  }
128
129
  }
129
130
 
131
+ /**
132
+ * Invariant 6: every Question id is unique. The answer contract addresses a
133
+ * Question by id (ADR-0022), so a repeated id would make a resume guess.
134
+ *
135
+ * Deliberately not checked: that every `ask.incomplete.questionId` names a
136
+ * Question of this run block. A `stopped` artifact can hold a parked Ask whose
137
+ * Question the drain never collected, and the loader must not refuse an
138
+ * artifact yaag itself writes.
139
+ */
140
+ function assertUniqueQuestionIds(artifact: CassetteArtifact, path: string): void {
141
+ const seen = new Set<string>();
142
+ const questions = artifact.run?.questions ?? [];
143
+ for (const [index, question] of questions.entries()) {
144
+ if (seen.has(question.id)) {
145
+ malformed(path, `run.questions[${index}].id "${question.id}" is used twice`);
146
+ }
147
+ seen.add(question.id);
148
+ }
149
+ assertAnswerIds(artifact, path, seen);
150
+ }
151
+
152
+ /**
153
+ * Invariant 7: every answer id is unique, and no id is open and resolved at
154
+ * once. An id names one step of the answer contract (ADR-0022), and that step
155
+ * either waits for a human or holds their answer.
156
+ */
157
+ function assertAnswerIds(artifact: CassetteArtifact, path: string, open: Set<string>): void {
158
+ const seen = new Set<string>();
159
+ const answers = artifact.run?.answers ?? [];
160
+ for (const [index, answer] of answers.entries()) {
161
+ if (seen.has(answer.id)) {
162
+ malformed(path, `run.answers[${index}].id "${answer.id}" is used twice`);
163
+ }
164
+ if (open.has(answer.id)) {
165
+ malformed(path, `run.answers[${index}].id "${answer.id}" is also an open question`);
166
+ }
167
+ seen.add(answer.id);
168
+ }
169
+ }
170
+
130
171
  function upgrade(artifact: CassetteArtifact): Cassette {
131
172
  return { ...artifact, v: CASSETTE_VERSION, run: artifact.run ?? { outcome: "completed" } };
132
173
  }
@@ -141,6 +182,14 @@ export function assertReplayable(cassette: Cassette, path: string): void {
141
182
  `cannot replay interrupted cassette "${path}": the Run died before it settled; use resume instead`,
142
183
  );
143
184
  }
185
+ for (const agent of cassette.agents) {
186
+ for (const [index, ask] of agent.asks.entries()) {
187
+ if (ask.incomplete === undefined) continue;
188
+ throw new Error(
189
+ `cannot replay cassette "${path}": ask ${index} of agent "${agent.spawn.name}" waits for user input and has no settlement; use resume instead`,
190
+ );
191
+ }
192
+ }
144
193
  }
145
194
 
146
195
  /**
@@ -38,6 +38,8 @@ const CassetteSpawnSchema = Type.Object({
38
38
  ...spawnPolicyFields,
39
39
  worktree: Type.Optional(Type.Literal(true)),
40
40
  declaredExtensions: Type.Optional(StringArray),
41
+ canAskUser: Type.Optional(Type.Literal(true)),
42
+ askUserProtocol: Type.Optional(Type.Integer()),
41
43
  parent: Type.Optional(Type.String()),
42
44
  origin: Type.Optional(Type.Literal("fork")),
43
45
  forkOf: Type.Optional(Type.String()),
@@ -112,6 +114,13 @@ const CassetteAskSchema = Type.Object({
112
114
  }),
113
115
  ),
114
116
  recovered: Type.Optional(Type.Literal(true)),
117
+ incomplete: Type.Optional(
118
+ Type.Object({
119
+ kind: Type.Literal("user_input"),
120
+ toolCallId: Type.String(),
121
+ questionId: Type.String(),
122
+ }),
123
+ ),
115
124
  });
116
125
 
117
126
  const TokenBreakdownSchema = Type.Object({
@@ -154,6 +163,21 @@ const CassetteAgentSchema = Type.Object({
154
163
  }),
155
164
  });
156
165
 
166
+ /** One durable Question of a paused run block; no `additionalProperties`, by house rule. */
167
+ const CassetteQuestionSchema = Type.Object({
168
+ id: Type.String(),
169
+ agent: Type.Optional(Type.String()),
170
+ question: Type.String(),
171
+ context: Type.Optional(Type.String()),
172
+ summary: Type.Optional(Type.String()),
173
+ });
174
+
175
+ /** One resolved Question of a resumed run block (ADR-0022). */
176
+ const CassetteAnswerSchema = Type.Object({
177
+ id: Type.String(),
178
+ answer: Type.String(),
179
+ });
180
+
157
181
  const CassetteRunSchema = Type.Object({
158
182
  outcome: Type.Union(
159
183
  (["completed", "failed", "stopped", "paused", "interrupted"] as const).map((outcome) =>
@@ -165,6 +189,9 @@ const CassetteRunSchema = Type.Object({
165
189
  args: Type.Optional(Type.Unknown()),
166
190
  programHash: Type.Optional(Type.String()),
167
191
  profile: Type.Optional(Type.String()),
192
+ questions: Type.Optional(Type.Array(CassetteQuestionSchema)),
193
+ answers: Type.Optional(Type.Array(CassetteAnswerSchema)),
194
+ reason: Type.Optional(Type.String()),
168
195
  });
169
196
 
170
197
  /**
@@ -19,6 +19,37 @@ import { shapeFrame } from "./cassette-frame-shape.ts";
19
19
  /** The Cassette format this runtime writes; the loader also reads version 1. */
20
20
  export const CASSETTE_VERSION = 2 as const;
21
21
 
22
+ /** One durable Question in a paused run block (ADR-0021/0022, spec decision 4). */
23
+ export interface CassetteQuestion {
24
+ /** The author key, the question hash, or `<agent>#<toolCallId>`. */
25
+ readonly id: string;
26
+ /** The Agent that asked; absent for a program Question (ADR-0022). */
27
+ readonly agent?: string;
28
+ readonly question: string;
29
+ /** Free text supplied by the asker. */
30
+ readonly context?: string;
31
+ /** Short restatement of the question: the Question Summary (ADR-0022). */
32
+ readonly summary?: string;
33
+ }
34
+
35
+ /** One resolved Question of a resumed run block: the answer contract (ADR-0022). */
36
+ export interface CassetteAnswer {
37
+ /** The Question id this answer resolved. */
38
+ readonly id: string;
39
+ /** The answer text, exactly as the human supplied it. */
40
+ readonly answer: string;
41
+ }
42
+
43
+ /**
44
+ * Why an Ask sits in the artifact without a settlement (ADR-0021). A
45
+ * discriminated union with one member today, so a later marker adds a `kind`.
46
+ */
47
+ export type CassetteAskIncomplete = {
48
+ readonly kind: "user_input";
49
+ readonly toolCallId: string;
50
+ readonly questionId: string;
51
+ };
52
+
22
53
  /** Run-level settlement record; the ADR-0021 v2 block. */
23
54
  export interface CassetteRun {
24
55
  /** The Run's terminal outcome. `paused` arrives with the pause slice. */
@@ -32,6 +63,12 @@ export interface CassetteRun {
32
63
  readonly programHash?: string;
33
64
  /** Id of the active Profile; absent for a program with no Profiles and for an older Cassette. */
34
65
  readonly profile?: string;
66
+ /** Wake payload of a `paused` or `stopped` Run; absent otherwise (ADR-0021). */
67
+ readonly questions?: readonly CassetteQuestion[];
68
+ /** Questions this Run resolved from `--answers`, plus every inherited one (ADR-0022). */
69
+ readonly answers?: readonly CassetteAnswer[];
70
+ /** The plain `ctx.pause(reason)` text, when the Run gave one. */
71
+ readonly reason?: string;
35
72
  }
36
73
 
37
74
  /** Versioned JSON artifact containing the frames exchanged during one Run. */
@@ -107,6 +144,10 @@ export interface CassetteSpawn {
107
144
  * across machines (ADR-0040). Absent when the Agent ran no extension.
108
145
  */
109
146
  readonly declaredExtensions?: readonly string[];
147
+ /** True when this Agent carried the injected `request_user_input` tool. Hashed. */
148
+ readonly canAskUser?: true;
149
+ /** The recorded tool protocol. Not hashed: it is checked on reactivation. */
150
+ readonly askUserProtocol?: number;
110
151
  /**
111
152
  * Resolved name of the Agent named as this Agent's parent (Parent Link).
112
153
  * Part of spawn identity; absent for a root Agent and for older Cassettes.
@@ -144,6 +185,8 @@ export interface CassetteAsk {
144
185
  readonly outcome?: AskInvalidOutputPlayback;
145
186
  /** Present only when the Stall Watchdog recovered the settlement (ADR-0029). */
146
187
  readonly recovered?: true;
188
+ /** Present only when the Ask parked on `request_user_input` and never settled. */
189
+ readonly incomplete?: CassetteAskIncomplete;
147
190
  }
148
191
 
149
192
  /** Sink consumed by recordingTransport without exposing its mutable state. */
@@ -186,6 +229,7 @@ interface MutableAsk {
186
229
  stalled?: AskStalledOutcome;
187
230
  outcome?: AskInvalidOutputPlayback;
188
231
  recovered?: true;
232
+ incomplete?: CassetteAskIncomplete;
189
233
  }
190
234
 
191
235
  interface MutableCompaction {
@@ -257,6 +301,9 @@ export class CassetteCollector implements CassetteSink {
257
301
  if (completion.stalled !== undefined) ask.stalled = completion.stalled;
258
302
  if (completion.invalidOutput !== undefined) ask.outcome = completion.invalidOutput;
259
303
  if (completion.recovered === true) ask.recovered = true;
304
+ if (completion.parked !== undefined) {
305
+ ask.incomplete = { kind: "user_input", ...completion.parked };
306
+ }
260
307
  },
261
308
  beginCompaction: (marker): void => {
262
309
  if (!agent) return;
@@ -334,6 +381,8 @@ function spawnIdentity(options: OpenOptions): CassetteSpawn {
334
381
  ...(options.declaredExtensions === undefined || options.declaredExtensions.length === 0
335
382
  ? {}
336
383
  : { declaredExtensions: [...options.declaredExtensions] }),
384
+ ...(options.canAskUser === undefined ? {} : { canAskUser: options.canAskUser }),
385
+ ...(options.askUserProtocol === undefined ? {} : { askUserProtocol: options.askUserProtocol }),
337
386
  ...(options.parent === undefined ? {} : { parent: options.parent }),
338
387
  ...(options.origin === undefined ? {} : { origin: options.origin }),
339
388
  ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
@@ -7,11 +7,14 @@ export {
7
7
  CASSETTE_VERSION,
8
8
  type Cassette,
9
9
  type CassetteAgent,
10
+ type CassetteAnswer,
10
11
  type CassetteArtifact,
11
12
  type CassetteAsk,
13
+ type CassetteAskIncomplete,
12
14
  CassetteCollector,
13
15
  type CassetteCompaction,
14
16
  type CassetteGit,
17
+ type CassetteQuestion,
15
18
  type CassetteRun,
16
19
  type CassetteSink,
17
20
  type CassetteSpawn,
@@ -32,7 +35,7 @@ export {
32
35
  profileIdentityWarning,
33
36
  programIdentityWarning,
34
37
  } from "./resume-identity.ts";
35
- export { resumeTransport } from "./resume-transport.ts";
38
+ export { type AskUserRestoration, resumeTransport } from "./resume-transport.ts";
36
39
  export {
37
40
  keepsCheckpoint,
38
41
  type ProgramIdentity,
@@ -40,6 +43,12 @@ export {
40
43
  publishRunCheckpoint,
41
44
  type RunCheckpointResult,
42
45
  type RunIdentityRequest,
46
+ type RunWakePayload,
43
47
  resolveRunIdentity,
44
48
  writeRecordingDiagnostic,
45
49
  } from "./run-checkpoint.ts";
50
+ export {
51
+ appendSessionAnswer,
52
+ restoreSessionAnswers,
53
+ type SessionAnswerAppend,
54
+ } from "./session-answer.ts";
@@ -192,6 +192,7 @@ const SPAWN_OPEN_FIELDS = [
192
192
  "name",
193
193
  ...SPAWN_IDENTITY_FIELDS,
194
194
  "declaredExtensions",
195
+ "canAskUser",
195
196
  "parent",
196
197
  "origin",
197
198
  "forkOf",
@@ -267,6 +268,10 @@ function spawnHash(options: CassetteSpawn | OpenOptions): string {
267
268
  ...(options.declaredExtensions === undefined || options.declaredExtensions.length === 0
268
269
  ? {}
269
270
  : { declaredExtensions: options.declaredExtensions }),
271
+ // Conditional, so a Cassette recorded before ADR-0023 keeps its hash.
272
+ // `askUserProtocol` is deliberately absent: a bumped protocol must refuse
273
+ // the reactivation, and a hash mismatch would start a fresh Agent instead.
274
+ ...(options.canAskUser === undefined ? {} : { canAskUser: options.canAskUser }),
270
275
  ...(options.parent === undefined ? {} : { parent: options.parent }),
271
276
  // Conditional, so a Cassette recorded before forking keeps its hash.
272
277
  ...(options.origin === undefined ? {} : { origin: options.origin }),
@@ -1,4 +1,5 @@
1
1
  import { stat } from "node:fs/promises";
2
+ import { REQUEST_USER_INPUT_PROTOCOL } from "../ask-contract/index.ts";
2
3
  import { YaagError } from "../errors.ts";
3
4
  import type { CassetteAgent } from "./cassette.ts";
4
5
 
@@ -30,6 +31,15 @@ export async function checkResumePreconditions(agent: CassetteAgent): Promise<vo
30
31
  }
31
32
  if (!agent.sessionFile)
32
33
  refuse(name, "has no recorded session file; re-record this Run before resuming");
34
+ // A reactivated Agent restores a dangling `request_user_input` call, so the
35
+ // two sides must speak one protocol (ADR-0023).
36
+ const recorded = agent.spawn.askUserProtocol;
37
+ if (agent.spawn.canAskUser === true && recorded !== REQUEST_USER_INPUT_PROTOCOL) {
38
+ refuse(
39
+ name,
40
+ `recorded request_user_input protocol ${recorded ?? "none"}, this yaag ships protocol ${REQUEST_USER_INPUT_PROTOCOL}`,
41
+ );
42
+ }
33
43
  }
34
44
 
35
45
  async function readHead(cwd: string): Promise<string | null> {