@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.
- package/package.json +2 -3
- package/src/agent/agent.ts +46 -6
- package/src/agent/ask-user-capability.ts +36 -0
- package/src/agent/index.ts +3 -1
- package/src/agent/spawn-open.ts +24 -5
- package/src/agent/spawn-request.ts +18 -1
- package/src/agent/spawn.ts +31 -9
- package/src/agent/spawnable-definition.ts +9 -0
- package/src/ask/ask-exchange-options.ts +5 -0
- package/src/ask/ask-exchange.ts +67 -2
- package/src/ask/ask-settlement.ts +8 -0
- package/src/ask/idle-watch.ts +12 -2
- package/src/ask/stall-watchdog.ts +13 -3
- package/src/ask-contract/ask-limit.ts +24 -6
- package/src/ask-contract/index.ts +8 -0
- package/src/ask-contract/request-user-input-extension.ts +105 -0
- package/src/ask-contract/request-user-input.ts +58 -0
- package/src/cassette/cassette-loader.ts +50 -1
- package/src/cassette/cassette-schema.ts +27 -0
- package/src/cassette/cassette.ts +49 -0
- package/src/cassette/index.ts +10 -1
- package/src/cassette/replay-divergence.ts +5 -0
- package/src/cassette/resume-preconditions.ts +10 -0
- package/src/cassette/resume-transport.ts +111 -6
- package/src/cassette/run-checkpoint.ts +52 -3
- package/src/cassette/session-answer.ts +163 -0
- package/src/catalog/index.ts +5 -3
- package/src/catalog/registry-reader.ts +1 -1
- package/src/catalog/resolve.ts +184 -0
- package/src/config/config-schema.ts +33 -0
- package/src/config/effective-config.ts +53 -0
- package/src/config/index.ts +4 -0
- package/src/contract/agent-policy.ts +9 -0
- package/src/contract/catalog-resolve.ts +33 -0
- package/src/contract/error-codes.ts +5 -2
- package/src/contract/index.ts +10 -2
- package/src/control/index.ts +2 -0
- package/src/control/pause-drain.ts +81 -24
- package/src/errors.ts +8 -2
- package/src/events.ts +6 -0
- package/src/index.ts +18 -2
- package/src/model/index.ts +1 -1
- package/src/public-api.ts +7 -0
- package/src/question-summary/index.ts +22 -0
- package/src/question-summary/session-copy.ts +169 -0
- package/src/question-summary/summarize-question.ts +129 -0
- package/src/question-summary/summary-policy.ts +25 -0
- package/src/run/agent-questions.ts +75 -0
- package/src/run/answers.ts +70 -0
- package/src/run/index.ts +5 -0
- package/src/run/pause-questions.ts +98 -0
- package/src/run/pause-signal.ts +32 -0
- package/src/run/question-id.ts +18 -0
- package/src/run/questions.ts +31 -0
- package/src/run/run-context.ts +26 -1
- package/src/run/run-result.ts +21 -0
- package/src/run/run-settlement.ts +36 -4
- package/src/run/run.ts +119 -20
- package/src/system-prompt/agent-system-prompt.ts +1 -1
- package/src/transport/pi-state.ts +21 -4
- package/src/transport/tool-probe.ts +4 -0
- package/src/transport/transport.ts +26 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session copy the fork summarizer reads (ADR-0022).
|
|
3
|
+
*
|
|
4
|
+
* The parked Agent is incomplete, so it cannot be forked: yaag copies its pi
|
|
5
|
+
* session file instead, and closes the pending `request_user_input` call with a
|
|
6
|
+
* synthetic `toolResult`. pi refuses to continue a session whose last assistant
|
|
7
|
+
* message has an unanswered tool call, and the copy keeps the parked Agent's
|
|
8
|
+
* own file untouched.
|
|
9
|
+
*/
|
|
10
|
+
import { copyFile, readFile, rm, writeFile } from "node:fs/promises";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What the summarizer session reads in place of the human's answer. It states
|
|
16
|
+
* three facts: no answer arrived, this session is a copy, and the task is over.
|
|
17
|
+
*/
|
|
18
|
+
export const SYNTHETIC_TOOL_RESULT_TEXT =
|
|
19
|
+
"The human has not answered yet. This session is a copy of your session, made " +
|
|
20
|
+
"only to summarize your question. Do not continue your task.";
|
|
21
|
+
|
|
22
|
+
/** One prepared copy: where it is, and how to remove it again. */
|
|
23
|
+
export interface SessionCopy {
|
|
24
|
+
/** Absolute path of the copy; hand it to `pi --session`. */
|
|
25
|
+
readonly path: string;
|
|
26
|
+
/** Removes the copy. Best effort: it never throws. */
|
|
27
|
+
remove(): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What one copy needs: the source session and the call to close. */
|
|
31
|
+
export interface SessionCopyRequest {
|
|
32
|
+
readonly sessionFile: string;
|
|
33
|
+
readonly toolCallId: string;
|
|
34
|
+
/** Where the copy goes; the OS temp directory by default. */
|
|
35
|
+
readonly directory?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Copies one pi session and appends the synthetic `toolResult`.
|
|
40
|
+
*
|
|
41
|
+
* Rejects when the source cannot be read, when its last
|
|
42
|
+
* line is not a complete JSON entry, or when no entry carries the parked tool
|
|
43
|
+
* call: a dangling result would corrupt the copy, and the summary is
|
|
44
|
+
* best-effort, so a refusal here is the correct outcome.
|
|
45
|
+
*/
|
|
46
|
+
export async function prepareSessionCopy(request: SessionCopyRequest): Promise<SessionCopy> {
|
|
47
|
+
const text = await readSession(request.sessionFile);
|
|
48
|
+
const entries = parseEntries(text, request.sessionFile);
|
|
49
|
+
if (!carriesToolCall(entries, request.toolCallId)) {
|
|
50
|
+
throw new Error(`session ${request.sessionFile} has no tool call ${request.toolCallId}`);
|
|
51
|
+
}
|
|
52
|
+
// The appended entry hangs below the current leaf. A leaf with no string id
|
|
53
|
+
// would detach it from pi's session tree, which is the very corruption the
|
|
54
|
+
// refusals above exist to prevent, so it refuses too.
|
|
55
|
+
const leaf = entries.at(-1);
|
|
56
|
+
if (typeof leaf?.id !== "string") {
|
|
57
|
+
throw new Error(`session ${request.sessionFile} ends with an entry that has no id`);
|
|
58
|
+
}
|
|
59
|
+
const parentId: string = leaf.id;
|
|
60
|
+
const path = join(
|
|
61
|
+
request.directory ?? tmpdir(),
|
|
62
|
+
`yaag-summary-${Date.now()}-${Math.random().toString(16).slice(2)}.jsonl`,
|
|
63
|
+
);
|
|
64
|
+
const copy: SessionCopy = {
|
|
65
|
+
path,
|
|
66
|
+
remove: async (): Promise<void> => {
|
|
67
|
+
try {
|
|
68
|
+
await rm(path, { force: true });
|
|
69
|
+
} catch {
|
|
70
|
+
// best effort: a leftover temp file must never fail a Run
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
await copyFile(request.sessionFile, path);
|
|
76
|
+
const line = JSON.stringify(syntheticEntry({ toolCallId: request.toolCallId, parentId }));
|
|
77
|
+
await writeFile(path, `${text.endsWith("\n") ? "" : "\n"}${line}\n`, { flag: "a" });
|
|
78
|
+
} catch (error) {
|
|
79
|
+
await copy.remove();
|
|
80
|
+
throw new Error(`cannot prepare a session copy: ${String(error)}`);
|
|
81
|
+
}
|
|
82
|
+
return copy;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One parsed session entry; only the fields this module reads are named. */
|
|
86
|
+
interface SessionEntry {
|
|
87
|
+
readonly id?: unknown;
|
|
88
|
+
readonly message?: unknown;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** One assistant tool call, as pi writes it into a session entry. */
|
|
92
|
+
interface ToolCallPart {
|
|
93
|
+
readonly type?: unknown;
|
|
94
|
+
readonly id?: unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
98
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function readSession(path: string): Promise<string> {
|
|
102
|
+
try {
|
|
103
|
+
return await readFile(path, "utf8");
|
|
104
|
+
} catch (error) {
|
|
105
|
+
throw new Error(`cannot read session ${path}: ${String(error)}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Every non-empty line, parsed. A truncated tail line fails the whole copy. */
|
|
110
|
+
function parseEntries(text: string, path: string): readonly SessionEntry[] {
|
|
111
|
+
const lines = text.split("\n").filter((line) => line.trim().length > 0);
|
|
112
|
+
return lines.map((line, index) => {
|
|
113
|
+
let parsed: unknown;
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(line);
|
|
116
|
+
} catch {
|
|
117
|
+
throw new Error(`session ${path} line ${index + 1} is not valid JSON`);
|
|
118
|
+
}
|
|
119
|
+
// Checked, never cast blind: a JSONL line is untrusted input, and a scalar
|
|
120
|
+
// or an array here would read as an entry with no id and no message.
|
|
121
|
+
if (!isRecord(parsed)) {
|
|
122
|
+
throw new Error(`session ${path} line ${index + 1} is not a session entry`);
|
|
123
|
+
}
|
|
124
|
+
return parsed;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* True when an entry holds the parked call as a real `toolCall` content part.
|
|
130
|
+
*
|
|
131
|
+
* Structural, never a substring scan of the serialized entry: the same id can
|
|
132
|
+
* appear inside message text, and this predicate carries the whole safety
|
|
133
|
+
* argument of the module — a false positive appends a dangling result.
|
|
134
|
+
*/
|
|
135
|
+
function carriesToolCall(entries: readonly SessionEntry[], toolCallId: string): boolean {
|
|
136
|
+
return entries.some((entry) => {
|
|
137
|
+
const message = entry.message;
|
|
138
|
+
if (!isRecord(message)) return false;
|
|
139
|
+
const content = message.content;
|
|
140
|
+
if (!Array.isArray(content)) return false;
|
|
141
|
+
return content.some((part: ToolCallPart) => part.type === "toolCall" && part.id === toolCallId);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function syntheticEntry(options: {
|
|
146
|
+
readonly toolCallId: string;
|
|
147
|
+
readonly parentId?: string;
|
|
148
|
+
}): unknown {
|
|
149
|
+
const now = new Date();
|
|
150
|
+
return {
|
|
151
|
+
type: "message",
|
|
152
|
+
id: randomEntryId(),
|
|
153
|
+
...(options.parentId === undefined ? {} : { parentId: options.parentId }),
|
|
154
|
+
timestamp: now.toISOString(),
|
|
155
|
+
message: {
|
|
156
|
+
role: "toolResult",
|
|
157
|
+
toolCallId: options.toolCallId,
|
|
158
|
+
toolName: "request_user_input",
|
|
159
|
+
content: [{ type: "text", text: SYNTHETIC_TOOL_RESULT_TEXT }],
|
|
160
|
+
isError: false,
|
|
161
|
+
timestamp: now.getTime(),
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** pi's entry ids are 8 hex characters. */
|
|
167
|
+
function randomEntryId(): string {
|
|
168
|
+
return Math.random().toString(16).slice(2, 10).padEnd(8, "0");
|
|
169
|
+
}
|
|
@@ -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 type { AgentQuestions } from "../run/index.ts";
|
|
12
|
+
import { prepareSessionCopy } from "./session-copy.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,25 @@
|
|
|
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. `when-missing`, the default, runs only
|
|
13
|
+
* when the Agent supplied no `context` of its own.
|
|
14
|
+
*/
|
|
15
|
+
export function summarizes(policy: QuestionSummaryPolicy, question: Question): boolean {
|
|
16
|
+
if (question.agent === undefined) return false;
|
|
17
|
+
switch (policy) {
|
|
18
|
+
case "never":
|
|
19
|
+
return false;
|
|
20
|
+
case "always":
|
|
21
|
+
return true;
|
|
22
|
+
case "when-missing":
|
|
23
|
+
return (question.context ?? "").trim().length === 0;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
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 { agentQuestionId } from "./question-id.ts";
|
|
9
|
+
import type { Question } from "./questions.ts";
|
|
10
|
+
|
|
11
|
+
/** One parked question, as the Ask that observed the frame reports it. */
|
|
12
|
+
export interface AgentQuestionRequest {
|
|
13
|
+
readonly agent: string;
|
|
14
|
+
readonly toolCallId: string;
|
|
15
|
+
readonly question: string;
|
|
16
|
+
readonly context?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The Agent questions of one Run, and the signal the Run races. */
|
|
20
|
+
export interface AgentQuestions {
|
|
21
|
+
/**
|
|
22
|
+
* Records one parked question, raises the Run's pause, and returns the
|
|
23
|
+
* durable id of the Question. Idempotent per id.
|
|
24
|
+
*/
|
|
25
|
+
raise(request: AgentQuestionRequest): string;
|
|
26
|
+
readonly questions: readonly Question[];
|
|
27
|
+
/**
|
|
28
|
+
* The parked calls, keyed by Question id. The fork summarizer reads the tool
|
|
29
|
+
* call from here rather than parsing it back out of the id (ADR-0022).
|
|
30
|
+
*/
|
|
31
|
+
readonly parked: ReadonlyMap<string, AgentQuestionRequest>;
|
|
32
|
+
/**
|
|
33
|
+
* Writes one Question Summary, before the Checkpoint is published, so the
|
|
34
|
+
* summary is durable in the Cassette (ADR-0022). An unknown id is inert.
|
|
35
|
+
*/
|
|
36
|
+
setSummary(id: string, summary: string): void;
|
|
37
|
+
/** Resolves at the first raised question; the Run races it and drains naturally. */
|
|
38
|
+
readonly raised: Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Builds the Agent question registry of one Run. */
|
|
42
|
+
export function createAgentQuestions(): AgentQuestions {
|
|
43
|
+
const byId = new Map<string, Question>();
|
|
44
|
+
const parked = new Map<string, AgentQuestionRequest>();
|
|
45
|
+
let signal: () => void = () => {};
|
|
46
|
+
const raised = new Promise<void>((resolve) => {
|
|
47
|
+
signal = resolve;
|
|
48
|
+
});
|
|
49
|
+
return {
|
|
50
|
+
raise(request: AgentQuestionRequest): string {
|
|
51
|
+
// The ADR's key: the Agent name and the tool call id of the parked call.
|
|
52
|
+
const id = agentQuestionId(request.agent, request.toolCallId);
|
|
53
|
+
if (byId.has(id)) return id;
|
|
54
|
+
parked.set(id, request);
|
|
55
|
+
byId.set(id, {
|
|
56
|
+
id,
|
|
57
|
+
agent: request.agent,
|
|
58
|
+
question: request.question,
|
|
59
|
+
...(request.context === undefined ? {} : { context: request.context }),
|
|
60
|
+
});
|
|
61
|
+
signal();
|
|
62
|
+
return id;
|
|
63
|
+
},
|
|
64
|
+
get questions(): readonly Question[] {
|
|
65
|
+
return [...byId.values()];
|
|
66
|
+
},
|
|
67
|
+
parked,
|
|
68
|
+
setSummary(id: string, summary: string): void {
|
|
69
|
+
const question = byId.get(id);
|
|
70
|
+
if (question === undefined) return;
|
|
71
|
+
byId.set(id, { ...question, summary });
|
|
72
|
+
},
|
|
73
|
+
raised,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -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
|
+
}
|