@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
@@ -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
+ }
@@ -8,13 +8,14 @@ import {
8
8
  type CassetteAsk,
9
9
  } from "./cassette.ts";
10
10
  import { CassetteSchema } from "./cassette-schema.ts";
11
+ import { readableCassette } from "./checkpoint.ts";
11
12
 
12
13
  /**
13
14
  * Reads and validates one Cassette artifact before replay begins.
14
15
  *
15
16
  * Rejects unreadable, unparsable, unsupported, and malformed artifacts at the
16
17
  * filesystem boundary; replay never receives unchecked external data. The
17
- * schema checks structure; the five named invariants below check semantics.
18
+ * schema checks structure; the seven named invariants below check semantics.
18
19
  * A version 1 artifact is upgraded in memory to version 2 (ADR-0021).
19
20
  * Unknown fields are retained, never dropped (forward tolerance).
20
21
  * The bytes are gzip-compressed JSON, or the plain JSON that older runtimes
@@ -38,6 +39,7 @@ export async function loadCassette(path: string): Promise<Cassette> {
38
39
  if (errors.length > 0) malformed(path, formatValidationErrors(value, errors).join("; "));
39
40
  const artifact = value as CassetteArtifact; // sound: CassetteSchemaIsSound (cassette-schema.ts)
40
41
  assertRunPresence(artifact, path);
42
+ assertUniqueQuestionIds(artifact, path);
41
43
  for (const [agentIndex, agent] of artifact.agents.entries()) {
42
44
  agent.asks.forEach((ask, askIndex) => {
43
45
  const label = `agents[${agentIndex}].asks[${askIndex}]`;
@@ -127,32 +129,68 @@ function assertRunPresence(artifact: CassetteArtifact, path: string): void {
127
129
  }
128
130
  }
129
131
 
130
- function upgrade(artifact: CassetteArtifact): Cassette {
131
- return { ...artifact, v: CASSETTE_VERSION, run: artifact.run ?? { outcome: "completed" } };
132
+ /**
133
+ * Invariant 6: every Question id is unique. The answer contract addresses a
134
+ * Question by id (ADR-0022), so a repeated id would make a resume guess.
135
+ *
136
+ * Deliberately not checked: that every `ask.incomplete.questionId` names a
137
+ * Question of this run block. A `stopped` artifact can hold a parked Ask whose
138
+ * Question the drain never collected, and the loader must not refuse an
139
+ * artifact yaag itself writes. The loader stays permissive on purpose: the rule
140
+ * belongs to resume, which refuses such a marker at ledger construction, in
141
+ * `run/answers.ts`, before the first Agent starts (ADR-0022/ADR-0023).
142
+ */
143
+ function assertUniqueQuestionIds(artifact: CassetteArtifact, path: string): void {
144
+ const seen = new Set<string>();
145
+ const questions = artifact.run?.questions ?? [];
146
+ for (const [index, question] of questions.entries()) {
147
+ if (seen.has(question.id)) {
148
+ malformed(path, `run.questions[${index}].id "${question.id}" is used twice`);
149
+ }
150
+ seen.add(question.id);
151
+ }
152
+ assertAnswerIds(artifact, path, seen);
132
153
  }
133
154
 
134
155
  /**
135
- * Strict replay demands a settled Run. An `interrupted` artifact stops at the
136
- * last Ask boundary, so its final Ask has no recorded settlement (ADR-0031).
156
+ * Invariant 7: every answer id is unique, and no id is open and resolved at
157
+ * once. An id names one step of the answer contract (ADR-0022), and that step
158
+ * either waits for a human or holds their answer.
137
159
  */
