@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
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isReportResultCommandFrame,
|
|
3
|
+
RESUME_NUDGE,
|
|
4
|
+
readQuestionFrame,
|
|
5
|
+
} from "../ask-contract/index.ts";
|
|
1
6
|
import type {
|
|
2
7
|
AgentStats,
|
|
3
8
|
AgentTransport,
|
|
@@ -14,7 +19,7 @@ import type {
|
|
|
14
19
|
TransportStartupObserver,
|
|
15
20
|
} from "../transport/index.ts";
|
|
16
21
|
import { FrameQueue } from "../transport/index.ts";
|
|
17
|
-
import type { Cassette, CassetteAgent } from "./cassette.ts";
|
|
22
|
+
import type { Cassette, CassetteAgent, CassetteAsk } from "./cassette.ts";
|
|
18
23
|
import { CassetteReplay } from "./cassette-replay.ts";
|
|
19
24
|
import {
|
|
20
25
|
recordedSpawnSelection,
|
|
@@ -23,13 +28,27 @@ import {
|
|
|
23
28
|
} from "./replay-divergence.ts";
|
|
24
29
|
import { checkResumePreconditions } from "./resume-preconditions.ts";
|
|
25
30
|
|
|
31
|
+
/**
|
|
32
|
+
* What a resume knows about the human's answers (ADR-0023). A recorded Ask
|
|
33
|
+
* that parked on `request_user_input` reads its answer here: with one, the Ask
|
|
34
|
+
* is restored; without one, it parks again and the Run pauses.
|
|
35
|
+
*/
|
|
36
|
+
export interface AskUserRestoration {
|
|
37
|
+
/** The answer of a recorded parked Ask, or undefined when it stays open. */
|
|
38
|
+
answerFor(questionId: string): string | undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
26
41
|
/**
|
|
27
42
|
* Creates a Cassette-prefix transport that continues with live pi at divergence.
|
|
28
43
|
*
|
|
29
44
|
* Matched Agents validate their recorded continuation point before replaying.
|
|
30
45
|
* Spawn mismatches intentionally bypass those checks and start a fresh Agent.
|
|
31
46
|
*/
|
|
32
|
-
export function resumeTransport(
|
|
47
|
+
export function resumeTransport(
|
|
48
|
+
cassette: Cassette,
|
|
49
|
+
live: TransportFactory,
|
|
50
|
+
restoration?: AskUserRestoration,
|
|
51
|
+
): TransportFactory {
|
|
33
52
|
let spawnCursor = 0;
|
|
34
53
|
return {
|
|
35
54
|
async open(
|
|
@@ -45,7 +64,7 @@ export function resumeTransport(cassette: Cassette, live: TransportFactory): Tra
|
|
|
45
64
|
...(agent.sessionFile === undefined ? {} : { sessionFile: agent.sessionFile }),
|
|
46
65
|
...(worktree === undefined ? {} : { worktree }),
|
|
47
66
|
});
|
|
48
|
-
return new ResumeTransport(agent, live, options);
|
|
67
|
+
return new ResumeTransport(agent, live, options, restoration);
|
|
49
68
|
},
|
|
50
69
|
|
|
51
70
|
// A changed spawn must not silently inherit the recorded model, so the
|
|
@@ -64,6 +83,9 @@ class ResumeTransport implements AgentTransport {
|
|
|
64
83
|
readonly #liveFactory: TransportFactory;
|
|
65
84
|
readonly #continuation: OpenOptions;
|
|
66
85
|
readonly #replay: CassetteReplay;
|
|
86
|
+
readonly #restoration: AskUserRestoration | undefined;
|
|
87
|
+
/** The Ask prompt the nudge replaces, while a restored Ask still awaits it. */
|
|
88
|
+
#nudgePrompt: string | null = null;
|
|
67
89
|
readonly #frames = new FrameQueue();
|
|
68
90
|
readonly #buffered: Frame[] = [];
|
|
69
91
|
#askCursor = 0;
|
|
@@ -74,8 +96,14 @@ class ResumeTransport implements AgentTransport {
|
|
|
74
96
|
#activationFailed = false;
|
|
75
97
|
#closed: Promise<AgentStats> | null = null;
|
|
76
98
|
|
|
77
|
-
constructor(
|
|
99
|
+
constructor(
|
|
100
|
+
agent: CassetteAgent,
|
|
101
|
+
liveFactory: TransportFactory,
|
|
102
|
+
options: OpenOptions,
|
|
103
|
+
restoration?: AskUserRestoration,
|
|
104
|
+
) {
|
|
78
105
|
this.#agent = agent;
|
|
106
|
+
this.#restoration = restoration;
|
|
79
107
|
this.#liveFactory = liveFactory;
|
|
80
108
|
this.#continuation = continuationOptions(agent, options);
|
|
81
109
|
this.#replay = new CassetteReplay(agent);
|
|
@@ -92,7 +120,7 @@ class ResumeTransport implements AgentTransport {
|
|
|
92
120
|
this.#buffered.push(frame);
|
|
93
121
|
return;
|
|
94
122
|
}
|
|
95
|
-
this.#live?.send(frame);
|
|
123
|
+
this.#live?.send(this.#nudged(frame));
|
|
96
124
|
}
|
|
97
125
|
|
|
98
126
|
frames(): AsyncIterable<Frame> {
|
|
@@ -104,6 +132,10 @@ class ResumeTransport implements AgentTransport {
|
|
|
104
132
|
if (this.#mode === "activating") return undefined;
|
|
105
133
|
const mismatch = replayMismatch.ask(this.#agent, this.#askCursor, marker);
|
|
106
134
|
if (!mismatch) {
|
|
135
|
+
// The restoration comes after the match: a parked Ask whose marker moved
|
|
136
|
+
// is a diverged Ask, and it must never inherit another Ask's question.
|
|
137
|
+
const restored = this.#restore(this.#agent.asks[this.#askCursor]);
|
|
138
|
+
if (restored !== null) return restored;
|
|
107
139
|
this.#askCursor += 1;
|
|
108
140
|
return this.#replay.beginAsk(marker);
|
|
109
141
|
}
|
|
@@ -146,6 +178,53 @@ class ResumeTransport implements AgentTransport {
|
|
|
146
178
|
return this.#closed;
|
|
147
179
|
}
|
|
148
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Handles a recorded Ask that parked on `request_user_input` (ADR-0023).
|
|
183
|
+
*
|
|
184
|
+
* The recorded Ask has no settlement, so it can never replay. With an answer
|
|
185
|
+
* it is restored: the answer goes into the session, pi respawns on it, and
|
|
186
|
+
* the nudge replaces the Ask prompt the Agent already saw. Without an answer
|
|
187
|
+
* the playback re-opens the same Question, and the Run pauses again.
|
|
188
|
+
*/
|
|
189
|
+
#restore(ask: CassetteAsk | undefined): AskPlayback | undefined | null {
|
|
190
|
+
const incomplete = ask?.incomplete;
|
|
191
|
+
if (ask === undefined || incomplete === undefined) return null;
|
|
192
|
+
const answer = this.#restoration?.answerFor(incomplete.questionId);
|
|
193
|
+
if (answer === undefined) {
|
|
194
|
+
const call = recordedQuestion(ask, incomplete.toolCallId);
|
|
195
|
+
this.#askCursor += 1;
|
|
196
|
+
return {
|
|
197
|
+
settles: false,
|
|
198
|
+
parked: {
|
|
199
|
+
toolCallId: incomplete.toolCallId,
|
|
200
|
+
questionId: incomplete.questionId,
|
|
201
|
+
question: call?.question ?? "",
|
|
202
|
+
...(call?.context === undefined ? {} : { context: call.context }),
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
// The answer is already in the session: `restoreSessionAnswers` wrote it
|
|
207
|
+
// before the Run started. This side only respawns and nudges (ADR-0023).
|
|
208
|
+
// The latch names the recorded Ask prompt, so the substitution hits that
|
|
209
|
+
// one frame and never the `report_result` schema command beside it.
|
|
210
|
+
this.#nudgePrompt = recordedPrompt(ask);
|
|
211
|
+
this.#mode = "activating";
|
|
212
|
+
this.#activation = this.#activate(null);
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Substitutes the nudge for the Ask prompt of a restored Ask, one time. Every
|
|
218
|
+
* other frame, the `report_result` schema command included, passes through
|
|
219
|
+
* unchanged, and the frame id stays, so the Ask's command still settles.
|
|
220
|
+
*/
|
|
221
|
+
#nudged(frame: Frame): Frame {
|
|
222
|
+
if (this.#nudgePrompt === null) return frame;
|
|
223
|
+
if (frame.type !== "prompt" || frame.message !== this.#nudgePrompt) return frame;
|
|
224
|
+
this.#nudgePrompt = null;
|
|
225
|
+
return { ...frame, message: RESUME_NUDGE };
|
|
226
|
+
}
|
|
227
|
+
|
|
149
228
|
async #activate(marker: AskMarker | null): Promise<void> {
|
|
150
229
|
// End the old source before attaching the new one, but keep the outward
|
|
151
230
|
// queue open so Connection remains attached across the handoff.
|
|
@@ -157,7 +236,7 @@ class ResumeTransport implements AgentTransport {
|
|
|
157
236
|
const live = await this.#liveFactory.open(this.#continuation);
|
|
158
237
|
this.#live = live;
|
|
159
238
|
if (marker !== null) live.beginAsk(marker);
|
|
160
|
-
for (const frame of this.#buffered.splice(0)) live.send(frame);
|
|
239
|
+
for (const frame of this.#buffered.splice(0)) live.send(this.#nudged(frame));
|
|
161
240
|
this.#mode = "live";
|
|
162
241
|
void this.#forward(live.frames());
|
|
163
242
|
} catch {
|
|
@@ -198,6 +277,32 @@ class ResumeTransport implements AgentTransport {
|
|
|
198
277
|
}
|
|
199
278
|
}
|
|
200
279
|
|
|
280
|
+
/**
|
|
281
|
+
* The Ask prompt of a recorded Ask, read back from its sent frames. The private
|
|
282
|
+
* `report_result` schema command is a prompt frame too, and it is not the Ask
|
|
283
|
+
* prompt, so it is skipped (ADR-0032).
|
|
284
|
+
*/
|
|
285
|
+
function recordedPrompt(ask: CassetteAsk): string | null {
|
|
286
|
+
for (const frame of ask.sentFrames) {
|
|
287
|
+
if (frame.type !== "prompt" || typeof frame.message !== "string") continue;
|
|
288
|
+
if (isReportResultCommandFrame(frame)) continue;
|
|
289
|
+
return frame.message;
|
|
290
|
+
}
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** The parked call of a recorded Ask, read back from its frames. */
|
|
295
|
+
function recordedQuestion(
|
|
296
|
+
ask: CassetteAsk,
|
|
297
|
+
toolCallId: string,
|
|
298
|
+
): { readonly question: string; readonly context?: string } | undefined {
|
|
299
|
+
for (const frame of ask.receivedFrames) {
|
|
300
|
+
const call = readQuestionFrame(frame);
|
|
301
|
+
if (call !== null && call.toolCallId === toolCallId) return call;
|
|
302
|
+
}
|
|
303
|
+
return undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
201
306
|
function continuationOptions(agent: CassetteAgent, original: OpenOptions): OpenOptions {
|
|
202
307
|
const { worktree: _worktree, ...spawn } = agent.spawn;
|
|
203
308
|
const worktree = worktreeResolution(agent);
|
|
@@ -2,12 +2,28 @@ import { mkdir, unlink } from "node:fs/promises";
|
|
|
2
2
|
import { dirname } from "node:path";
|
|
3
3
|
import { YaagError } from "../errors.ts";
|
|
4
4
|
import type { RunOutcome } from "../events.ts";
|
|
5
|
-
import type {
|
|
5
|
+
import type {
|
|
6
|
+
CassetteAnswer,
|
|
7
|
+
CassetteCollector,
|
|
8
|
+
CassetteQuestion,
|
|
9
|
+
CassetteRun,
|
|
10
|
+
} from "./cassette.ts";
|
|
6
11
|
import { publishCassette } from "./cassette-publish.ts";
|
|
7
12
|
import { sha256Hex } from "./program-hash.ts";
|
|
8
13
|
|
|
9
14
|
/** What a resume is about to re-execute; resolved once, at Run start. */
|
|
10
|
-
export type RunIdentity = Omit<CassetteRun, "outcome">;
|
|
15
|
+
export type RunIdentity = Omit<CassetteRun, "outcome" | "questions" | "answers" | "reason">;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The wake payload of a paused or stopped Run (ADR-0021). It is settlement
|
|
19
|
+
* data, never invocation identity, so it travels beside `RunIdentity`.
|
|
20
|
+
*/
|
|
21
|
+
export interface RunWakePayload {
|
|
22
|
+
readonly questions: readonly CassetteQuestion[];
|
|
23
|
+
/** Questions this Run resolved, plus every answer it inherited (ADR-0022). */
|
|
24
|
+
readonly answers?: readonly CassetteAnswer[];
|
|
25
|
+
readonly reason?: string;
|
|
26
|
+
}
|
|
11
27
|
|
|
12
28
|
/**
|
|
13
29
|
* One Run's publication request: what settled, what it collected, and where the
|
|
@@ -24,6 +40,14 @@ export interface RunCheckpointOptions {
|
|
|
24
40
|
readonly destination: string;
|
|
25
41
|
/** Invocation identity written into the artifact's run block. */
|
|
26
42
|
readonly identity: RunIdentity;
|
|
43
|
+
/**
|
|
44
|
+
* Wake payload: the Questions and the pause reason collected at settlement.
|
|
45
|
+
* They ride a `paused`
|
|
46
|
+
* and a `stopped` artifact only: a stop that overrides a drain must not
|
|
47
|
+
* discard collected Questions (ADR-0021). An in-flight `interrupted` flush
|
|
48
|
+
* carries neither, and a hard death mid-pause loses them.
|
|
49
|
+
*/
|
|
50
|
+
readonly wake?: RunWakePayload;
|
|
27
51
|
}
|
|
28
52
|
|
|
29
53
|
/**
|
|
@@ -56,7 +80,11 @@ export async function publishRunCheckpoint(
|
|
|
56
80
|
await ensureCheckpointDirectory(options.record, options.destination);
|
|
57
81
|
await publishCassette(
|
|
58
82
|
options.destination,
|
|
59
|
-
options.collector.cassette({
|
|
83
|
+
options.collector.cassette({
|
|
84
|
+
outcome: options.outcome,
|
|
85
|
+
...options.identity,
|
|
86
|
+
...wakePayload(options.outcome, options.wake),
|
|
87
|
+
}),
|
|
60
88
|
);
|
|
61
89
|
return { kind: "published" };
|
|
62
90
|
} catch (error) {
|
|
@@ -88,6 +116,27 @@ export async function publishRunCheckpoint(
|
|
|
88
116
|
}
|
|
89
117
|
}
|
|
90
118
|
|
|
119
|
+
/**
|
|
120
|
+
* The wake payload of a run block. Empty for every outcome other than `paused`
|
|
121
|
+
* and `stopped`, and minimal for a plain `ctx.pause()`, so an artifact that
|
|
122
|
+
* collected nothing keeps the bytes it had before this field existed.
|
|
123
|
+
*
|
|
124
|
+
* A `failed` artifact keeps no answers either, exactly as it keeps no
|
|
125
|
+
* Questions: it is not a resume source of the answer contract, and a resume of
|
|
126
|
+
* the Checkpoint that preceded it takes the answers again (ADR-0022).
|
|
127
|
+
*/
|
|
128
|
+
function wakePayload(
|
|
129
|
+
outcome: RunOutcome,
|
|
130
|
+
wake: RunWakePayload | undefined,
|
|
131
|
+
): Pick<CassetteRun, "questions" | "answers" | "reason"> {
|
|
132
|
+
if (wake === undefined || (outcome !== "paused" && outcome !== "stopped")) return {};
|
|
133
|
+
return {
|
|
134
|
+
...(wake.questions.length === 0 ? {} : { questions: wake.questions }),
|
|
135
|
+
...(wake.answers === undefined || wake.answers.length === 0 ? {} : { answers: wake.answers }),
|
|
136
|
+
...(wake.reason === undefined ? {} : { reason: wake.reason }),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
91
140
|
/**
|
|
92
141
|
* Whether a Run keeps its artifact: `--record` names a destination, or the Run
|
|
93
142
|
* paused or stopped. Every other Run discards the in-flight artifact, so it
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restoration of one human answer into a pi session file (ADR-0023).
|
|
3
|
+
*
|
|
4
|
+
* The Agent parked on a `request_user_input` tool call and the process died.
|
|
5
|
+
* The answer goes back into the session as the tool result of that call, so the
|
|
6
|
+
* respawned Agent reads it as the result of its own request.
|
|
7
|
+
*
|
|
8
|
+
* The file is JSONL, one entry per line, pi session version 3. Parsing is
|
|
9
|
+
* lenient on purpose: an unknown entry type, or one line yaag cannot parse, is
|
|
10
|
+
* not this module's business, and must not fail a restoration.
|
|
11
|
+
*/
|
|
12
|
+
import { appendFile } from "node:fs/promises";
|
|
13
|
+
import { REQUEST_USER_INPUT_TOOL_NAME } from "../ask-contract/index.ts";
|
|
14
|
+
import { YaagError } from "../errors.ts";
|
|
15
|
+
import type { Cassette } from "./cassette.ts";
|
|
16
|
+
|
|
17
|
+
/** One correlated answer, and the session file it belongs to. */
|
|
18
|
+
export interface SessionAnswerAppend {
|
|
19
|
+
readonly sessionFile: string;
|
|
20
|
+
/** The tool call id of the parked `request_user_input` call. */
|
|
21
|
+
readonly toolCallId: string;
|
|
22
|
+
readonly answer: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface SessionEntry {
|
|
26
|
+
readonly id?: unknown;
|
|
27
|
+
readonly message?: {
|
|
28
|
+
readonly role?: unknown;
|
|
29
|
+
readonly toolCallId?: unknown;
|
|
30
|
+
readonly content?: unknown;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Appends the answer as the tool result of the parked call.
|
|
36
|
+
*
|
|
37
|
+
* The same answer already in the file is a skip, so retrying a resume changes
|
|
38
|
+
* nothing. A different answer for the same call is a refusal: an answered
|
|
39
|
+
* question has one answer (ADR-0022). An absent tool call is a refusal too —
|
|
40
|
+
* the session is not the one the Cassette recorded.
|
|
41
|
+
*/
|
|
42
|
+
export async function appendSessionAnswer(request: SessionAnswerAppend): Promise<void> {
|
|
43
|
+
const entries = await readEntries(request.sessionFile);
|
|
44
|
+
const call = entries.find((entry) => holdsToolCall(entry, request.toolCallId));
|
|
45
|
+
if (call === undefined) {
|
|
46
|
+
throw new YaagError(
|
|
47
|
+
"RESUME_REFUSED",
|
|
48
|
+
`the session file ${request.sessionFile} holds no tool call "${request.toolCallId}" — ` +
|
|
49
|
+
`it is not the session this checkpoint recorded`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
const present = entries.find((entry) => isToolResult(entry, request.toolCallId));
|
|
53
|
+
if (present !== undefined) {
|
|
54
|
+
const text = resultText(present);
|
|
55
|
+
if (text === request.answer) return;
|
|
56
|
+
throw new YaagError(
|
|
57
|
+
"RESUME_REFUSED",
|
|
58
|
+
`the tool call "${request.toolCallId}" is already answered with "${String(text)}" — ` +
|
|
59
|
+
`it cannot be answered with "${request.answer}" as well`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
await appendFile(request.sessionFile, `${JSON.stringify(resultEntry(request, call))}\n`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Restores every answered park of a resume source, before the Run starts.
|
|
67
|
+
*
|
|
68
|
+
* The restoration runs first, and not at the respawn, so a refused answer stops
|
|
69
|
+
* the resume before it does any work (ADR-0023). It is same-or-refuse, so a
|
|
70
|
+
* retried resume changes nothing.
|
|
71
|
+
*/
|
|
72
|
+
export async function restoreSessionAnswers(
|
|
73
|
+
cassette: Cassette,
|
|
74
|
+
answerFor: (questionId: string) => string | undefined,
|
|
75
|
+
): Promise<void> {
|
|
76
|
+
for (const agent of cassette.agents) {
|
|
77
|
+
const sessionFile = agent.sessionFile;
|
|
78
|
+
if (sessionFile === undefined) continue;
|
|
79
|
+
for (const ask of agent.asks) {
|
|
80
|
+
const incomplete = ask.incomplete;
|
|
81
|
+
if (incomplete === undefined) continue;
|
|
82
|
+
const answer = answerFor(incomplete.questionId);
|
|
83
|
+
if (answer === undefined) continue;
|
|
84
|
+
await appendSessionAnswer({ sessionFile, toolCallId: incomplete.toolCallId, answer });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The entry one answer becomes: a `toolResult` message correlated by tool call id. */
|
|
90
|
+
function resultEntry(request: SessionAnswerAppend, call: SessionEntry): unknown {
|
|
91
|
+
const now = Date.now();
|
|
92
|
+
return {
|
|
93
|
+
type: "message",
|
|
94
|
+
id: entryId(),
|
|
95
|
+
parentId: typeof call.id === "string" ? call.id : null,
|
|
96
|
+
timestamp: new Date(now).toISOString(),
|
|
97
|
+
message: {
|
|
98
|
+
role: "toolResult",
|
|
99
|
+
toolCallId: request.toolCallId,
|
|
100
|
+
toolName: REQUEST_USER_INPUT_TOOL_NAME,
|
|
101
|
+
content: [{ type: "text", text: request.answer }],
|
|
102
|
+
isError: false,
|
|
103
|
+
timestamp: now,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Eight hex digits, pi's own entry id shape; the file never addresses this one. */
|
|
109
|
+
function entryId(): string {
|
|
110
|
+
return Math.floor(Math.random() * 0x1_0000_0000)
|
|
111
|
+
.toString(16)
|
|
112
|
+
.padStart(8, "0");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Reads the session, and drops every line yaag cannot parse. */
|
|
116
|
+
async function readEntries(sessionFile: string): Promise<readonly SessionEntry[]> {
|
|
117
|
+
let text: string;
|
|
118
|
+
try {
|
|
119
|
+
text = await Bun.file(sessionFile).text();
|
|
120
|
+
} catch (error) {
|
|
121
|
+
throw new YaagError(
|
|
122
|
+
"RESUME_REFUSED",
|
|
123
|
+
`cannot read the session file ${sessionFile}: ${String(error)}`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
const entries: SessionEntry[] = [];
|
|
127
|
+
for (const line of text.split("\n")) {
|
|
128
|
+
if (line.trim() === "") continue;
|
|
129
|
+
try {
|
|
130
|
+
const parsed: unknown = JSON.parse(line);
|
|
131
|
+
if (typeof parsed === "object" && parsed !== null) entries.push(parsed as SessionEntry);
|
|
132
|
+
} catch {
|
|
133
|
+
// One malformed line is not a malformed session: pi may have died mid-write.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return entries;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function holdsToolCall(entry: SessionEntry, toolCallId: string): boolean {
|
|
140
|
+
if (entry.message?.role !== "assistant") return false;
|
|
141
|
+
return contentParts(entry).some((part) => part.type === "toolCall" && part.id === toolCallId);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function isToolResult(entry: SessionEntry, toolCallId: string): boolean {
|
|
145
|
+
return entry.message?.role === "toolResult" && entry.message.toolCallId === toolCallId;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function resultText(entry: SessionEntry): string | undefined {
|
|
149
|
+
const part = contentParts(entry).find((candidate) => candidate.type === "text");
|
|
150
|
+
return typeof part?.text === "string" ? part.text : undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface ContentPart {
|
|
154
|
+
readonly type?: unknown;
|
|
155
|
+
readonly id?: unknown;
|
|
156
|
+
readonly text?: unknown;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function contentParts(entry: SessionEntry): readonly ContentPart[] {
|
|
160
|
+
const content = entry.message?.content;
|
|
161
|
+
if (!Array.isArray(content)) return [];
|
|
162
|
+
return content.filter((part): part is ContentPart => typeof part === "object" && part !== null);
|
|
163
|
+
}
|
package/src/catalog/index.ts
CHANGED
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
* fixture Catalog consumer tests assert against, plus the on-demand describe
|
|
5
5
|
* contract for a registered Agent Definition (ADR-0047) and its recorded
|
|
6
6
|
* CLI-child transcript, plus the reader, the program
|
|
7
|
-
* scanner,
|
|
8
|
-
* `registry-reader.ts`, and `program-scan.ts`
|
|
9
|
-
* and import no
|
|
7
|
+
* scanner, the layer merge, and the Catalog Resolve resolver. The contract
|
|
8
|
+
* half is pure; `load-catalog.ts`, `registry-reader.ts`, and `program-scan.ts`
|
|
9
|
+
* — the readers and the scanner — import no module; `resolve.ts` is the one
|
|
10
|
+
* file that imports a Definition module, on a program's request (ADR-0053).
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
export type {
|
|
@@ -56,3 +57,4 @@ export {
|
|
|
56
57
|
parseRegistryFile,
|
|
57
58
|
readRegistryDocument,
|
|
58
59
|
} from "./registry-schema.ts";
|
|
60
|
+
export { createYaagGlobal } from "./resolve.ts";
|
|
@@ -31,7 +31,7 @@ const EMPTY: CatalogResult = { rows: [], diagnostics: [] };
|
|
|
31
31
|
* This function imports no Orchestration Program module and reads no target
|
|
32
32
|
* file. Two guards keep that honest: `registry-reader.test.ts` writes a module
|
|
33
33
|
* with a top-level side effect and asserts the marker file was never created,
|
|
34
|
-
* and `apps/yaag/
|
|
34
|
+
* and `apps/yaag/test/program/runtime-alias.test.ts` guards the
|
|
35
35
|
* program-visible surface.
|
|
36
36
|
*/
|
|
37
37
|
export async function readRegistryLayer(request: RegistryLayerRequest): Promise<CatalogResult> {
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Catalog Resolve resolver (ADR-0053). It is the one file in `catalog/`
|
|
3
|
+
* that imports an Orchestration Program's Definition module, and only on a
|
|
4
|
+
* program's request.
|
|
5
|
+
*
|
|
6
|
+
* It calls `readFile` and `parseRegistryFile` directly and never
|
|
7
|
+
* `readRegistryLayer`: the reader turns every failure into a diagnostic, and
|
|
8
|
+
* this call must throw.
|
|
9
|
+
*/
|
|
10
|
+
import { readFile, stat } from "node:fs/promises";
|
|
11
|
+
import { dirname, resolve } from "node:path";
|
|
12
|
+
import { isSpawnableDefinition } from "../agent/index.ts";
|
|
13
|
+
import type {
|
|
14
|
+
CatalogScope,
|
|
15
|
+
SpawnableDefinition,
|
|
16
|
+
YaagGlobal,
|
|
17
|
+
YaagGlobalOptions,
|
|
18
|
+
} from "../contract/index.ts";
|
|
19
|
+
import { YaagError } from "../errors.ts";
|
|
20
|
+
import type { AgentDefinitionEntry } from "./catalog-entry.ts";
|
|
21
|
+
import { parseRegistryFile } from "./registry-schema.ts";
|
|
22
|
+
|
|
23
|
+
/** Builds the `$yaag` global: two independent Catalog Scopes, never `undefined`. */
|
|
24
|
+
export function createYaagGlobal(options: YaagGlobalOptions): YaagGlobal {
|
|
25
|
+
return {
|
|
26
|
+
global: scope("global", options.globalRegistryPath),
|
|
27
|
+
project: scope("project", options.projectRegistryPath),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function scope(name: "global" | "project", registryPath: string | undefined): CatalogScope {
|
|
32
|
+
return { importAgent: (agent) => importAgent({ scope: name, registryPath, name: agent }) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** One resolve request: which scope asked, which Registry File, which name. */
|
|
36
|
+
interface ResolveRequest {
|
|
37
|
+
readonly scope: "global" | "project";
|
|
38
|
+
readonly registryPath: string | undefined;
|
|
39
|
+
readonly name: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Runs the fixed check order of the spec (decision 9). */
|
|
43
|
+
async function importAgent(request: ResolveRequest): Promise<SpawnableDefinition> {
|
|
44
|
+
if (request.registryPath === undefined) {
|
|
45
|
+
throw notFound(request, "this Run has no Program Directory");
|
|
46
|
+
}
|
|
47
|
+
const registry = resolve(request.registryPath);
|
|
48
|
+
const text = await readRegistry(request, registry);
|
|
49
|
+
const entries = parseEntries(request, registry, text);
|
|
50
|
+
|
|
51
|
+
const matches = entries.filter((entry) => entry.name === request.name);
|
|
52
|
+
if (matches.length > 1) {
|
|
53
|
+
const files = matches.map((entry) => JSON.stringify(entry.file)).join(", ");
|
|
54
|
+
throw new YaagError(
|
|
55
|
+
"CATALOG_ENTRY_AMBIGUOUS",
|
|
56
|
+
`${prefix(request)}: ${matches.length} agent entries have this name in ${registry}: ${files}`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
const [entry] = matches;
|
|
60
|
+
if (entry === undefined) {
|
|
61
|
+
throw notFound(request, `no agent entry has this name in ${registry}`);
|
|
62
|
+
}
|
|
63
|
+
const malformed =
|
|
64
|
+
entry.file === ""
|
|
65
|
+
? "file is empty"
|
|
66
|
+
: entry.exportName === ""
|
|
67
|
+
? "exportName is empty"
|
|
68
|
+
: undefined;
|
|
69
|
+
if (malformed !== undefined) {
|
|
70
|
+
throw unresolvable(request, `the entry in ${registry} is malformed: ${malformed}`, malformed);
|
|
71
|
+
}
|
|
72
|
+
return await loadEntry(request, resolve(dirname(registry), entry.file), entry.exportName);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Step 1, the read. ENOENT alone is `NOT_FOUND`; every other errno is
|
|
77
|
+
* `cannot be read`. This deviates from `readRegistryLayer`, which also
|
|
78
|
+
* swallows ENOTDIR: the spec names ENOENT only, thus a registry path under a
|
|
79
|
+
* file reads as `cannot be read`.
|
|
80
|
+
*/
|
|
81
|
+
async function readRegistry(request: ResolveRequest, registry: string): Promise<string> {
|
|
82
|
+
try {
|
|
83
|
+
return await readFile(registry, "utf8");
|
|
84
|
+
} catch (cause) {
|
|
85
|
+
if ((cause as NodeJS.ErrnoException).code === "ENOENT") {
|
|
86
|
+
throw notFound(request, `no Registry File at ${registry}`);
|
|
87
|
+
}
|
|
88
|
+
throw unresolvable(request, `${registry} did not parse: cannot be read`, "cannot be read");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Step 1, the parse. The file-scoped diagnostic prose comes from
|
|
94
|
+
* `registry-schema.ts`; this maps it to the spec's three remaining reasons. A
|
|
95
|
+
* `programs`-section diagnostic is ignored on purpose: a broken `programs`
|
|
96
|
+
* array never fails an agent resolve.
|
|
97
|
+
*/
|
|
98
|
+
function parseEntries(
|
|
99
|
+
request: ResolveRequest,
|
|
100
|
+
registry: string,
|
|
101
|
+
text: string,
|
|
102
|
+
): readonly AgentDefinitionEntry[] {
|
|
103
|
+
const parsed = parseRegistryFile(text, registry);
|
|
104
|
+
for (const diagnostic of parsed.diagnostics) {
|
|
105
|
+
if (diagnostic.scope !== "file") continue;
|
|
106
|
+
const reason = parseReason(diagnostic.message);
|
|
107
|
+
if (reason === undefined) continue;
|
|
108
|
+
throw unresolvable(request, `${registry} did not parse: ${reason}`, reason);
|
|
109
|
+
}
|
|
110
|
+
return parsed.entries;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function parseReason(message: string): string | undefined {
|
|
114
|
+
if (message.includes("is not valid JSON")) return "is not valid JSON";
|
|
115
|
+
if (message.includes("must contain a JSON object")) return "root is not an object";
|
|
116
|
+
if (message.includes('"agents" must be an array')) return "agents is not an array";
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Steps 5 to 8: the target file, the import, the export, the predicate. */
|
|
121
|
+
async function loadEntry(
|
|
122
|
+
request: ResolveRequest,
|
|
123
|
+
target: string,
|
|
124
|
+
exportName: string,
|
|
125
|
+
): Promise<SpawnableDefinition> {
|
|
126
|
+
if (!(await isFile(target))) {
|
|
127
|
+
throw unresolvable(request, targetTail(target, "file not found"), "file not found");
|
|
128
|
+
}
|
|
129
|
+
let namespace: unknown;
|
|
130
|
+
try {
|
|
131
|
+
namespace = await import(target);
|
|
132
|
+
} catch (cause) {
|
|
133
|
+
throw failed(request, targetTail(target, "module threw on import"), cause);
|
|
134
|
+
}
|
|
135
|
+
if (typeof namespace !== "object" || namespace === null || !(exportName in namespace)) {
|
|
136
|
+
const reason = `export "${exportName}" not found`;
|
|
137
|
+
throw unresolvable(request, targetTail(target, reason), reason);
|
|
138
|
+
}
|
|
139
|
+
const value = Reflect.get(namespace, exportName);
|
|
140
|
+
if (!isSpawnableDefinition(value)) {
|
|
141
|
+
const reason = `export "${exportName}" is not a Spawnable Definition`;
|
|
142
|
+
throw unresolvable(request, targetTail(target, reason), reason);
|
|
143
|
+
}
|
|
144
|
+
return value;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function isFile(target: string): Promise<boolean> {
|
|
148
|
+
try {
|
|
149
|
+
return (await stat(target)).isFile();
|
|
150
|
+
} catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function prefix(request: ResolveRequest): string {
|
|
156
|
+
return `$yaag.${request.scope}.importAgent("${request.name}")`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function notFound(request: ResolveRequest, tail: string): YaagError {
|
|
160
|
+
return new YaagError("CATALOG_ENTRY_NOT_FOUND", `${prefix(request)}: ${tail}`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* An UNRESOLVABLE whose cause is a plain `Error` with the reason fragment as
|
|
165
|
+
* its message, and nothing else (decision 10).
|
|
166
|
+
*/
|
|
167
|
+
function unresolvable(request: ResolveRequest, tail: string, reason: string): YaagError {
|
|
168
|
+
return failed(request, tail, new Error(reason));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** An UNRESOLVABLE whose cause is the failure it wraps, for step 6. */
|
|
172
|
+
function failed(request: ResolveRequest, tail: string, cause: unknown): YaagError {
|
|
173
|
+
return new YaagError(
|
|
174
|
+
"CATALOG_ENTRY_UNRESOLVABLE",
|
|
175
|
+
`${prefix(request)}: ${tail}`,
|
|
176
|
+
undefined,
|
|
177
|
+
undefined,
|
|
178
|
+
cause,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function targetTail(target: string, reason: string): string {
|
|
183
|
+
return `${target} did not resolve: ${reason}`;
|
|
184
|
+
}
|