@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
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The one parse policy of a pi session file, and the two structural lookups
3
+ * every caller of it needs.
4
+ *
5
+ * The file is JSONL, one entry per line, pi session version 3. A *half-written*
6
+ * last line is tolerated, because pi may have died mid-write: the writer
7
+ * truncates it away, so the file the append leaves behind parses whole and a
8
+ * second append reads it the same way. Every other bad line is a refusal,
9
+ * including a last line that parses whole but is no entry — those are bytes pi
10
+ * meant to write, and they are never deleted.
11
+ *
12
+ * The "holds this tool call" check is structural: a `toolCall` content part
13
+ * with this id. Never a substring scan, because the same id can appear inside
14
+ * message text, and a false positive appends a dangling result.
15
+ */
16
+ import { PiSessionError } from "./pi-session-error.ts";
17
+
18
+ /** One parsed session entry; only the fields the callers read are named. */
19
+ export interface SessionEntry {
20
+ readonly id?: unknown;
21
+ readonly message?: unknown;
22
+ }
23
+
24
+ /** One content part of a message entry, as pi writes it. */
25
+ export interface ContentPart {
26
+ readonly type?: unknown;
27
+ readonly id?: unknown;
28
+ readonly name?: unknown;
29
+ readonly text?: unknown;
30
+ }
31
+
32
+ /** What one parse yields: the entries, and where an incomplete tail starts. */
33
+ export interface ParsedSession {
34
+ readonly entries: readonly SessionEntry[];
35
+ /**
36
+ * Byte offset of the half-written last line, when there is one. The writer
37
+ * truncates the file here, so the partial line never survives the append.
38
+ *
39
+ * Bytes, never characters: `truncate` takes a byte length, and one non-ASCII
40
+ * character earlier in the session would otherwise move the cut inside a real
41
+ * entry — including the one that holds the parked call.
42
+ */
43
+ readonly truncatedTailAtByte?: number;
44
+ }
45
+
46
+ export function isRecord(value: unknown): value is Record<string, unknown> {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+
50
+ /**
51
+ * Parses every non-empty line of one session text. Only the last line may be
52
+ * incomplete; every other unparsable or non-entry line throws a
53
+ * `PiSessionError` with reason `bad-line`.
54
+ */
55
+ export function parseSession(text: string, path: string): ParsedSession {
56
+ const lines: { line: string; number: number; byte: number }[] = [];
57
+ let byte = 0;
58
+ for (const [index, line] of text.split("\n").entries()) {
59
+ if (line.trim().length > 0) lines.push({ line, number: index + 1, byte });
60
+ // The separator this split consumed is one byte, and so is every newline.
61
+ byte += Buffer.byteLength(line, "utf8") + 1;
62
+ }
63
+ const entries: SessionEntry[] = [];
64
+ let truncatedTailAtByte: number | undefined;
65
+ for (const [index, item] of lines.entries()) {
66
+ const parsed = parseLine(item.line);
67
+ if (parsed.kind === "entry") {
68
+ entries.push(parsed.entry);
69
+ continue;
70
+ }
71
+ if (index === lines.length - 1 && parsed.kind === "incomplete") {
72
+ truncatedTailAtByte = item.byte;
73
+ continue;
74
+ }
75
+ throw new PiSessionError(
76
+ "bad-line",
77
+ `session ${path} line ${item.number} is not a session entry`,
78
+ );
79
+ }
80
+ return truncatedTailAtByte === undefined ? { entries } : { entries, truncatedTailAtByte };
81
+ }
82
+
83
+ /**
84
+ * One line, read three ways: an entry, a complete value that is no entry, or a
85
+ * half-written line. Only the last of the three may be dropped.
86
+ */
87
+ type ParsedLine =
88
+ | { readonly kind: "entry"; readonly entry: SessionEntry }
89
+ | { readonly kind: "not-an-entry" }
90
+ | { readonly kind: "incomplete" };
91
+
92
+ function parseLine(line: string): ParsedLine {
93
+ let parsed: unknown;
94
+ try {
95
+ parsed = JSON.parse(line);
96
+ } catch {
97
+ return { kind: "incomplete" };
98
+ }
99
+ return isRecord(parsed) ? { kind: "entry", entry: parsed } : { kind: "not-an-entry" };
100
+ }
101
+
102
+ /** The entry that holds one tool call, and the tool name that call carries. */
103
+ export interface ToolCallHolder {
104
+ readonly entry: SessionEntry;
105
+ /** The `name` of the `toolCall` part; absent when pi wrote none. */
106
+ readonly toolName?: string;
107
+ }
108
+
109
+ /** The first entry that holds the call as a real `toolCall` part. */
110
+ export function findToolCall(
111
+ entries: readonly SessionEntry[],
112
+ toolCallId: string,
113
+ ): ToolCallHolder | undefined {
114
+ for (const entry of entries) {
115
+ const part = contentParts(entry).find(
116
+ (candidate) => candidate.type === "toolCall" && candidate.id === toolCallId,
117
+ );
118
+ if (part === undefined) continue;
119
+ return typeof part.name === "string" ? { entry, toolName: part.name } : { entry };
120
+ }
121
+ return undefined;
122
+ }
123
+
124
+ export function contentParts(entry: SessionEntry): readonly ContentPart[] {
125
+ const message = entry.message;
126
+ if (!isRecord(message)) return [];
127
+ const content = message.content;
128
+ if (!Array.isArray(content)) return [];
129
+ return content.filter((part): part is ContentPart => isRecord(part));
130
+ }
package/src/public-api.ts CHANGED
@@ -59,6 +59,7 @@ export { isProfiledDefinition, useProfile } from "./profile/use-profile.ts";
59
59
  export { prompt } from "./prompt/prompt.ts";
60
60
  export type { OrchestrationProgram, ProgramDefinition } from "./run/define-run.ts";
61
61
  export { defineRun } from "./run/define-run.ts";
62
+ export type { AskUserOptions, Question } from "./run/questions.ts";
62
63
  export type { RunContext } from "./run/run-context.ts";
63
64
  export type { YaagSystemPromptOptions } from "./system-prompt/agent-system-prompt.ts";
64
65
  export { yaagSystemPrompt } from "./system-prompt/agent-system-prompt.ts";
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Public surface of the `question-summary/` module: the fork summarizer that
3
+ * fills `summary` on an Agent Question (ADR-0022): the policy table and the
4
+ * one-Ask orchestration. The session copy lives in `pi-session/`. It is named
5
+ * for the glossary term, and stays apart from `summary/`, which owns the Run
6
+ * Summary fold.
7
+ * Files inside this directory import each other directly.
8
+ */
9
+
10
+ export {
11
+ type InternalOpen,
12
+ type ParkedAgent,
13
+ type QuestionSummaryResult,
14
+ SUMMARIZER_PROMPT,
15
+ type SummarizeQuestionsRequest,
16
+ summarizeQuestions,
17
+ } from "./summarize-question.ts";
18
+ export { summarizes } from "./summary-policy.ts";
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The fork summarizer (ADR-0022): it writes the Question Summary of every
3
+ * eligible Agent Question, after quiescence and after every Agent is reaped,
4
+ * and before the Checkpoint is published.
5
+ *
6
+ * Every step is best-effort. A failure produces one warning and no summary; it
7
+ * never fails the pause, because a paused Run must always publish.
8
+ */
9
+ import type { SpawnGate } from "../agent/index.ts";
10
+ import type { QuestionSummaryConfig } from "../config/index.ts";
11
+ import { prepareSessionCopy } from "../pi-session/index.ts";
12
+ import type { AgentQuestions } from "../run/index.ts";
13
+ import { summarizes } from "./summary-policy.ts";
14
+
15
+ /**
16
+ * The one Ask the summarizer sends. It states the audience, the length, and the
17
+ * three things the answer must not contain.
18
+ */
19
+ export const SUMMARIZER_PROMPT =
20
+ "Summarize why you ask this question, for the human who answers it. Write 1 to " +
21
+ "3 sentences. Write no preamble, no greeting, and no question.";
22
+
23
+ /** What one summarizer Agent needs from the parked Agent it copies. */
24
+ export interface ParkedAgent {
25
+ readonly name: string;
26
+ /** The concrete resolved model, so the summarizer never re-runs a fallback list. */
27
+ readonly model: string;
28
+ readonly sessionFile: string | undefined;
29
+ }
30
+
31
+ /**
32
+ * The Run's internal open path. It is `SpawnGate.openInternal` itself, so this
33
+ * request shape cannot drift from the one the open path accepts.
34
+ */
35
+ export type InternalOpen = SpawnGate["openInternal"];
36
+
37
+ export interface SummarizeQuestionsRequest {
38
+ readonly questions: AgentQuestions;
39
+ /** The Agents of this Run, already reaped; looked up by name. */
40
+ readonly agents: readonly ParkedAgent[];
41
+ readonly policy: QuestionSummaryConfig;
42
+ readonly openAgent: InternalOpen;
43
+ /**
44
+ * True when the Run replays a Cassette. The recorded summaries are already in
45
+ * the run block, and the temp session copy is long gone, so the summarizer is
46
+ * skipped whole (ADR-0022).
47
+ */
48
+ readonly replaying?: boolean;
49
+ }
50
+
51
+ export interface QuestionSummaryResult {
52
+ /** One line for each failure, naming the Agent and the reason. */
53
+ readonly warnings: readonly string[];
54
+ }
55
+
56
+ /**
57
+ * Summarizes every eligible Question, in order and one at a time.
58
+ *
59
+ * Sequential on purpose: a pause carries few questions, and a parallel fan-out
60
+ * of pi processes at pause time is a resource surprise.
61
+ */
62
+ export async function summarizeQuestions(
63
+ request: SummarizeQuestionsRequest,
64
+ ): Promise<QuestionSummaryResult> {
65
+ if (request.replaying === true) return { warnings: [] };
66
+ const warnings: string[] = [];
67
+ for (const question of request.questions.questions) {
68
+ if (!summarizes(request.policy.policy, question)) continue;
69
+ const parked = request.questions.parked.get(question.id);
70
+ const agent = request.agents.find((one) => one.name === question.agent);
71
+ // Requirement 6 is "any failure warns": a Question with no parked call, or
72
+ // an Agent this Run does not hold, is a failure like every other one.
73
+ if (parked === undefined || agent === undefined) {
74
+ warnings.push(`${question.agent}: question summary failed: the run holds no such agent`);
75
+ continue;
76
+ }
77
+ try {
78
+ const summary = await summarizeOne({ parked: agent, toolCallId: parked.toolCallId, request });
79
+ request.questions.setSummary(question.id, summary);
80
+ } catch (error) {
81
+ warnings.push(`${agent.name}: question summary failed: ${reason(error)}`);
82
+ }
83
+ }
84
+ return { warnings };
85
+ }
86
+
87
+ interface OneRequest {
88
+ readonly parked: ParkedAgent;
89
+ readonly toolCallId: string;
90
+ readonly request: SummarizeQuestionsRequest;
91
+ }
92
+
93
+ /** Copies, spawns, asks, reaps, and deletes. The copy always goes away. */
94
+ async function summarizeOne({ parked, toolCallId, request }: OneRequest): Promise<string> {
95
+ if (parked.sessionFile === undefined) throw new Error("the agent reported no session file");
96
+ const copy = await prepareSessionCopy({ sessionFile: parked.sessionFile, toolCallId });
97
+ try {
98
+ const handle = await request.openAgent({
99
+ spawnOptions: {
100
+ name: `${parked.name}.summary`,
101
+ // No tools and no worktree: this Agent reads its own context and
102
+ // answers. It stays a normal Agent in lifecycle, events, and cost.
103
+ tools: [],
104
+ // The resolved model of the parked Agent by default, never its pattern.
105
+ model: request.policy.model ?? parked.model,
106
+ thinking: request.policy.thinking,
107
+ },
108
+ // The Parent Link is the parked Agent itself, so the tree shows where the
109
+ // summary came from.
110
+ parent: parked,
111
+ askDefaults: undefined,
112
+ definitionName: undefined,
113
+ sessionFile: copy.path,
114
+ });
115
+ try {
116
+ const text = (await handle.ask(SUMMARIZER_PROMPT)).trim();
117
+ if (text.length === 0) throw new Error("the summarizer answered with no text");
118
+ return text;
119
+ } finally {
120
+ await handle.close().catch(() => {});
121
+ }
122
+ } finally {
123
+ await copy.remove();
124
+ }
125
+ }
126
+
127
+ function reason(error: unknown): string {
128
+ return error instanceof Error ? error.message : String(error);
129
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * When the fork summarizer runs for one Question (ADR-0022). Pure: the decision
3
+ * table lives apart from the orchestration that acts on it.
4
+ */
5
+ import type { QuestionSummaryPolicy } from "../config/index.ts";
6
+ import type { Question } from "../run/index.ts";
7
+
8
+ /**
9
+ * True when this Question earns a Question Summary.
10
+ *
11
+ * A program Question never does: it has no Agent, so there is no session to
12
+ * copy and no reasoning to summarize. A Question that already carries a summary
13
+ * never does either: a resume re-opens the Checkpoint's Question with its
14
+ * summary, and it must cost no second model call (ADR-0022). `when-missing`,
15
+ * the default, runs only when the Agent supplied no `context` of its own.
16
+ */
17
+ export function summarizes(policy: QuestionSummaryPolicy, question: Question): boolean {
18
+ if (question.agent === undefined) return false;
19
+ if ((question.summary ?? "").trim().length > 0) return false;
20
+ switch (policy) {
21
+ case "never":
22
+ return false;
23
+ case "always":
24
+ return true;
25
+ case "when-missing":
26
+ return (question.context ?? "").trim().length === 0;
27
+ }
28
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The Run-scoped sink of the questions an Agent asks (ADR-0023).
3
+ *
4
+ * It stays apart from `pause-questions.ts`, which owns the questions the
5
+ * program asks: a question raised from an Ask's frame handler must never throw,
6
+ * so this registry refuses nothing and repeats are inert.
7
+ */
8
+ import type { ParkedAsk } from "../cassette/index.ts";
9
+ import { agentQuestionId } from "./question-id.ts";
10
+ import type { Question } from "./questions.ts";
11
+
12
+ /** One parked question, as the Ask that observed the frame reports it. */
13
+ export interface AgentQuestionRequest {
14
+ readonly agent: string;
15
+ readonly toolCallId: string;
16
+ readonly question: string;
17
+ readonly context?: string;
18
+ }
19
+
20
+ /** The parked call alone: the Agent name and the tool call id that key it. */
21
+ export interface AgentParkRequest {
22
+ readonly agent: string;
23
+ readonly toolCallId: string;
24
+ }
25
+
26
+ /** One Question a resume re-opens, with the parked call it belongs to. */
27
+ export interface SeededQuestion {
28
+ /** The recorded Question: id, text, context and Question Summary. */
29
+ readonly question: Question;
30
+ /** The parked call the incomplete marker names. */
31
+ readonly parked: AgentQuestionRequest;
32
+ }
33
+
34
+ /** The Agent questions of one Run, and the signal the Run races. */
35
+ export interface AgentQuestions {
36
+ /**
37
+ * Records one parked question, raises the Run's pause, and returns the
38
+ * durable id of the Question. Idempotent per id.
39
+ */
40
+ raise(request: AgentQuestionRequest): string;
41
+ /**
42
+ * Holds the open Questions of a Checkpoint apart, ready for the Ask that
43
+ * parks on them. A seeded Question is invisible until it is parked, and
44
+ * seeding raises no pause signal: a resume that diverges before the parked
45
+ * Ask must publish no Question (ADR-0022/0023).
46
+ */
47
+ seed(seeds: readonly SeededQuestion[]): void;
48
+ /**
49
+ * Marks the parked call open, and returns the durable id of its Question. A
50
+ * seeded Question keeps its recorded text, context and summary.
51
+ */
52
+ park(request: AgentParkRequest): string;
53
+ readonly questions: readonly Question[];
54
+ /**
55
+ * The parked calls, keyed by Question id. The fork summarizer reads the tool
56
+ * call from here rather than parsing it back out of the id (ADR-0022).
57
+ */
58
+ readonly parked: ReadonlyMap<string, AgentQuestionRequest>;
59
+ /**
60
+ * Writes one Question Summary, before the Checkpoint is published, so the
61
+ * summary is durable in the Cassette (ADR-0022). An unknown id is inert.
62
+ */
63
+ setSummary(id: string, summary: string): void;
64
+ /** Resolves at the first raised question; the Run races it and drains naturally. */
65
+ readonly raised: Promise<void>;
66
+ }
67
+
68
+ /** Builds the Agent question registry of one Run. */
69
+ export function createAgentQuestions(): AgentQuestions {
70
+ const byId = new Map<string, Question>();
71
+ const parked = new Map<string, AgentQuestionRequest>();
72
+ let signal: () => void = () => {};
73
+ const raised = new Promise<void>((resolve) => {
74
+ signal = resolve;
75
+ });
76
+ const seeded = new Map<string, SeededQuestion>();
77
+ /** Moves one seeded Question into the open set, with its recorded record. */
78
+ const promote = (id: string): boolean => {
79
+ const seed = seeded.get(id);
80
+ if (seed === undefined) return false;
81
+ seeded.delete(id);
82
+ if (!byId.has(id)) {
83
+ parked.set(id, seed.parked);
84
+ byId.set(id, seed.question);
85
+ }
86
+ signal();
87
+ return true;
88
+ };
89
+ return {
90
+ raise(request: AgentQuestionRequest): string {
91
+ // The ADR's key: the Agent name and the tool call id of the parked call.
92
+ const id = agentQuestionId(request.agent, request.toolCallId);
93
+ if (promote(id)) return id;
94
+ if (byId.has(id)) return id;
95
+ parked.set(id, request);
96
+ byId.set(id, {
97
+ id,
98
+ agent: request.agent,
99
+ question: request.question,
100
+ ...(request.context === undefined ? {} : { context: request.context }),
101
+ });
102
+ signal();
103
+ return id;
104
+ },
105
+ seed(seeds: readonly SeededQuestion[]): void {
106
+ for (const seed of seeds) {
107
+ const id = seed.question.id;
108
+ if (byId.has(id) || seeded.has(id)) continue;
109
+ seeded.set(id, seed);
110
+ }
111
+ },
112
+ park(request: AgentParkRequest): string {
113
+ const id = agentQuestionId(request.agent, request.toolCallId);
114
+ if (!promote(id)) signal();
115
+ return id;
116
+ },
117
+ get questions(): readonly Question[] {
118
+ return [...byId.values()];
119
+ },
120
+ parked,
121
+ setSummary(id: string, summary: string): void {
122
+ const question = byId.get(id);
123
+ if (question === undefined) return;
124
+ byId.set(id, { ...question, summary });
125
+ },
126
+ raised,
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Seeds the registry from the open Questions of a Checkpoint (ADR-0022/0023).
132
+ *
133
+ * Only a Question that an Agent raised is seeded, and only when an incomplete
134
+ * marker names it: a program Question is raised again by the program itself.
135
+ */
136
+ export function seedFromResume(options: {
137
+ readonly questions: AgentQuestions;
138
+ readonly open: readonly Question[];
139
+ readonly parked: readonly ParkedAsk[];
140
+ }): void {
141
+ const seeds: SeededQuestion[] = [];
142
+ for (const question of options.open) {
143
+ if (question.agent === undefined) continue;
144
+ const mark = options.parked.find((entry) => entry.questionId === question.id);
145
+ if (mark === undefined) continue;
146
+ seeds.push({
147
+ question,
148
+ parked: {
149
+ agent: mark.agent,
150
+ toolCallId: mark.toolCallId,
151
+ question: question.question,
152
+ ...(question.context === undefined ? {} : { context: question.context }),
153
+ },
154
+ });
155
+ }
156
+ options.questions.seed(seeds);
157
+ }
@@ -0,0 +1,91 @@
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, ParkedAsk } from "../cassette/index.ts";
9
+ import { YaagError } from "../errors.ts";
10
+ import type { Question } from "./questions.ts";
11
+
12
+ /** What one resume knows about its answers. */
13
+ export interface AnswerLedger {
14
+ /** The answer for this Question id, or undefined when it stays open. */
15
+ take(id: string): string | undefined;
16
+ /** Every resolved step the successor Cassette must carry. */
17
+ resolved(): readonly CassetteAnswer[];
18
+ /**
19
+ * The Questions of the resume source that no answer resolves. They are the
20
+ * Questions of this resume: id, text, context and Question Summary come from
21
+ * the run block, not from the recorded frames (ADR-0022).
22
+ */
23
+ open(): readonly Question[];
24
+ }
25
+
26
+ export interface AnswerLedgerOptions {
27
+ /** What `--answers` supplied, keyed by Question id. */
28
+ readonly supplied: Readonly<Record<string, string>>;
29
+ /** The open Questions of the resume source. */
30
+ readonly questions: readonly CassetteQuestion[];
31
+ /** The answers the resume source already resolved. */
32
+ readonly inherited: readonly CassetteAnswer[];
33
+ /** The incomplete-Ask markers of the resume source (ADR-0023). */
34
+ readonly parked?: readonly ParkedAsk[];
35
+ }
36
+
37
+ /**
38
+ * Builds the ledger, and refuses the resume when an answer names nothing open
39
+ * or contradicts an inherited answer. A repeated `--answers` of the same text
40
+ * is accepted, so retrying one resume is safe.
41
+ */
42
+ export function createAnswerLedger(options: AnswerLedgerOptions): AnswerLedger {
43
+ const open = new Set(options.questions.map((question) => question.id));
44
+ const resolved = new Map<string, string>(
45
+ options.inherited.map((answer) => [answer.id, answer.answer] as const),
46
+ );
47
+ for (const [id, answer] of Object.entries(options.supplied)) {
48
+ const known = resolved.get(id);
49
+ if (known !== undefined) {
50
+ // Idempotent: the same answer again resolves the same step.
51
+ if (known === answer) continue;
52
+ throw new YaagError(
53
+ "RESUME_REFUSED",
54
+ `the question "${id}" is already answered with "${known}" — ` +
55
+ `it cannot be answered with "${answer}" as well`,
56
+ );
57
+ }
58
+ if (!open.has(id)) {
59
+ throw new YaagError(
60
+ "RESUME_REFUSED",
61
+ `the answer key "${id}" names no open question of this checkpoint`,
62
+ );
63
+ }
64
+ resolved.set(id, answer);
65
+ }
66
+ for (const mark of options.parked ?? []) {
67
+ if (open.has(mark.questionId) || resolved.has(mark.questionId)) continue;
68
+ throw new YaagError(
69
+ "RESUME_REFUSED",
70
+ `the checkpoint records agent "${mark.agent}" parked on question ` +
71
+ `"${mark.questionId}", and its run block holds no such question — ` +
72
+ "the checkpoint is incomplete",
73
+ );
74
+ }
75
+ return {
76
+ take(id: string): string | undefined {
77
+ return resolved.get(id);
78
+ },
79
+ resolved(): readonly CassetteAnswer[] {
80
+ return [...resolved].map(([id, answer]) => ({ id, answer }));
81
+ },
82
+ open(): readonly Question[] {
83
+ return options.questions.filter((question) => !resolved.has(question.id));
84
+ },
85
+ };
86
+ }
87
+
88
+ /** The empty ledger of a Run that resumes nothing: it answers no question. */
89
+ export function emptyAnswerLedger(): AnswerLedger {
90
+ return createAnswerLedger({ supplied: {}, questions: [], inherited: [] });
91
+ }