138
- export function assertReplayable(cassette: Cassette, path: string): void {
139
- if (cassette.run.outcome === "interrupted") {
140
- throw new Error(
141
- `cannot replay interrupted cassette "${path}": the Run died before it settled; use resume instead`,
142
- );
160
+ function assertAnswerIds(artifact: CassetteArtifact, path: string, open: Set<string>): void {
161
+ const seen = new Set<string>();
162
+ const answers = artifact.run?.answers ?? [];
163
+ for (const [index, answer] of answers.entries()) {
164
+ if (seen.has(answer.id)) {
165
+ malformed(path, `run.answers[${index}].id "${answer.id}" is used twice`);
166
+ }
167
+ if (open.has(answer.id)) {
168
+ malformed(path, `run.answers[${index}].id "${answer.id}" is also an open question`);
169
+ }
170
+ seen.add(answer.id);
143
171
  }
144
172
  }
145
173
 
174
+ function upgrade(artifact: CassetteArtifact): Cassette {
175
+ return { ...artifact, v: CASSETTE_VERSION, run: artifact.run ?? { outcome: "completed" } };
176
+ }
177
+
146
178
  /**
147
- * Warns once when a resume source came from a hard death. The Run continues:
148
- * resume already handles an incomplete last Ask.
179
+ * Strict replay demands a settled Run. The `interrupted` refusal is the
180
+ * Checkpoint's own read-side rule (ADR-0031); the parked-Ask refusal below is a
181
+ * replay rule and stays here.
149
182
  */
150
- export function interruptedResumeWarning(cassette: Cassette, path: string): string | null {
151
- if (cassette.run.outcome !== "interrupted") return null;
152
- return (
153
- `resuming interrupted cassette "${path}": the Run died before it settled, ` +
154
- "the recording stops at the last Ask boundary, and re-run tools can repeat their effects"
155
- );
183
+ export function assertReplayable(cassette: Cassette, path: string): void {
184
+ const readable = readableCassette(cassette, path, "replay");
185
+ if (!readable.ok) throw new Error(readable.reason);
186
+ for (const agent of cassette.agents) {
187
+ for (const [index, ask] of agent.asks.entries()) {
188
+ if (ask.incomplete === undefined) continue;
189
+ throw new Error(
190
+ `cannot replay cassette "${path}": ask ${index} of agent "${agent.spawn.name}" waits for user input and has no settlement; use resume instead`,
191
+ );
192
+ }
193
+ }
156
194
  }
157
195
 
158
196
  function message(error: unknown): string {
@@ -21,6 +21,11 @@ const ThinkingSchema = Type.Union(
21
21
 
22
22
  const StringArray = Type.Array(Type.String());
23
23
 
24
+ /**
25
+ * The policy half of a recorded spawn. It mirrors the rows the spawn field
26
+ * table marks `askContext` (`spawn-identity.ts`), minus `cwd` and `worktree`,
27
+ * which the two schemas below place themselves.
28
+ */
24
29
  const spawnPolicyFields = {
25
30
  model: Type.Optional(Type.String()),
26
31
  systemPrompt: Type.Optional(Type.String()),
@@ -38,8 +43,13 @@ const CassetteSpawnSchema = Type.Object({
38
43
  ...spawnPolicyFields,
39
44
  worktree: Type.Optional(Type.Literal(true)),
40
45
  declaredExtensions: Type.Optional(StringArray),
46
+ canAskUser: Type.Optional(Type.Literal(true)),
47
+ askUserProtocol: Type.Optional(Type.Integer()),
41
48
  parent: Type.Optional(Type.String()),
42
- origin: Type.Optional(Type.Literal("fork")),
49
+ origin: Type.Optional(
50
+ Type.Union([Type.Literal("spawn"), Type.Literal("fork"), Type.Literal("host-fork")]),
51
+ ),
52
+ hostHash: Type.Optional(Type.String()),
43
53
  forkOf: Type.Optional(Type.String()),
44
54
  forkAsks: Type.Optional(Type.Number()),
45
55
  });
@@ -112,6 +122,13 @@ const CassetteAskSchema = Type.Object({
112
122
  }),
113
123
  ),
114
124
  recovered: Type.Optional(Type.Literal(true)),
125
+ incomplete: Type.Optional(
126
+ Type.Object({
127
+ kind: Type.Literal("user_input"),
128
+ toolCallId: Type.String(),
129
+ questionId: Type.String(),
130
+ }),
131
+ ),
115
132
  });
116
133
 
117
134
  const TokenBreakdownSchema = Type.Object({
@@ -154,6 +171,21 @@ const CassetteAgentSchema = Type.Object({
154
171
  }),
155
172
  });
156
173
 
174
+ /** One durable Question of a paused run block; no `additionalProperties`, by house rule. */
175
+ const CassetteQuestionSchema = Type.Object({
176
+ id: Type.String(),
177
+ agent: Type.Optional(Type.String()),
178
+ question: Type.String(),
179
+ context: Type.Optional(Type.String()),
180
+ summary: Type.Optional(Type.String()),
181
+ });
182
+
183
+ /** One resolved Question of a resumed run block (ADR-0022). */
184
+ const CassetteAnswerSchema = Type.Object({
185
+ id: Type.String(),
186
+ answer: Type.String(),
187
+ });
188
+
157
189
  const CassetteRunSchema = Type.Object({
158
190
  outcome: Type.Union(
159
191
  (["completed", "failed", "stopped", "paused", "interrupted"] as const).map((outcome) =>
@@ -165,6 +197,10 @@ const CassetteRunSchema = Type.Object({
165
197
  args: Type.Optional(Type.Unknown()),
166
198
  programHash: Type.Optional(Type.String()),
167
199
  profile: Type.Optional(Type.String()),
200
+ host: Type.Optional(Type.Object({ hostHash: Type.String() })),
201
+ questions: Type.Optional(Type.Array(CassetteQuestionSchema)),
202
+ answers: Type.Optional(Type.Array(CassetteAnswerSchema)),
203
+ reason: Type.Optional(Type.String()),
168
204
  });
169
205
 
170
206
  /**
@@ -1,6 +1,6 @@
1
1
  import type { CanonicalJsonObject } from "../ask-contract/index.ts";
2
2
  import type { AskLimitOutcome, AskStalledOutcome } from "../errors.ts";
3
- import type { RunOutcome } from "../events.ts";
3
+ import type { RunOutcome, SpawnOrigin } from "../events.ts";
4
4
  import type {
5
5
  AgentStats,
6
6
  AskCompletion,
@@ -15,10 +15,42 @@ import type {
15
15
  } from "../transport/index.ts";
16
16
  import type { ThinkingLevel } from "../types.ts";
17
17
  import { shapeFrame } from "./cassette-frame-shape.ts";
18
+ import { fromOpenOptions } from "./spawn-identity.ts";
18
19
 
19
20
  /** The Cassette format this runtime writes; the loader also reads version 1. */
20
21
  export const CASSETTE_VERSION = 2 as const;
21
22
 
23
+ /** One durable Question in a paused run block (ADR-0021/0022, spec decision 4). */
24
+ export interface CassetteQuestion {
25
+ /** The author key, the question hash, or `<agent>#<toolCallId>`. */
26
+ readonly id: string;
27
+ /** The Agent that asked; absent for a program Question (ADR-0022). */
28
+ readonly agent?: string;
29
+ readonly question: string;
30
+ /** Free text supplied by the asker. */
31
+ readonly context?: string;
32
+ /** Short restatement of the question: the Question Summary (ADR-0022). */
33
+ readonly summary?: string;
34
+ }
35
+
36
+ /** One resolved Question of a resumed run block: the answer contract (ADR-0022). */
37
+ export interface CassetteAnswer {
38
+ /** The Question id this answer resolved. */
39
+ readonly id: string;
40
+ /** The answer text, exactly as the human supplied it. */
41
+ readonly answer: string;
42
+ }
43
+
44
+ /**
45
+ * Why an Ask sits in the artifact without a settlement (ADR-0021). A
46
+ * discriminated union with one member today, so a later marker adds a `kind`.
47
+ */
48
+ export type CassetteAskIncomplete = {
49
+ readonly kind: "user_input";
50
+ readonly toolCallId: string;
51
+ readonly questionId: string;
52
+ };
53
+
22
54
  /** Run-level settlement record; the ADR-0021 v2 block. */
23
55
  export interface CassetteRun {
24
56
  /** The Run's terminal outcome. `paused` arrives with the pause slice. */
@@ -32,6 +64,14 @@ export interface CassetteRun {
32
64
  readonly programHash?: string;
33
65
  /** Id of the active Profile; absent for a program with no Profiles and for an older Cassette. */
34
66
  readonly profile?: string;
67
+ /** The Host Source this Run was given (ADR-0068). Run-level: ctx.host exists before any spawn. */
68
+ readonly host?: { readonly hostHash: string };
69
+ /** Wake payload of a `paused` or `stopped` Run; absent otherwise (ADR-0021). */
70
+ readonly questions?: readonly CassetteQuestion[];
71
+ /** Questions this Run resolved from `--answers`, plus every inherited one (ADR-0022). */
72
+ readonly answers?: readonly CassetteAnswer[];
73
+ /** The plain `ctx.pause(reason)` text, when the Run gave one. */
74
+ readonly reason?: string;
35
75
  }
36
76
 
37
77
  /** Versioned JSON artifact containing the frames exchanged during one Run. */
@@ -107,13 +147,22 @@ export interface CassetteSpawn {
107
147
  * across machines (ADR-0040). Absent when the Agent ran no extension.
108
148
  */
109
149
  readonly declaredExtensions?: readonly string[];
150
+ /** True when this Agent carried the injected `request_user_input` tool. Hashed. */
151
+ readonly canAskUser?: true;
152
+ /** The recorded tool protocol. Not hashed: it is checked on reactivation. */
153
+ readonly askUserProtocol?: number;
110
154
  /**
111
155
  * Resolved name of the Agent named as this Agent's parent (Parent Link).
112
156
  * Part of spawn identity; absent for a root Agent and for older Cassettes.
113
157
  */
114
158
  readonly parent?: string;
115
159
  /** How the Agent came to be; absent means an ordinary spawn. Spawn identity. */
116
- readonly origin?: "fork";
160
+ readonly origin?: SpawnOrigin;
161
+ /**
162
+ * SHA-256 of the Host Session bytes a Host Fork was taken from. Spawn
163
+ * identity; the copy path is not (ADR-0068).
164
+ */
165
+ readonly hostHash?: string;
117
166
  /** Name of the Agent this one was forked from. Spawn identity. */
118
167
  readonly forkOf?: string;
119
168
  /** Settled Asks of the fork source at the fork point. Spawn identity. */
@@ -144,6 +193,8 @@ export interface CassetteAsk {
144
193
  readonly outcome?: AskInvalidOutputPlayback;
145
194
  /** Present only when the Stall Watchdog recovered the settlement (ADR-0029). */
146
195
  readonly recovered?: true;
196
+ /** Present only when the Ask parked on `request_user_input` and never settled. */
197
+ readonly incomplete?: CassetteAskIncomplete;
147
198
  }
148
199
 
149
200
  /** Sink consumed by recordingTransport without exposing its mutable state. */
@@ -186,6 +237,7 @@ interface MutableAsk {
186
237
  stalled?: AskStalledOutcome;
187
238
  outcome?: AskInvalidOutputPlayback;
188
239
  recovered?: true;
240
+ incomplete?: CassetteAskIncomplete;
189
241
  }
190
242
 
191
243
  interface MutableCompaction {
@@ -218,7 +270,7 @@ export class CassetteCollector implements CassetteSink {
218
270
 
219
271
  reserve(options: OpenOptions): CassetteRecorder {
220
272
  const slot = this.#agents.length;
221
- const spawn = spawnIdentity(options);
273
+ const spawn = fromOpenOptions(options);
222
274
  let agent: MutableAgent | null = null;
223
275
  this.#agents.push(null);
224
276
  return {
@@ -257,6 +309,9 @@ export class CassetteCollector implements CassetteSink {
257
309
  if (completion.stalled !== undefined) ask.stalled = completion.stalled;
258
310
  if (completion.invalidOutput !== undefined) ask.outcome = completion.invalidOutput;
259
311
  if (completion.recovered === true) ask.recovered = true;
312
+ if (completion.parked !== undefined) {
313
+ ask.incomplete = { kind: "user_input", ...completion.parked };
314
+ }
260
315
  },
261
316
  beginCompaction: (marker): void => {
262
317
  if (!agent) return;
@@ -313,35 +368,6 @@ export class CassetteCollector implements CassetteSink {
313
368
  }
314
369
  }
315
370
 
316
- function spawnIdentity(options: OpenOptions): CassetteSpawn {
317
- return {
318
- name: options.name,
319
- cwd: options.cwd,
320
- ...(options.model === undefined ? {} : { model: options.model }),
321
- ...(options.systemPrompt === undefined ? {} : { systemPrompt: options.systemPrompt }),
322
- ...(options.thinking === undefined ? {} : { thinking: options.thinking }),
323
- ...(options.appendSystemPrompt === undefined
324
- ? {}
325
- : { appendSystemPrompt: options.appendSystemPrompt }),
326
- ...(options.tools === undefined ? {} : { tools: [...options.tools] }),
327
- ...(options.disallowedTools === undefined
328
- ? {}
329
- : { disallowedTools: [...options.disallowedTools] }),
330
- ...(options.skills === undefined ? {} : { skills: [...options.skills] }),
331
- ...(options.disallowedSkills === undefined
332
- ? {}
333
- : { disallowedSkills: [...options.disallowedSkills] }),
334
- ...(options.declaredExtensions === undefined || options.declaredExtensions.length === 0
335
- ? {}
336
- : { declaredExtensions: [...options.declaredExtensions] }),
337
- ...(options.parent === undefined ? {} : { parent: options.parent }),
338
- ...(options.origin === undefined ? {} : { origin: options.origin }),
339
- ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
340
- ...(options.forkAsks === undefined ? {} : { forkAsks: options.forkAsks }),
341
- ...(options.worktree === true ? { worktree: true } : {}),
342
- };
343
- }
344
-
345
371
  /** The Ask that later frames belong to, or nothing when a compaction owns them. */
346
372
  function activeAsk(agent: MutableAgent | null): MutableAsk | null {
347
373
  const active = agent?.active;