@yaag/runtime 0.22.0 → 0.24.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 +1 -1
- package/src/agent/agent.ts +52 -2
- package/src/agent/fork.ts +7 -0
- package/src/agent/spawn-open.ts +25 -5
- package/src/agent/spawn-request.ts +123 -3
- package/src/agent/spawn.ts +6 -0
- package/src/ask/ask-hash.ts +7 -0
- package/src/ask-contract/ask-limit.ts +2 -4
- package/src/ask-contract/index.ts +2 -1
- package/src/ask-contract/wrap-up-steer.ts +17 -0
- package/src/cassette/index.ts +1 -0
- package/src/cassette/run-checkpoint.ts +17 -5
- package/src/contract/agent-policy.ts +15 -4
- package/src/contract/error-codes.ts +3 -2
- package/src/contract/index.ts +10 -0
- package/src/contract/spawn-options.ts +7 -1
- package/src/contract/system-prompt.ts +88 -0
- package/src/control/ask-admission.ts +24 -0
- package/src/control/control-commands.ts +300 -0
- package/src/control/index.ts +31 -0
- package/src/control/pause-drain.ts +105 -0
- package/src/control/run-controller.ts +88 -0
- package/src/events.ts +40 -0
- package/src/index.ts +30 -0
- package/src/public-api.ts +11 -0
- package/src/run/run-settlement.ts +93 -0
- package/src/run/run.ts +86 -32
- package/src/summary/summary.ts +6 -0
- package/src/system-prompt/agent-prompt-extension.ts +337 -0
- package/src/system-prompt/agent-prompt.ts +15 -0
- package/src/system-prompt/agent-system-prompt.ts +90 -0
- package/src/system-prompt/append-channel.ts +69 -0
- package/src/system-prompt/define-system-prompt.ts +112 -0
- package/src/system-prompt/index.ts +48 -0
- package/src/system-prompt/prompt-guards.ts +60 -0
- package/src/system-prompt/render-sentinel.ts +75 -0
- package/src/transport/append-env.ts +69 -0
- package/src/transport/index.ts +2 -0
- package/src/transport/live-transport.ts +50 -26
- package/src/transport/pi-state.ts +38 -4
- package/src/transport/transport.ts +4 -1
- package/src/types.ts +8 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The author surface of a Prompt Definition (ADR-0057, ADR-0058, ADR-0064).
|
|
3
|
+
*
|
|
4
|
+
* Types only, and no import outside this directory (ADR-0045). The values that
|
|
5
|
+
* build a Prompt Definition live in `system-prompt/define-system-prompt.ts`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Brand of a rendered prompt text; no program can build the symbol. */
|
|
9
|
+
declare const renderedPromptText: unique symbol;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What `yaagSystemPrompt` and every `ctx.render*()` call return: a string that
|
|
13
|
+
* holds Render Sentinels. It is a `string` everywhere, except where a literal
|
|
14
|
+
* prompt is expected — that is the compile-time half of ADR-0060.
|
|
15
|
+
*/
|
|
16
|
+
export type PromptText = string & { readonly [renderedPromptText]: "yaag" };
|
|
17
|
+
|
|
18
|
+
/** A `systemPrompt` string a program wrote itself, so not a `PromptText`. */
|
|
19
|
+
export type LiteralPromptText = string & { readonly [renderedPromptText]?: undefined };
|
|
20
|
+
|
|
21
|
+
/** Who reads what an Agent writes. `"user"` is not reachable from a program yet. */
|
|
22
|
+
export type PromptAudience = "program" | "user";
|
|
23
|
+
|
|
24
|
+
/** What a Prompt Definition learns about the Agent it writes the prompt for. */
|
|
25
|
+
export interface SystemPromptAgent {
|
|
26
|
+
/** The Agent name, as the Run allocated it. */
|
|
27
|
+
readonly name: string;
|
|
28
|
+
/** The Run name, the same value `run_start.program` carries. */
|
|
29
|
+
readonly runName: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The Prompt Context: one method per Prompt Variable.
|
|
34
|
+
*
|
|
35
|
+
* Every method is **write-only**. It returns a Render Sentinel, an opaque
|
|
36
|
+
* marker, and not the text behind it: the facts exist only inside the Agent
|
|
37
|
+
* process, and the private prompt extension puts them in there. Put the result
|
|
38
|
+
* in the prompt; do not read it, match it, or split on it.
|
|
39
|
+
*/
|
|
40
|
+
export interface SystemPromptContext {
|
|
41
|
+
/** Writes the model the Agent runs on, as `provider/id`. */
|
|
42
|
+
renderModel(): PromptText;
|
|
43
|
+
/** Writes the Agent process id. */
|
|
44
|
+
renderPid(): PromptText;
|
|
45
|
+
/** Writes the time the Agent started, in ISO 8601. */
|
|
46
|
+
renderStartedAt(): PromptText;
|
|
47
|
+
/** Writes the time of the current turn, in ISO 8601. */
|
|
48
|
+
renderCurrentDateTime(): PromptText;
|
|
49
|
+
/** Writes the Agent working directory. */
|
|
50
|
+
renderCwd(): PromptText;
|
|
51
|
+
/** Writes the tool list of the Agent, one line per tool. */
|
|
52
|
+
renderTools(): PromptText;
|
|
53
|
+
/** Writes the user's `APPEND_SYSTEM.md`. */
|
|
54
|
+
renderAppendSystem(): PromptText;
|
|
55
|
+
/** Writes the text the program set with `appendSystemPrompt`. */
|
|
56
|
+
renderProgramAppend(): PromptText;
|
|
57
|
+
/** Writes the context files pi loaded, in pi's own block format. */
|
|
58
|
+
renderContextFiles(): PromptText;
|
|
59
|
+
/** Writes the skills pi loaded, in pi's own block format. */
|
|
60
|
+
renderSkills(): PromptText;
|
|
61
|
+
/** Writes the default system prompt pi would have built alone. */
|
|
62
|
+
renderPiDefaultPrompt(): PromptText;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The one object a Prompt Definition builder receives. */
|
|
66
|
+
export interface SystemPromptInput {
|
|
67
|
+
/** The write-only Prompt Context. */
|
|
68
|
+
readonly ctx: SystemPromptContext;
|
|
69
|
+
/** The Agent this prompt is for. */
|
|
70
|
+
readonly agent: SystemPromptAgent;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Builds one Agent's system prompt. It must be pure and synchronous, and it
|
|
75
|
+
* runs in the Orchestrator exactly once per spawn.
|
|
76
|
+
*/
|
|
77
|
+
export type SystemPromptBuilder = (input: SystemPromptInput) => string;
|
|
78
|
+
|
|
79
|
+
/** Brand of a Prompt Definition; no program can build the symbol. */
|
|
80
|
+
declare const systemPromptDefinition: unique symbol;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The opaque, frozen result of `defineSystemPrompt`. It is a value a spawn
|
|
84
|
+
* carries, not a string: yaag renders it at the spawn-request seam.
|
|
85
|
+
*/
|
|
86
|
+
export interface SystemPromptDefinition {
|
|
87
|
+
readonly [systemPromptDefinition]: true;
|
|
88
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run-scoped gate over new Asks, closed before a pause drain sends its first
|
|
3
|
+
* wrap-up steer (ADR-0024). Spawn admission has its own gate in `agent/spawn.ts`;
|
|
4
|
+
* both close together when the Run begins settling.
|
|
5
|
+
*/
|
|
6
|
+
export interface AskAdmission {
|
|
7
|
+
/** True once the Run began settling; a new Ask is refused with RUN_CLOSED. */
|
|
8
|
+
readonly closed: boolean;
|
|
9
|
+
/** Refuses every later Ask. Idempotent. */
|
|
10
|
+
close(): void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Creates one Run's Ask admission gate, open until the Run begins settling. */
|
|
14
|
+
export function createAskAdmission(): AskAdmission {
|
|
15
|
+
let closed = false;
|
|
16
|
+
return {
|
|
17
|
+
get closed(): boolean {
|
|
18
|
+
return closed;
|
|
19
|
+
},
|
|
20
|
+
close(): void {
|
|
21
|
+
closed = true;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The control command state machine (ADR-0024, ADR-0054): one reader that both
|
|
3
|
+
* stdin and the Control Channel socket feed. It is pure — no I/O, no clock, no
|
|
4
|
+
* `node:` module. It takes text in and returns response bodies plus at most one
|
|
5
|
+
* typed command per accepted request; the caller does every side effect.
|
|
6
|
+
*/
|
|
7
|
+
import type { ControlErrorCode, ControlResponseStatus, LifecycleEventBody } from "../events.ts";
|
|
8
|
+
|
|
9
|
+
export type { ControlErrorCode, ControlResponseStatus } from "../events.ts";
|
|
10
|
+
|
|
11
|
+
/** ADR-0024 frame cap: a longer line is refused, never buffered. */
|
|
12
|
+
export const CONTROL_FRAME_MAX_BYTES = 64 * 1024;
|
|
13
|
+
/** Longest accepted request id. A longer id is `INVALID_FIELD`. */
|
|
14
|
+
export const CONTROL_ID_MAX_CHARS = 128;
|
|
15
|
+
/** Pause deadline used when the frame names none. */
|
|
16
|
+
export const PAUSE_DEADLINE_DEFAULT_MS = 60_000;
|
|
17
|
+
/** Smallest accepted pause deadline. */
|
|
18
|
+
export const PAUSE_DEADLINE_MIN_MS = 1_000;
|
|
19
|
+
/** Largest accepted pause deadline. */
|
|
20
|
+
export const PAUSE_DEADLINE_MAX_MS = 600_000;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Bound on the answered-id table. An unbounded map is a memory hole a hostile
|
|
24
|
+
* client can grow one frame at a time. Eviction is safe: after the first
|
|
25
|
+
* accepted terminal every fresh id gets `RUN_SETTLING`/`RUN_ENDED` anyway.
|
|
26
|
+
*/
|
|
27
|
+
const CONTROL_ID_TABLE_MAX = 256;
|
|
28
|
+
|
|
29
|
+
/** The `control_response` Lifecycle Event body (ADR-0024 wire contract). */
|
|
30
|
+
export type ControlResponse = Extract<LifecycleEventBody, { type: "control_response" }>;
|
|
31
|
+
|
|
32
|
+
/** What an accepted request means for the Run. */
|
|
33
|
+
export type ControlCommand =
|
|
34
|
+
| { readonly kind: "pause"; readonly deadlineMs: number }
|
|
35
|
+
| { readonly kind: "stop" };
|
|
36
|
+
|
|
37
|
+
/** One line in, one response out, plus at most one command for the caller. */
|
|
38
|
+
export interface ControlDecision {
|
|
39
|
+
readonly response: ControlResponse;
|
|
40
|
+
readonly command: ControlCommand | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type Phase =
|
|
44
|
+
| { readonly name: "open" }
|
|
45
|
+
| { readonly name: "pausing" }
|
|
46
|
+
| { readonly name: "stopping" }
|
|
47
|
+
| { readonly name: "settling" }
|
|
48
|
+
| { readonly name: "ended" };
|
|
49
|
+
|
|
50
|
+
type Request =
|
|
51
|
+
| { readonly id: string; readonly cmd: "pause"; readonly deadlineMs: number }
|
|
52
|
+
| { readonly id: string; readonly cmd: "stop" };
|
|
53
|
+
|
|
54
|
+
type ParsedFrame =
|
|
55
|
+
| { readonly ok: true; readonly request: Request }
|
|
56
|
+
| { readonly ok: false; readonly response: ControlResponse };
|
|
57
|
+
|
|
58
|
+
const KNOWN_KEYS = new Set(["v", "id", "cmd", "deadlineMs"]);
|
|
59
|
+
const encoder = new TextEncoder();
|
|
60
|
+
|
|
61
|
+
function error(id: string | null, code: ControlErrorCode, message: string): ControlResponse {
|
|
62
|
+
return { type: "control_response", id, status: "error", code, message };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function ok(id: string, status: ControlResponseStatus): ControlResponse {
|
|
66
|
+
return { type: "control_response", id, status };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isInteger(value: unknown): value is number {
|
|
70
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Parses and validates one line, in the ADR-0024 order, without any state. */
|
|
74
|
+
function parseControlFrame(line: string): ParsedFrame {
|
|
75
|
+
let value: unknown;
|
|
76
|
+
try {
|
|
77
|
+
value = JSON.parse(line);
|
|
78
|
+
} catch {
|
|
79
|
+
return { ok: false, response: error(null, "MALFORMED", "the frame is not JSON") };
|
|
80
|
+
}
|
|
81
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
82
|
+
return { ok: false, response: error(null, "MALFORMED", "the frame is not a JSON object") };
|
|
83
|
+
}
|
|
84
|
+
const frame = value as Record<string, unknown>;
|
|
85
|
+
const id = frame.id;
|
|
86
|
+
// The id is read first, so a version error can still name the request it
|
|
87
|
+
// answers; `id: null` stays reserved for a frame with no usable id (ADR-0024).
|
|
88
|
+
const usableId =
|
|
89
|
+
typeof id === "string" && id !== "" && id.length <= CONTROL_ID_MAX_CHARS ? id : null;
|
|
90
|
+
if (!("v" in frame)) {
|
|
91
|
+
return { ok: false, response: error(usableId, "MALFORMED", "the field `v` is missing") };
|
|
92
|
+
}
|
|
93
|
+
if (!isInteger(frame.v)) {
|
|
94
|
+
return { ok: false, response: error(usableId, "MALFORMED", "the field `v` is not an integer") };
|
|
95
|
+
}
|
|
96
|
+
if (frame.v !== 1) {
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
response: error(usableId, "UNSUPPORTED_VERSION", `unsupported version ${frame.v}`),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (usableId === null) {
|
|
103
|
+
return { ok: false, response: error(null, "INVALID_FIELD", "the field `id` is invalid") };
|
|
104
|
+
}
|
|
105
|
+
if (!("cmd" in frame) || typeof frame.cmd !== "string") {
|
|
106
|
+
return { ok: false, response: error(usableId, "INVALID_FIELD", "the field `cmd` is invalid") };
|
|
107
|
+
}
|
|
108
|
+
const cmd = frame.cmd;
|
|
109
|
+
if (cmd !== "pause" && cmd !== "stop") {
|
|
110
|
+
return { ok: false, response: error(usableId, "UNKNOWN_CMD", `unknown command \`${cmd}\``) };
|
|
111
|
+
}
|
|
112
|
+
for (const key of Object.keys(frame)) {
|
|
113
|
+
if (!KNOWN_KEYS.has(key)) {
|
|
114
|
+
return { ok: false, response: error(usableId, "INVALID_FIELD", `unknown field \`${key}\``) };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (cmd === "stop") {
|
|
118
|
+
if ("deadlineMs" in frame) {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
response: error(usableId, "INVALID_FIELD", "the field `deadlineMs` is not valid on a stop"),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return { ok: true, request: { id: usableId, cmd } };
|
|
125
|
+
}
|
|
126
|
+
if (!("deadlineMs" in frame)) {
|
|
127
|
+
return { ok: true, request: { id: usableId, cmd, deadlineMs: PAUSE_DEADLINE_DEFAULT_MS } };
|
|
128
|
+
}
|
|
129
|
+
const deadlineMs = frame.deadlineMs;
|
|
130
|
+
if (
|
|
131
|
+
!isInteger(deadlineMs) ||
|
|
132
|
+
deadlineMs < PAUSE_DEADLINE_MIN_MS ||
|
|
133
|
+
deadlineMs > PAUSE_DEADLINE_MAX_MS
|
|
134
|
+
) {
|
|
135
|
+
return {
|
|
136
|
+
ok: false,
|
|
137
|
+
response: error(usableId, "INVALID_FIELD", "the field `deadlineMs` is invalid"),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
return { ok: true, request: { id: usableId, cmd, deadlineMs } };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function byteLength(text: string): number {
|
|
144
|
+
return encoder.encode(text).length;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function overlong(): ControlDecision {
|
|
148
|
+
return {
|
|
149
|
+
response: error(null, "FRAME_TOO_LONG", "the frame is longer than the 64 KiB cap"),
|
|
150
|
+
command: null,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function signatureOf(request: Request): string {
|
|
155
|
+
return request.cmd === "pause" ? `pause|${request.deadlineMs}` : "stop";
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Reads `\n`-terminated control frames and arbitrates them: the first terminal
|
|
160
|
+
* request wins, a stop overrides a pause drain, and an identical id coalesces.
|
|
161
|
+
* It never does I/O and never reads a clock; the caller applies the commands.
|
|
162
|
+
*/
|
|
163
|
+
export class ControlCommandReader {
|
|
164
|
+
#buffer = "";
|
|
165
|
+
#skipping = false;
|
|
166
|
+
#phase: Phase = { name: "open" };
|
|
167
|
+
readonly #answered = new Map<string, { signature: string; response: ControlResponse }>();
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The `BUSY` frame the Control Channel writes to a second client while one
|
|
171
|
+
* client holds the channel (spec decision 18). Static: no Run state is read.
|
|
172
|
+
*/
|
|
173
|
+
static busy(message = "another client holds the Control Channel"): ControlResponse {
|
|
174
|
+
return { type: "control_response", id: null, status: "error", code: "BUSY", message };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Feeds one chunk of text and returns one decision per complete frame. A
|
|
179
|
+
* blank line is not a frame. An unterminated tail stays buffered; ADR-0024
|
|
180
|
+
* discards it at EOF.
|
|
181
|
+
*/
|
|
182
|
+
read(chunk: string): readonly ControlDecision[] {
|
|
183
|
+
const decisions: ControlDecision[] = [];
|
|
184
|
+
this.#buffer += chunk;
|
|
185
|
+
let newline = this.#buffer.indexOf("\n");
|
|
186
|
+
while (newline !== -1) {
|
|
187
|
+
const line = this.#buffer.slice(0, newline);
|
|
188
|
+
this.#buffer = this.#buffer.slice(newline + 1);
|
|
189
|
+
if (this.#skipping) this.#skipping = false;
|
|
190
|
+
else if (byteLength(line) > CONTROL_FRAME_MAX_BYTES) {
|
|
191
|
+
// The cap precedes the parse, so an overlong frame is never decoded.
|
|
192
|
+
decisions.push(overlong());
|
|
193
|
+
} else {
|
|
194
|
+
const decision = this.#line(line);
|
|
195
|
+
if (decision !== null) decisions.push(decision);
|
|
196
|
+
}
|
|
197
|
+
newline = this.#buffer.indexOf("\n");
|
|
198
|
+
}
|
|
199
|
+
if (!this.#skipping && byteLength(this.#buffer) > CONTROL_FRAME_MAX_BYTES) {
|
|
200
|
+
this.#buffer = "";
|
|
201
|
+
this.#skipping = true;
|
|
202
|
+
decisions.push(overlong());
|
|
203
|
+
}
|
|
204
|
+
if (this.#skipping) this.#buffer = "";
|
|
205
|
+
return decisions;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The caller reports that settlement began: later requests get `RUN_SETTLING`.
|
|
210
|
+
* The phase setters are not guarded against a backwards move; the Run calls
|
|
211
|
+
* them one time each, in order.
|
|
212
|
+
*/
|
|
213
|
+
settling(): void {
|
|
214
|
+
this.#phase = { name: "settling" };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The caller reports that `run_end` was emitted: later new requests get `RUN_ENDED`. */
|
|
218
|
+
ended(): void {
|
|
219
|
+
this.#phase = { name: "ended" };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
#line(raw: string): ControlDecision | null {
|
|
223
|
+
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
|
|
224
|
+
if (line.trim() === "") return null;
|
|
225
|
+
const parsed = parseControlFrame(line);
|
|
226
|
+
if (!parsed.ok) {
|
|
227
|
+
const id = parsed.response.id;
|
|
228
|
+
if (id === null) return { response: parsed.response, command: null };
|
|
229
|
+
// The signature is the payload, not the code: two different payloads that
|
|
230
|
+
// share an id are a `DUPLICATE_ID`, whatever they failed on (ADR-0024).
|
|
231
|
+
return this.#answer(id, `raw|${line}`, { response: parsed.response, command: null });
|
|
232
|
+
}
|
|
233
|
+
return this.#arbitrate(parsed.request);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Coalesces on an identical payload, refuses a different one, else records the answer. */
|
|
237
|
+
#answer(id: string, signature: string, fresh: ControlDecision): ControlDecision {
|
|
238
|
+
const coalesced = this.#coalesce(id, signature);
|
|
239
|
+
if (coalesced !== null) return coalesced;
|
|
240
|
+
this.#remember(id, signature, fresh.response);
|
|
241
|
+
return fresh;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
#coalesce(id: string, signature: string): ControlDecision | null {
|
|
245
|
+
const previous = this.#answered.get(id);
|
|
246
|
+
if (previous === undefined) return null;
|
|
247
|
+
if (previous.signature === signature) return { response: previous.response, command: null };
|
|
248
|
+
return {
|
|
249
|
+
response: error(id, "DUPLICATE_ID", `the id \`${id}\` already carries a different request`),
|
|
250
|
+
command: null,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
#remember(id: string, signature: string, response: ControlResponse): void {
|
|
255
|
+
if (this.#answered.size >= CONTROL_ID_TABLE_MAX) {
|
|
256
|
+
const oldest = this.#answered.keys().next();
|
|
257
|
+
if (!oldest.done) this.#answered.delete(oldest.value);
|
|
258
|
+
}
|
|
259
|
+
this.#answered.set(id, { signature, response });
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
#arbitrate(request: Request): ControlDecision {
|
|
263
|
+
// There is no terminal-response cache: a request that arrives after
|
|
264
|
+
// settlement gets `RUN_SETTLING`/`RUN_ENDED`, even when it repeats an
|
|
265
|
+
// answered id (ADR-0024).
|
|
266
|
+
const phase = this.#phase.name;
|
|
267
|
+
if (phase === "ended") {
|
|
268
|
+
return { response: error(request.id, "RUN_ENDED", "the Run ended"), command: null };
|
|
269
|
+
}
|
|
270
|
+
if (phase === "settling") {
|
|
271
|
+
return { response: error(request.id, "RUN_SETTLING", "the Run is settling"), command: null };
|
|
272
|
+
}
|
|
273
|
+
const signature = signatureOf(request);
|
|
274
|
+
const coalesced = this.#coalesce(request.id, signature);
|
|
275
|
+
if (coalesced !== null) return coalesced;
|
|
276
|
+
// `#decide` moves the phase, so it runs only after coalescing ruled out a repeat.
|
|
277
|
+
const decision = this.#decide(request);
|
|
278
|
+
this.#remember(request.id, signature, decision.response);
|
|
279
|
+
return decision;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
#decide(request: Request): ControlDecision {
|
|
283
|
+
const phase = this.#phase.name;
|
|
284
|
+
if (phase === "stopping") {
|
|
285
|
+
return { response: error(request.id, "RUN_SETTLING", "the Run is settling"), command: null };
|
|
286
|
+
}
|
|
287
|
+
if (request.cmd === "stop") {
|
|
288
|
+
this.#phase = { name: "stopping" };
|
|
289
|
+
return { response: ok(request.id, "accepted"), command: { kind: "stop" } };
|
|
290
|
+
}
|
|
291
|
+
if (phase === "pausing") {
|
|
292
|
+
return { response: ok(request.id, "already_pausing"), command: null };
|
|
293
|
+
}
|
|
294
|
+
this.#phase = { name: "pausing" };
|
|
295
|
+
return {
|
|
296
|
+
response: ok(request.id, "accepted"),
|
|
297
|
+
command: { kind: "pause", deadlineMs: request.deadlineMs },
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public surface of the `control/` module: the command reader both inputs feed,
|
|
3
|
+
* external Run control, and the bounded pause drain (ADR-0024, ADR-0054).
|
|
4
|
+
* Files inside this directory import each other directly.
|
|
5
|
+
*/
|
|
6
|
+
export { type AskAdmission, createAskAdmission } from "./ask-admission.ts";
|
|
7
|
+
export {
|
|
8
|
+
type ControlCommand,
|
|
9
|
+
ControlCommandReader,
|
|
10
|
+
type ControlDecision,
|
|
11
|
+
type ControlErrorCode,
|
|
12
|
+
type ControlResponse,
|
|
13
|
+
type ControlResponseStatus,
|
|
14
|
+
PAUSE_DEADLINE_MAX_MS,
|
|
15
|
+
PAUSE_DEADLINE_MIN_MS,
|
|
16
|
+
} from "./control-commands.ts";
|
|
17
|
+
export {
|
|
18
|
+
type AskInFlight,
|
|
19
|
+
type DrainableAgent,
|
|
20
|
+
drainForPause,
|
|
21
|
+
type PauseDrainOptions,
|
|
22
|
+
type PauseDrainResult,
|
|
23
|
+
} from "./pause-drain.ts";
|
|
24
|
+
export {
|
|
25
|
+
type ControlRequest,
|
|
26
|
+
type ControlRequests,
|
|
27
|
+
controlRequests,
|
|
28
|
+
createRunController,
|
|
29
|
+
DEFAULT_PAUSE_DEADLINE_MS,
|
|
30
|
+
type RunController,
|
|
31
|
+
} from "./run-controller.ts";
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bounded pause drain (ADR-0024): wrap-up steer, then abort at the
|
|
3
|
+
* deadline, then force-close through the Run's reap ladder.
|
|
4
|
+
*
|
|
5
|
+
* The function takes structural inputs only — Agent handles, a deadline, an
|
|
6
|
+
* admission closer and a stop promise — so a program-initiated pause can call
|
|
7
|
+
* it unchanged.
|
|
8
|
+
*
|
|
9
|
+
* The drain deliberately does not trip `AskLimit`, so an externally paused Ask
|
|
10
|
+
* never misreports `ASK_LIMIT`. A soft budget that trips at the same moment
|
|
11
|
+
* simply sends its own steer first; both paths converge on the same reap ladder.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Controls of one Ask in flight, as the drain sees them; a Handle never exposes these. */
|
|
15
|
+
export interface AskInFlight {
|
|
16
|
+
readonly agent: string;
|
|
17
|
+
/**
|
|
18
|
+
* Sends this Ask's wrap-up steer. Never throws; a refusal is reported as
|
|
19
|
+
* false. An Agent that never answers leaves it pending, so the drain bounds
|
|
20
|
+
* this call by its own deadline rather than trusting it to settle.
|
|
21
|
+
*/
|
|
22
|
+
wrapUp(): Promise<boolean>;
|
|
23
|
+
/** Aborts the turn. Never throws, and the drain never waits for its answer. */
|
|
24
|
+
abort(): Promise<boolean>;
|
|
25
|
+
/** Resolves when the Ask leaves flight, whatever its outcome. Never rejects. */
|
|
26
|
+
readonly settled: Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What the drain needs from one Agent; `Agent` satisfies it structurally. */
|
|
30
|
+
export interface DrainableAgent {
|
|
31
|
+
readonly name: string;
|
|
32
|
+
readonly askInFlight: AskInFlight | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PauseDrainOptions {
|
|
36
|
+
/** Live reference to the Run's Agent list; read at drain start. */
|
|
37
|
+
readonly agents: readonly DrainableAgent[];
|
|
38
|
+
/** Wall-clock grace before the abort (ADR-0024). */
|
|
39
|
+
readonly deadlineMs: number;
|
|
40
|
+
/** Closes Ask and spawn admission before the first steer. */
|
|
41
|
+
readonly closeAdmission: () => void;
|
|
42
|
+
/** A stop request; it skips the remaining grace and takes the outcome. */
|
|
43
|
+
readonly stopped: Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** How one drain ended: paused, naming every Ask it cut short, or overridden by a stop. */
|
|
47
|
+
export type PauseDrainResult =
|
|
48
|
+
| { readonly kind: "paused"; readonly cutShort: readonly string[] }
|
|
49
|
+
| { readonly kind: "stopped" };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Drains one Run for a pause and resolves once the Run may settle.
|
|
53
|
+
*
|
|
54
|
+
* It never waits after an abort: the reap ladder of `executeRun` is the
|
|
55
|
+
* force-close, and it is what stamps the incomplete marker (ADR-0021).
|
|
56
|
+
*/
|
|
57
|
+
export async function drainForPause(options: PauseDrainOptions): Promise<PauseDrainResult> {
|
|
58
|
+
options.closeAdmission();
|
|
59
|
+
const inFlight = options.agents
|
|
60
|
+
.map((agent) => agent.askInFlight)
|
|
61
|
+
.filter((ask): ask is AskInFlight => ask !== null);
|
|
62
|
+
if (inFlight.length === 0) return { kind: "paused", cutShort: [] };
|
|
63
|
+
// The grace starts before the first steer, so an Agent that never answers a
|
|
64
|
+
// command cannot hold the drain open past the deadline, and a stop always
|
|
65
|
+
// lands. A refused steer is ignored on purpose: the deadline bounds it too.
|
|
66
|
+
const grace = raceGrace(inFlight, options);
|
|
67
|
+
for (const ask of inFlight) void ask.wrapUp();
|
|
68
|
+
const outcome = await grace;
|
|
69
|
+
if (outcome === "stopped") return { kind: "stopped" };
|
|
70
|
+
if (outcome === "settled") return { kind: "paused", cutShort: [] };
|
|
71
|
+
return { kind: "paused", cutShort: abortRemaining(options.agents) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type GraceOutcome = "settled" | "deadline" | "stopped";
|
|
75
|
+
|
|
76
|
+
/** Waits for every Ask to settle, the grace to elapse, or a stop to arrive. */
|
|
77
|
+
function raceGrace(
|
|
78
|
+
inFlight: readonly AskInFlight[],
|
|
79
|
+
options: PauseDrainOptions,
|
|
80
|
+
): Promise<GraceOutcome> {
|
|
81
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
82
|
+
const deadline = new Promise<GraceOutcome>((resolve) => {
|
|
83
|
+
timer = setTimeout(() => resolve("deadline"), options.deadlineMs);
|
|
84
|
+
});
|
|
85
|
+
const settled = Promise.all(inFlight.map((ask) => ask.settled)).then<GraceOutcome>(
|
|
86
|
+
() => "settled",
|
|
87
|
+
);
|
|
88
|
+
const stopped = options.stopped.then<GraceOutcome>(() => "stopped");
|
|
89
|
+
return Promise.race([settled, deadline, stopped]).finally(() => {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Aborts every Ask still in flight and names its Agent as cut short. The
|
|
96
|
+
* answers are deliberately not awaited: an Agent that swallows the abort must
|
|
97
|
+
* not hold the Run away from its reap ladder.
|
|
98
|
+
*/
|
|
99
|
+
function abortRemaining(agents: readonly DrainableAgent[]): readonly string[] {
|
|
100
|
+
const remaining = agents
|
|
101
|
+
.map((agent) => agent.askInFlight)
|
|
102
|
+
.filter((ask): ask is AskInFlight => ask !== null);
|
|
103
|
+
for (const ask of remaining) void ask.abort();
|
|
104
|
+
return remaining.map((ask) => ask.agent);
|
|
105
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* External Run control: the AbortController analogue for a pause (ADR-0024).
|
|
3
|
+
*
|
|
4
|
+
* A control reader holds the controller and requests a pause or a stop; the Run
|
|
5
|
+
* reads the request side only. The first request wins, and a stop always
|
|
6
|
+
* overrides a drain that is already running.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Default wall-clock grace one pause gives every Ask in flight (ADR-0024). */
|
|
10
|
+
export const DEFAULT_PAUSE_DEADLINE_MS = 60_000;
|
|
11
|
+
|
|
12
|
+
/** A terminal control request that settles the Run (ADR-0024). */
|
|
13
|
+
export type ControlRequest =
|
|
14
|
+
| { readonly kind: "pause"; readonly deadlineMs: number }
|
|
15
|
+
| { readonly kind: "stop" };
|
|
16
|
+
|
|
17
|
+
/** Run-side view: the first request wins, and a later stop overrides a drain. */
|
|
18
|
+
export interface ControlRequests {
|
|
19
|
+
/** The first pause or stop. Never rejects; never resolves without a request. */
|
|
20
|
+
readonly first: Promise<ControlRequest>;
|
|
21
|
+
/** A stop, whenever it arrives — including during a drain. Never rejects. */
|
|
22
|
+
readonly stopped: Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** External Run control handed to `executeRun`; the caller drives pause and stop. */
|
|
26
|
+
export interface RunController {
|
|
27
|
+
/** Requests a bounded drain. Coalesces once a first request landed. */
|
|
28
|
+
pause(deadlineMs?: number): void;
|
|
29
|
+
/** Requests an immediate stop; it outranks a pause, before or during a drain. */
|
|
30
|
+
stop(): void;
|
|
31
|
+
/** Read by `executeRun`; a control reader never touches it. */
|
|
32
|
+
readonly requests: ControlRequests;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A resolve-only deferred, so no control promise can ever reject. */
|
|
36
|
+
interface Deferred<T> {
|
|
37
|
+
readonly promise: Promise<T>;
|
|
38
|
+
resolve(value: T): void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function deferred<T>(): Deferred<T> {
|
|
42
|
+
let resolve: (value: T) => void = () => {};
|
|
43
|
+
const promise = new Promise<T>((settle) => {
|
|
44
|
+
resolve = settle;
|
|
45
|
+
});
|
|
46
|
+
return { promise, resolve };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Creates one Run's control handle. Both requests are idempotent. */
|
|
50
|
+
export function createRunController(): RunController {
|
|
51
|
+
const first = deferred<ControlRequest>();
|
|
52
|
+
const stop = deferred<void>();
|
|
53
|
+
return {
|
|
54
|
+
pause(deadlineMs = DEFAULT_PAUSE_DEADLINE_MS): void {
|
|
55
|
+
first.resolve({ kind: "pause", deadlineMs });
|
|
56
|
+
},
|
|
57
|
+
stop(): void {
|
|
58
|
+
first.resolve({ kind: "stop" });
|
|
59
|
+
stop.resolve();
|
|
60
|
+
},
|
|
61
|
+
requests: { first: first.promise, stopped: stop.promise },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Folds an `AbortSignal` and a controller into one Run-side view.
|
|
67
|
+
*
|
|
68
|
+
* The signal is a stop request, so an abort settles the Run exactly as
|
|
69
|
+
* `controller.stop()` does, before or during a drain.
|
|
70
|
+
*/
|
|
71
|
+
export function controlRequests(
|
|
72
|
+
control: RunController | undefined,
|
|
73
|
+
signal: AbortSignal | undefined,
|
|
74
|
+
): ControlRequests {
|
|
75
|
+
const folded = createRunController();
|
|
76
|
+
if (control !== undefined) {
|
|
77
|
+
void control.requests.first.then((request) => {
|
|
78
|
+
if (request.kind === "stop") folded.stop();
|
|
79
|
+
else folded.pause(request.deadlineMs);
|
|
80
|
+
});
|
|
81
|
+
void control.requests.stopped.then(() => folded.stop());
|
|
82
|
+
}
|
|
83
|
+
if (signal !== undefined) {
|
|
84
|
+
if (signal.aborted) folded.stop();
|
|
85
|
+
else signal.addEventListener("abort", () => folded.stop(), { once: true });
|
|
86
|
+
}
|
|
87
|
+
return folded.requests;
|
|
88
|
+
}
|
package/src/events.ts
CHANGED
|
@@ -26,6 +26,25 @@ export type RunOutcome = "completed" | "failed" | "stopped" | "paused" | "interr
|
|
|
26
26
|
*/
|
|
27
27
|
export type SpawnOrigin = "spawn" | "fork";
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Why a control request failed, or `BUSY` when a second Control Channel client
|
|
31
|
+
* asks while one holds the channel (ADR-0024, ADR-0054). It never says whether
|
|
32
|
+
* the Run acted: `run_end` is the durable phase-2 answer.
|
|
33
|
+
*/
|
|
34
|
+
export type ControlErrorCode =
|
|
35
|
+
| "MALFORMED"
|
|
36
|
+
| "UNSUPPORTED_VERSION"
|
|
37
|
+
| "UNKNOWN_CMD"
|
|
38
|
+
| "INVALID_FIELD"
|
|
39
|
+
| "DUPLICATE_ID"
|
|
40
|
+
| "FRAME_TOO_LONG"
|
|
41
|
+
| "RUN_SETTLING"
|
|
42
|
+
| "RUN_ENDED"
|
|
43
|
+
| "BUSY";
|
|
44
|
+
|
|
45
|
+
/** The outcome of one control request: taken, already in progress, or refused. */
|
|
46
|
+
export type ControlResponseStatus = "accepted" | "already_pausing" | "error";
|
|
47
|
+
|
|
29
48
|
/** The current, Ask-scoped observer projection derived from Agent frames. */
|
|
30
49
|
export type AgentActivity =
|
|
31
50
|
| { readonly type: "thinking" }
|
|
@@ -242,6 +261,27 @@ export type LifecycleEventBody =
|
|
|
242
261
|
* failed. Carries the publication error text. Absent on every other path.
|
|
243
262
|
*/
|
|
244
263
|
readonly checkpointLost?: string;
|
|
264
|
+
/**
|
|
265
|
+
* Path of the Checkpoint this Run published, present only when the Run
|
|
266
|
+
* paused or stopped and publication succeeded (ADR-0054). The Reattach
|
|
267
|
+
* client resumes from it, and refuses a path it did not expect.
|
|
268
|
+
*/
|
|
269
|
+
readonly checkpoint?: string;
|
|
270
|
+
}
|
|
271
|
+
| {
|
|
272
|
+
/**
|
|
273
|
+
* Phase-1 acknowledgement of exactly one control request (ADR-0024): the
|
|
274
|
+
* Run read the frame and decided. It is never durability — the Run's real
|
|
275
|
+
* answer is `run_end` (phase 2). `id` is null when the frame carried no
|
|
276
|
+
* usable id, so a client that waits on an id never hangs on a frame it
|
|
277
|
+
* can identify.
|
|
278
|
+
*/
|
|
279
|
+
readonly type: "control_response";
|
|
280
|
+
readonly id: string | null;
|
|
281
|
+
readonly status: ControlResponseStatus;
|
|
282
|
+
/** Present exactly when `status` is `"error"`. */
|
|
283
|
+
readonly code?: ControlErrorCode;
|
|
284
|
+
readonly message?: string;
|
|
245
285
|
};
|
|
246
286
|
|
|
247
287
|
/**
|