@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.
- package/package.json +2 -3
- package/src/agent/agent.ts +75 -23
- package/src/agent/ask-user-capability.ts +36 -0
- package/src/agent/fork.ts +40 -12
- package/src/agent/host-fork.ts +85 -0
- package/src/agent/index.ts +2 -1
- package/src/agent/spawn-definition-request.ts +38 -3
- package/src/agent/spawn-open.ts +59 -100
- package/src/agent/spawn-plan.ts +114 -0
- package/src/agent/spawn-request.ts +34 -3
- package/src/agent/spawn.ts +41 -5
- package/src/ask/ask-exchange-options.ts +8 -6
- package/src/ask/ask-exchange.ts +102 -97
- package/src/ask/ask-guard.ts +207 -0
- package/src/ask/ask-settlement.ts +8 -0
- package/src/ask/ask-timing.ts +12 -0
- package/src/ask/idle-watch.ts +12 -2
- package/src/ask/index.ts +1 -0
- 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 +56 -18
- package/src/cassette/cassette-schema.ts +37 -1
- package/src/cassette/cassette.ts +58 -32
- package/src/cassette/checkpoint.ts +306 -0
- package/src/cassette/index.ts +25 -7
- package/src/cassette/parked-asks.ts +38 -0
- package/src/cassette/replay-divergence.ts +7 -97
- package/src/cassette/resume-identity.ts +5 -1
- package/src/cassette/resume-preconditions.ts +24 -0
- package/src/cassette/resume-transport.ts +112 -13
- package/src/cassette/run-identity.ts +109 -0
- package/src/cassette/session-answer.ts +100 -0
- package/src/cassette/spawn-identity.ts +318 -0
- package/src/catalog/registry-reader.ts +1 -1
- 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/error-codes.ts +3 -2
- package/src/contract/index.ts +1 -0
- package/src/contract/spawn-options.ts +33 -2
- package/src/control/index.ts +2 -0
- package/src/control/pause-drain.ts +81 -24
- package/src/error-factories.ts +8 -0
- package/src/events.ts +10 -2
- package/src/index.ts +15 -1
- package/src/model/index.ts +1 -1
- package/src/pi-session/append-tool-result.ts +165 -0
- package/src/pi-session/index.ts +30 -0
- package/src/pi-session/pi-session-error.ts +34 -0
- package/src/pi-session/session-copy.ts +113 -0
- package/src/pi-session/session-entries.ts +130 -0
- package/src/public-api.ts +1 -0
- package/src/question-summary/index.ts +18 -0
- package/src/question-summary/summarize-question.ts +129 -0
- package/src/question-summary/summary-policy.ts +28 -0
- package/src/run/agent-questions.ts +157 -0
- package/src/run/answers.ts +91 -0
- package/src/run/host-session.ts +233 -0
- package/src/run/index.ts +12 -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 +21 -0
- package/src/run/run-result.ts +21 -0
- package/src/run/run-settlement.ts +36 -4
- package/src/run/run.ts +248 -139
- package/src/system-prompt/agent-system-prompt.ts +1 -1
- package/src/transport/live-transport.ts +19 -0
- package/src/transport/pi-state.ts +31 -5
- package/src/transport/tool-probe.ts +4 -0
- package/src/transport/transport.ts +31 -1
- package/src/types.ts +1 -0
- package/src/cassette/checkpoint-flush.ts +0 -101
- package/src/cassette/run-checkpoint.ts +0 -223
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Host Session file this Run was given: the pre-flight, the hash, and the
|
|
3
|
+
* one copy a Host Fork is spawned from.
|
|
4
|
+
*
|
|
5
|
+
* The pre-flight exists to pre-empt pi's own `SessionManager.forkFrom`, which
|
|
6
|
+
* throws inside the child — a `SPAWN_FAILED` far away from the cause. So a Run
|
|
7
|
+
* refuses a missing, unreadable, empty, header-less or ill-formed Host Session
|
|
8
|
+
* before it starts, and before it emits any Lifecycle Event.
|
|
9
|
+
*
|
|
10
|
+
* The hash is taken over the source bytes as read, before any append, so a
|
|
11
|
+
* replay can hash without copying and two Runs over one unchanged file agree.
|
|
12
|
+
*/
|
|
13
|
+
import { sha256Hex } from "../cassette/index.ts";
|
|
14
|
+
import type { HostSource } from "../contract/index.ts";
|
|
15
|
+
import { hostSessionUnusableError } from "../error-factories.ts";
|
|
16
|
+
import type { YaagError } from "../errors.ts";
|
|
17
|
+
import {
|
|
18
|
+
findToolCall,
|
|
19
|
+
isPiSessionError,
|
|
20
|
+
isRecord,
|
|
21
|
+
parseSession,
|
|
22
|
+
prepareSessionCopy,
|
|
23
|
+
type SessionCopy,
|
|
24
|
+
} from "../pi-session/index.ts";
|
|
25
|
+
|
|
26
|
+
/** The Host Fork orientation text, written into the copy in place of the human's result. */
|
|
27
|
+
export const HOST_FORK_TOOL_RESULT_TEXT =
|
|
28
|
+
"yaag started a Run from this point. This session is a copy of the human's session. " +
|
|
29
|
+
"You are an Agent of that Run. Wait for the next message.";
|
|
30
|
+
|
|
31
|
+
/** What the launcher gives the Run: the Host Session file and the call that started it. */
|
|
32
|
+
export interface HostSessionOptions {
|
|
33
|
+
readonly sessionFile: string;
|
|
34
|
+
/** Required on a live Run, which must close that call in the copy. */
|
|
35
|
+
readonly toolCallId?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The Host Source this Run resolved: the runtime shape behind the branded
|
|
40
|
+
* `HostSource`. The brand key is private to `contract/spawn-options.ts`, so the
|
|
41
|
+
* object is built here and branded with one documented cast; the spawn side
|
|
42
|
+
* reads these two fields to spawn the Host Fork.
|
|
43
|
+
*/
|
|
44
|
+
export interface ResolvedHostSource extends HostSource {
|
|
45
|
+
/**
|
|
46
|
+
* The copy a Host Fork is spawned from. It is present only when a copy was
|
|
47
|
+
* made.
|
|
48
|
+
*
|
|
49
|
+
* Absent means this Run holds no copy: a strict replay, a resume with no
|
|
50
|
+
* tool call id, and a Host Source rebuilt from the Cassette alone. The source
|
|
51
|
+
* path is never put here — a spawn must never fork from it, because it would
|
|
52
|
+
* append to the human's live session. With no path, the spawn side refuses to
|
|
53
|
+
* fork instead (ADR-0068 decision 2).
|
|
54
|
+
*/
|
|
55
|
+
readonly sessionFile?: string;
|
|
56
|
+
/** SHA-256 hex of the source bytes as read. */
|
|
57
|
+
readonly hostHash: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The prepared Host Source, plus the removal of its copy. */
|
|
61
|
+
export interface PreparedHostSource {
|
|
62
|
+
readonly source: ResolvedHostSource;
|
|
63
|
+
/** Removes the copy. Best effort: it never throws. */
|
|
64
|
+
remove(): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* What one pre-flight needs: the option, and the two Run facts that decide how
|
|
69
|
+
* strict it is. `live` means a `toolCallId` is required; `copies` means the copy
|
|
70
|
+
* is made. A strict replay does neither, so it only hashes.
|
|
71
|
+
*/
|
|
72
|
+
export interface PrepareHostSourceRequest {
|
|
73
|
+
readonly host: HostSessionOptions;
|
|
74
|
+
readonly live: boolean;
|
|
75
|
+
readonly copies: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Pre-flights the Host Session, hashes it, and prepares its copy.
|
|
80
|
+
*
|
|
81
|
+
* Throws `HOST_SESSION_UNUSABLE` — and nothing else — when the file is missing,
|
|
82
|
+
* unreadable, empty, header-less, ill-formed, holds no such tool call, or when
|
|
83
|
+
* a live Run was given no `toolCallId`. It never writes to the source file.
|
|
84
|
+
*/
|
|
85
|
+
export async function prepareHostSource(
|
|
86
|
+
request: PrepareHostSourceRequest,
|
|
87
|
+
): Promise<PreparedHostSource> {
|
|
88
|
+
const sessionFile = request.host.sessionFile;
|
|
89
|
+
const bytes = await readBytes(sessionFile);
|
|
90
|
+
// Before the copy, so the hash names the human's file and not yaag's append.
|
|
91
|
+
const hostHash = sha256Hex(bytes);
|
|
92
|
+
const toolName = checkedToolName(sessionFile, bytes, request.host.toolCallId);
|
|
93
|
+
// A live Run must close that call in the copy, and it cannot find the call
|
|
94
|
+
// itself: a session may hold several `yaag_run` calls (ADR-0068).
|
|
95
|
+
if (request.live && request.host.toolCallId === undefined) {
|
|
96
|
+
throw hostSessionUnusableError(
|
|
97
|
+
sessionFile,
|
|
98
|
+
"no tool call id was given, and a live run must close that call in the copy",
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
const copy =
|
|
102
|
+
request.copies && request.host.toolCallId !== undefined
|
|
103
|
+
? await copySession(sessionFile, request.host.toolCallId, toolName)
|
|
104
|
+
: undefined;
|
|
105
|
+
// The brand key is private to the contract, which is type-only and exports no
|
|
106
|
+
// factory (ADR-0045), so the one cast that builds a HostSource lives here.
|
|
107
|
+
const source = {
|
|
108
|
+
kind: "host",
|
|
109
|
+
...(copy === undefined ? {} : { sessionFile: copy.path }),
|
|
110
|
+
hostHash,
|
|
111
|
+
} as ResolvedHostSource;
|
|
112
|
+
return { source, remove: async (): Promise<void> => await copy?.remove() };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The Host Source of a replay or a resume that was given no `--host-session`:
|
|
117
|
+
* the recorded hash, and no copy. A replay never spawns pi, and a resume
|
|
118
|
+
* re-opens each Host Fork from its recorded session file, so neither needs one.
|
|
119
|
+
*/
|
|
120
|
+
export function adoptedHostSource(hostHash: string): ResolvedHostSource {
|
|
121
|
+
// The same single documented cast as above: the brand key is private to the
|
|
122
|
+
// contract, which exports no factory (ADR-0045).
|
|
123
|
+
return { kind: "host", hostHash } as ResolvedHostSource;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function readBytes(sessionFile: string): Promise<ArrayBuffer> {
|
|
127
|
+
try {
|
|
128
|
+
return await Bun.file(sessionFile).arrayBuffer();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
// Node reports a missing file by code; a directory or a permission failure
|
|
131
|
+
// arrives here too, and says so with its own message.
|
|
132
|
+
if (isRecord(error) && error.code === "ENOENT") {
|
|
133
|
+
throw hostSessionUnusableError(sessionFile, "the file does not exist");
|
|
134
|
+
}
|
|
135
|
+
throw hostSessionUnusableError(
|
|
136
|
+
sessionFile,
|
|
137
|
+
`the file cannot be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The tool name of the named call, which the copy records the result under.
|
|
144
|
+
* Checks the file-level rules the copy module does not own on the way, and
|
|
145
|
+
* throws the refusal of the first one that fails.
|
|
146
|
+
*/
|
|
147
|
+
function checkedToolName(
|
|
148
|
+
sessionFile: string,
|
|
149
|
+
bytes: ArrayBuffer,
|
|
150
|
+
toolCallId: string | undefined,
|
|
151
|
+
): string | undefined {
|
|
152
|
+
const text = new TextDecoder().decode(bytes);
|
|
153
|
+
if (text.trim().length === 0) throw hostSessionUnusableError(sessionFile, "the file is empty");
|
|
154
|
+
// The pre-flight must not be stricter than the copy it guards: it reuses the
|
|
155
|
+
// writer's parse policy, which tolerates one half-written last line.
|
|
156
|
+
assertHeader(sessionFile, text);
|
|
157
|
+
const entries = parse(sessionFile, text);
|
|
158
|
+
if (toolCallId === undefined) return undefined;
|
|
159
|
+
const holder = findToolCall(entries.entries, toolCallId);
|
|
160
|
+
if (holder === undefined) {
|
|
161
|
+
throw hostSessionUnusableError(sessionFile, `no entry holds the tool call ${toolCallId}`);
|
|
162
|
+
}
|
|
163
|
+
return holder.toolName;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function parse(sessionFile: string, text: string): ReturnType<typeof parseSession> {
|
|
167
|
+
try {
|
|
168
|
+
return parseSession(text, sessionFile);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
throw refusalOf(sessionFile, error);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function assertHeader(sessionFile: string, text: string): void {
|
|
175
|
+
const first = text.split("\n").find((line) => line.trim().length > 0) ?? "";
|
|
176
|
+
let parsed: unknown;
|
|
177
|
+
try {
|
|
178
|
+
parsed = JSON.parse(first);
|
|
179
|
+
} catch {
|
|
180
|
+
throw hostSessionUnusableError(sessionFile, "the first line is no session header");
|
|
181
|
+
}
|
|
182
|
+
if (!isRecord(parsed) || parsed.type !== "session") {
|
|
183
|
+
throw hostSessionUnusableError(sessionFile, "the first line is no session header");
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function copySession(
|
|
188
|
+
sessionFile: string,
|
|
189
|
+
toolCallId: string,
|
|
190
|
+
toolName: string | undefined,
|
|
191
|
+
): Promise<SessionCopy> {
|
|
192
|
+
try {
|
|
193
|
+
return await prepareSessionCopy({
|
|
194
|
+
sessionFile,
|
|
195
|
+
toolCallId,
|
|
196
|
+
text: HOST_FORK_TOOL_RESULT_TEXT,
|
|
197
|
+
...(toolName === undefined ? {} : { toolName }),
|
|
198
|
+
// The `background: true` race: the human's client may answer the call
|
|
199
|
+
// while yaag copies, so an answered call is used as it is and never a
|
|
200
|
+
// refusal on this path.
|
|
201
|
+
toleratesAnsweredCall: true,
|
|
202
|
+
});
|
|
203
|
+
} catch (error) {
|
|
204
|
+
throw refusalOf(sessionFile, error);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Every refusal of the copy module, said in this module's one message shape. */
|
|
209
|
+
function refusalOf(sessionFile: string, error: unknown): YaagError {
|
|
210
|
+
if (!isPiSessionError(error)) {
|
|
211
|
+
return hostSessionUnusableError(
|
|
212
|
+
sessionFile,
|
|
213
|
+
error instanceof Error ? error.message : String(error),
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
switch (error.reason) {
|
|
217
|
+
case "unreadable":
|
|
218
|
+
return hostSessionUnusableError(sessionFile, "the file cannot be read");
|
|
219
|
+
case "bad-line":
|
|
220
|
+
return hostSessionUnusableError(sessionFile, badLineReason(error.message));
|
|
221
|
+
case "no-such-call":
|
|
222
|
+
return hostSessionUnusableError(sessionFile, "no entry holds the tool call");
|
|
223
|
+
case "different-result":
|
|
224
|
+
// Unreachable: this module always tolerates an answered call.
|
|
225
|
+
return hostSessionUnusableError(sessionFile, "the tool call is already answered");
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The writer says which line failed; the refusal keeps that number. */
|
|
230
|
+
function badLineReason(message: string): string {
|
|
231
|
+
const line = /line (\d+)/.exec(message)?.[1];
|
|
232
|
+
return line === undefined ? "a line is no session entry" : `line ${line} is no session entry`;
|
|
233
|
+
}
|
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,15 @@ export {
|
|
|
9
11
|
type ProgramDefinition,
|
|
10
12
|
programDefinition,
|
|
11
13
|
} from "./define-run.ts";
|
|
14
|
+
export {
|
|
15
|
+
adoptedHostSource,
|
|
16
|
+
HOST_FORK_TOOL_RESULT_TEXT,
|
|
17
|
+
type HostSessionOptions,
|
|
18
|
+
prepareHostSource,
|
|
19
|
+
type ResolvedHostSource,
|
|
20
|
+
} from "./host-session.ts";
|
|
21
|
+
export { isPauseSignal, RunPauseSignal } from "./pause-signal.ts";
|
|
22
|
+
export type { AskUserOptions, Question } from "./questions.ts";
|
|
12
23
|
export { executeRun, type RunOptions } from "./run.ts";
|
|
13
24
|
export type { RunContext } from "./run-context.ts";
|
|
25
|
+
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
|
+
}
|
package/src/run/run-context.ts
CHANGED
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
import type { AgentDefinition } from "../agent/define-agent.ts";
|
|
4
4
|
import type {
|
|
5
5
|
Handle,
|
|
6
|
+
HostSource,
|
|
6
7
|
SpawnableDefinition,
|
|
7
8
|
SpawnOptions,
|
|
8
9
|
SpawnOverrides,
|
|
9
10
|
} from "../contract/index.ts";
|
|
10
11
|
import type { ProfiledDefinition } from "../profile/use-profile.ts";
|
|
12
|
+
import type { AskUserOptions } from "./questions.ts";
|
|
11
13
|
|
|
12
14
|
/** What an Orchestration Program is handed. */
|
|
13
15
|
export interface RunContext<Args = unknown> {
|
|
@@ -27,9 +29,28 @@ export interface RunContext<Args = unknown> {
|
|
|
27
29
|
spawn(profiled: ProfiledDefinition, overrides?: SpawnOverrides): Promise<Handle>;
|
|
28
30
|
/** Last on purpose: a union-typed value, e.g. what a Catalog Resolve gave back (ADR-0053). */
|
|
29
31
|
spawn(definition: SpawnableDefinition, overrides?: SpawnOverrides): Promise<Handle>;
|
|
32
|
+
/**
|
|
33
|
+
* Asks the user one question and pauses the Run (ADR-0022).
|
|
34
|
+
*
|
|
35
|
+
* The call never resolves in this Run: it records the question, then unwinds
|
|
36
|
+
* the program with the pause control signal. The Run drains, publishes a
|
|
37
|
+
* Checkpoint, and ends with the `paused` outcome. A resume answers the
|
|
38
|
+
* question (ticket 05). Two questions must not claim one id: give each one a
|
|
39
|
+
* `key`, or `PAUSE_REFUSED` is thrown.
|
|
40
|
+
*/
|
|
41
|
+
askUser(question: string, options?: AskUserOptions): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Pauses the Run without a question (ADR-0022).
|
|
44
|
+
*
|
|
45
|
+
* The call never resolves in this Run, the same way `askUser` does not. The
|
|
46
|
+
* first `reason` is the reason the Run reports.
|
|
47
|
+
*/
|
|
48
|
+
pause(reason?: string): Promise<void>;
|
|
30
49
|
/**
|
|
31
50
|
* The Profile this Run activated (ADR-0052). Defined when the program
|
|
32
51
|
* declares Profiles, undefined otherwise.
|
|
33
52
|
*/
|
|
34
53
|
readonly profile?: { readonly id: string };
|
|
54
|
+
/** The Host Session's conversation as a fork source. Absent when the Run has none. */
|
|
55
|
+
readonly host?: HostSource;
|
|
35
56
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one Run gives back (ADR-0022). A completed Run carries the program's
|
|
3
|
+
* value; a paused Run carries what it needs to be resumed. A failed Run and a
|
|
4
|
+
* stopped Run keep rejecting with a `YaagError`, so no caller has to read an
|
|
5
|
+
* outcome to know that something went wrong.
|
|
6
|
+
*/
|
|
7
|
+
import type { Question } from "./questions.ts";
|
|
8
|
+
|
|
9
|
+
export type RunResult<Result> =
|
|
10
|
+
| { readonly outcome: "completed"; readonly value: Result }
|
|
11
|
+
| {
|
|
12
|
+
readonly outcome: "paused";
|
|
13
|
+
/** Every question the program asked its user. */
|
|
14
|
+
readonly questions: readonly Question[];
|
|
15
|
+
/** The reason the first `ctx.pause` gave, when it gave one. */
|
|
16
|
+
readonly reason?: string;
|
|
17
|
+
/** Path of the published Checkpoint the Run resumes from (ADR-0021). */
|
|
18
|
+
readonly checkpoint: string;
|
|
19
|
+
/** Ask rejections observed during the drain; they never change the outcome. */
|
|
20
|
+
readonly warnings?: readonly string[];
|
|
21
|
+
};
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import type { ControlRequests, DrainableAgent } from "../control/index.ts";
|
|
2
2
|
import { drainForPause } from "../control/index.ts";
|
|
3
|
+
import { isPauseSignal } from "./pause-signal.ts";
|
|
3
4
|
|
|
4
5
|
/** How one Run settled, before it reaps its Agents and publishes its Checkpoint. */
|
|
5
6
|
export type RunSettlement<Result> =
|
|
6
7
|
| { readonly outcome: "completed"; readonly value: Result }
|
|
7
8
|
| { readonly outcome: "failed"; readonly error: unknown }
|
|
8
|
-
| {
|
|
9
|
+
| {
|
|
10
|
+
readonly outcome: "paused";
|
|
11
|
+
readonly cutShort: readonly string[];
|
|
12
|
+
/** Ask rejections observed during the drain; they never change the outcome. */
|
|
13
|
+
readonly warnings: readonly string[];
|
|
14
|
+
}
|
|
9
15
|
| { readonly outcome: "stopped" };
|
|
10
16
|
|
|
11
17
|
export interface RunSettlementOptions<Result> {
|
|
@@ -17,6 +23,8 @@ export interface RunSettlementOptions<Result> {
|
|
|
17
23
|
readonly agents: readonly DrainableAgent[];
|
|
18
24
|
/** Closes Ask and spawn admission; the drain calls it before its first steer. */
|
|
19
25
|
readonly closeAdmission: () => void;
|
|
26
|
+
/** Resolves at the first question an Agent asked its human (ADR-0023). */
|
|
27
|
+
readonly questionRaised: Promise<void>;
|
|
20
28
|
}
|
|
21
29
|
|
|
22
30
|
/**
|
|
@@ -29,6 +37,10 @@ export interface RunSettlementOptions<Result> {
|
|
|
29
37
|
* absorbed: the rejection is a consequence of the closed admission or the
|
|
30
38
|
* cut-short Ask, so the Run stays `paused`. The rule reads a settlement latch
|
|
31
39
|
* rather than error codes, so no failure vocabulary decides an outcome.
|
|
40
|
+
*
|
|
41
|
+
* A question an Agent asked its human is a third entrant: the program never
|
|
42
|
+
* sees it, because the program awaits an `ask()` the parked turn never settles,
|
|
43
|
+
* so the pause can only arrive as its own signal (ADR-0023).
|
|
32
44
|
*/
|
|
33
45
|
export async function settleRun<Result>(
|
|
34
46
|
options: RunSettlementOptions<Result>,
|
|
@@ -55,8 +67,28 @@ export async function settleRun<Result>(
|
|
|
55
67
|
() => "program" as const,
|
|
56
68
|
),
|
|
57
69
|
options.requests.first.then(() => "control" as const),
|
|
70
|
+
options.questionRaised.then(() => "question" as const),
|
|
58
71
|
]);
|
|
59
|
-
|
|
72
|
+
// One drain policy for both natural pauses: nothing is cut short, and the
|
|
73
|
+
// settlement latch is never read, because the program is still running.
|
|
74
|
+
const naturalDrain = async (): Promise<RunSettlement<Result>> => {
|
|
75
|
+
const drained = await drainForPause({
|
|
76
|
+
agents: options.agents,
|
|
77
|
+
grace: { kind: "natural" },
|
|
78
|
+
closeAdmission: options.closeAdmission,
|
|
79
|
+
stopped: options.requests.stopped,
|
|
80
|
+
});
|
|
81
|
+
if (drained.kind === "stopped") return { outcome: "stopped" };
|
|
82
|
+
return { outcome: "paused", cutShort: drained.cutShort, warnings: drained.warnings };
|
|
83
|
+
};
|
|
84
|
+
if (first === "question") return naturalDrain();
|
|
85
|
+
if (first === "program") {
|
|
86
|
+
const settled = settledLatch(latch.settled);
|
|
87
|
+
// The program asked its user a question (ADR-0022). It is a pause, not a
|
|
88
|
+
// failure, so the Run drains naturally: no wrap-up steer, and no deadline.
|
|
89
|
+
if (settled.outcome === "failed" && isPauseSignal(settled.error)) return naturalDrain();
|
|
90
|
+
return settled;
|
|
91
|
+
}
|
|
60
92
|
const control = await options.requests.first;
|
|
61
93
|
if (control.kind === "stop") {
|
|
62
94
|
options.closeAdmission();
|
|
@@ -64,14 +96,14 @@ export async function settleRun<Result>(
|
|
|
64
96
|
}
|
|
65
97
|
const drained = await drainForPause({
|
|
66
98
|
agents: options.agents,
|
|
67
|
-
deadlineMs: control.deadlineMs,
|
|
99
|
+
grace: { kind: "bounded", deadlineMs: control.deadlineMs },
|
|
68
100
|
closeAdmission: options.closeAdmission,
|
|
69
101
|
stopped: options.requests.stopped,
|
|
70
102
|
});
|
|
71
103
|
const settled = latch.settled;
|
|
72
104
|
if (settled !== null && settled.outcome === "completed") return settled;
|
|
73
105
|
if (drained.kind === "stopped") return { outcome: "stopped" };
|
|
74
|
-
return { outcome: "paused", cutShort: drained.cutShort };
|
|
106
|
+
return { outcome: "paused", cutShort: drained.cutShort, warnings: drained.warnings };
|
|
75
107
|
}
|
|
76
108
|
|
|
77
109
|
/**
|