@yaag/runtime 0.25.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 +2 -1
- package/src/agent/spawn-open.ts +24 -5
- package/src/agent/spawn-request.ts +18 -1
- package/src/agent/spawn.ts +21 -2
- 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/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 +2 -2
- package/src/control/index.ts +2 -0
- package/src/control/pause-drain.ts +81 -24
- package/src/events.ts +6 -0
- package/src/index.ts +11 -1
- package/src/model/index.ts +1 -1
- package/src/public-api.ts +1 -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 +18 -0
- 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,16 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
2
|
+
* The pause drain, in two grace modes.
|
|
3
|
+
*
|
|
4
|
+
* `bounded` is the external pause of ADR-0024: wrap-up steer, then abort at the
|
|
3
5
|
* deadline, then force-close through the Run's reap ladder.
|
|
4
6
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
7
|
+
* `natural` is the program pause of ADR-0022: the program asked its user a
|
|
8
|
+
* question, so nothing is cut short. The drain sends no wrap-up steer, sets no
|
|
9
|
+
* timer, and waits for quiescence. The honest consequence: one sibling Ask
|
|
10
|
+
* that never returns holds the drain open forever. ADR-0022 accepts this — a
|
|
11
|
+
* stop is the way out, and a stop always wins.
|
|
12
|
+
*
|
|
13
|
+
* The function takes structural inputs only — Agent handles, a grace, an
|
|
14
|
+
* admission closer and a stop promise — so both callers use it unchanged.
|
|
8
15
|
*
|
|
9
16
|
* The drain deliberately does not trip `AskLimit`, so an externally paused Ask
|
|
10
17
|
* never misreports `ASK_LIMIT`. A soft budget that trips at the same moment
|
|
11
18
|
* simply sends its own steer first; both paths converge on the same reap ladder.
|
|
12
19
|
*/
|
|
13
20
|
|
|
21
|
+
/** How one Ask left flight. It never rejects; a failed Ask carries its error. */
|
|
22
|
+
export interface AskSettled {
|
|
23
|
+
/** What the Ask rejected with, or absent when it resolved. */
|
|
24
|
+
readonly error?: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
14
27
|
/** Controls of one Ask in flight, as the drain sees them; a Handle never exposes these. */
|
|
15
28
|
export interface AskInFlight {
|
|
16
29
|
readonly agent: string;
|
|
@@ -23,7 +36,20 @@ export interface AskInFlight {
|
|
|
23
36
|
/** Aborts the turn. Never throws, and the drain never waits for its answer. */
|
|
24
37
|
abort(): Promise<boolean>;
|
|
25
38
|
/** Resolves when the Ask leaves flight, whatever its outcome. Never rejects. */
|
|
26
|
-
readonly settled: Promise<
|
|
39
|
+
readonly settled: Promise<AskSettled>;
|
|
40
|
+
/**
|
|
41
|
+
* The turn is parked on `request_user_input` (ADR-0023). The drain never
|
|
42
|
+
* waits for it, never steers it, never aborts it, and never names it cut
|
|
43
|
+
* short.
|
|
44
|
+
*/
|
|
45
|
+
readonly parked?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Resolves when this Ask parks, also after the drain read its wait set.
|
|
48
|
+
* ADR-0023 ends the drain at quiescence, where every Ask has settled **or**
|
|
49
|
+
* parked, so an Ask that parks later must leave the wait the same way a
|
|
50
|
+
* settled one does.
|
|
51
|
+
*/
|
|
52
|
+
readonly parkedSignal?: Promise<void>;
|
|
27
53
|
}
|
|
28
54
|
|
|
29
55
|
/** What the drain needs from one Agent; `Agent` satisfies it structurally. */
|
|
@@ -32,11 +58,16 @@ export interface DrainableAgent {
|
|
|
32
58
|
readonly askInFlight: AskInFlight | null;
|
|
33
59
|
}
|
|
34
60
|
|
|
61
|
+
/** How long the drain waits, and whether it steers at all. */
|
|
62
|
+
export type PauseGrace =
|
|
63
|
+
| { readonly kind: "bounded"; readonly deadlineMs: number }
|
|
64
|
+
| { readonly kind: "natural" };
|
|
65
|
+
|
|
35
66
|
export interface PauseDrainOptions {
|
|
36
67
|
/** Live reference to the Run's Agent list; read at drain start. */
|
|
37
68
|
readonly agents: readonly DrainableAgent[];
|
|
38
|
-
/** Wall-clock grace before the abort (ADR-0024). */
|
|
39
|
-
readonly
|
|
69
|
+
/** Wall-clock grace before the abort (ADR-0024), or the natural wait (ADR-0022). */
|
|
70
|
+
readonly grace: PauseGrace;
|
|
40
71
|
/** Closes Ask and spawn admission before the first steer. */
|
|
41
72
|
readonly closeAdmission: () => void;
|
|
42
73
|
/** A stop request; it skips the remaining grace and takes the outcome. */
|
|
@@ -45,7 +76,12 @@ export interface PauseDrainOptions {
|
|
|
45
76
|
|
|
46
77
|
/** How one drain ended: paused, naming every Ask it cut short, or overridden by a stop. */
|
|
47
78
|
export type PauseDrainResult =
|
|
48
|
-
| {
|
|
79
|
+
| {
|
|
80
|
+
readonly kind: "paused";
|
|
81
|
+
readonly cutShort: readonly string[];
|
|
82
|
+
/** One line per Ask that rejected during the drain; never an outcome. */
|
|
83
|
+
readonly warnings: readonly string[];
|
|
84
|
+
}
|
|
49
85
|
| { readonly kind: "stopped" };
|
|
50
86
|
|
|
51
87
|
/**
|
|
@@ -56,19 +92,35 @@ export type PauseDrainResult =
|
|
|
56
92
|
*/
|
|
57
93
|
export async function drainForPause(options: PauseDrainOptions): Promise<PauseDrainResult> {
|
|
58
94
|
options.closeAdmission();
|
|
59
|
-
const inFlight = options.agents
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
95
|
+
const inFlight = waitable(options.agents);
|
|
96
|
+
if (inFlight.length === 0) return { kind: "paused", cutShort: [], warnings: [] };
|
|
97
|
+
const warnings: string[] = [];
|
|
98
|
+
for (const ask of inFlight) {
|
|
99
|
+
void ask.settled.then((settled) => {
|
|
100
|
+
if (settled.error !== undefined) warnings.push(warningLine(ask.agent, settled.error));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
63
103
|
// The grace starts before the first steer, so an Agent that never answers a
|
|
64
104
|
// command cannot hold the drain open past the deadline, and a stop always
|
|
65
105
|
// lands. A refused steer is ignored on purpose: the deadline bounds it too.
|
|
66
106
|
const grace = raceGrace(inFlight, options);
|
|
67
|
-
for (const ask of inFlight) void ask.wrapUp();
|
|
107
|
+
if (options.grace.kind === "bounded") for (const ask of inFlight) void ask.wrapUp();
|
|
68
108
|
const outcome = await grace;
|
|
69
109
|
if (outcome === "stopped") return { kind: "stopped" };
|
|
70
|
-
if (outcome === "settled") return { kind: "paused", cutShort: [] };
|
|
71
|
-
return { kind: "paused", cutShort: abortRemaining(options.agents) };
|
|
110
|
+
if (outcome === "settled") return { kind: "paused", cutShort: [], warnings };
|
|
111
|
+
return { kind: "paused", cutShort: abortRemaining(options.agents), warnings };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Every Ask the drain waits for: in flight, and not parked on a user question. */
|
|
115
|
+
function waitable(agents: readonly DrainableAgent[]): readonly AskInFlight[] {
|
|
116
|
+
return agents
|
|
117
|
+
.map((agent) => agent.askInFlight)
|
|
118
|
+
.filter((ask): ask is AskInFlight => ask !== null && ask.parked !== true);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function warningLine(agent: string, error: unknown): string {
|
|
122
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
123
|
+
return `${agent}: Ask rejected during the pause drain: ${message}`;
|
|
72
124
|
}
|
|
73
125
|
|
|
74
126
|
type GraceOutcome = "settled" | "deadline" | "stopped";
|
|
@@ -79,13 +131,20 @@ function raceGrace(
|
|
|
79
131
|
options: PauseDrainOptions,
|
|
80
132
|
): Promise<GraceOutcome> {
|
|
81
133
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
134
|
+
// A parked Ask counts as quiescent: its own promise settles only at the reap,
|
|
135
|
+
// and the natural grace has no deadline that could end the wait (ADR-0023).
|
|
136
|
+
const quiet = inFlight.map((ask) =>
|
|
137
|
+
ask.parkedSignal === undefined
|
|
138
|
+
? ask.settled
|
|
139
|
+
: Promise.race([ask.settled, ask.parkedSignal.then(() => ({}) as AskSettled)]),
|
|
87
140
|
);
|
|
141
|
+
const settled = Promise.all(quiet).then<GraceOutcome>(() => "settled");
|
|
88
142
|
const stopped = options.stopped.then<GraceOutcome>(() => "stopped");
|
|
143
|
+
const grace = options.grace;
|
|
144
|
+
if (grace.kind === "natural") return Promise.race([settled, stopped]);
|
|
145
|
+
const deadline = new Promise<GraceOutcome>((resolve) => {
|
|
146
|
+
timer = setTimeout(() => resolve("deadline"), grace.deadlineMs);
|
|
147
|
+
});
|
|
89
148
|
return Promise.race([settled, deadline, stopped]).finally(() => {
|
|
90
149
|
clearTimeout(timer);
|
|
91
150
|
});
|
|
@@ -94,12 +153,10 @@ function raceGrace(
|
|
|
94
153
|
/**
|
|
95
154
|
* Aborts every Ask still in flight and names its Agent as cut short. The
|
|
96
155
|
* answers are deliberately not awaited: an Agent that swallows the abort must
|
|
97
|
-
* not hold the Run away from its reap ladder.
|
|
156
|
+
* not hold the Run away from its reap ladder. A parked Ask is exempt.
|
|
98
157
|
*/
|
|
99
158
|
function abortRemaining(agents: readonly DrainableAgent[]): readonly string[] {
|
|
100
|
-
const remaining = agents
|
|
101
|
-
.map((agent) => agent.askInFlight)
|
|
102
|
-
.filter((ask): ask is AskInFlight => ask !== null);
|
|
159
|
+
const remaining = waitable(agents);
|
|
103
160
|
for (const ask of remaining) void ask.abort();
|
|
104
161
|
return remaining.map((ask) => ask.agent);
|
|
105
162
|
}
|
package/src/events.ts
CHANGED
|
@@ -261,6 +261,12 @@ export type LifecycleEventBody =
|
|
|
261
261
|
* failed. Carries the publication error text. Absent on every other path.
|
|
262
262
|
*/
|
|
263
263
|
readonly checkpointLost?: string;
|
|
264
|
+
/**
|
|
265
|
+
* What went wrong beside the outcome: a sibling Ask that rejected during
|
|
266
|
+
* a pause drain, and (ticket 04) a summarizer failure. It never changes
|
|
267
|
+
* `outcome`. Absent when the Run has nothing to warn about.
|
|
268
|
+
*/
|
|
269
|
+
readonly warnings?: readonly string[];
|
|
264
270
|
/**
|
|
265
271
|
* Path of the Checkpoint this Run published, present only when the Run
|
|
266
272
|
* paused or stopped and publication succeeded (ADR-0054). The Reattach
|
package/src/index.ts
CHANGED
|
@@ -165,12 +165,22 @@ export {
|
|
|
165
165
|
} from "./profile/index.ts";
|
|
166
166
|
export { prompt, promptGist } from "./prompt/index.ts";
|
|
167
167
|
export type {
|
|
168
|
+
AskUserOptions,
|
|
168
169
|
OrchestrationProgram,
|
|
169
170
|
ProgramDefinition,
|
|
171
|
+
Question,
|
|
170
172
|
RunContext,
|
|
171
173
|
RunOptions,
|
|
174
|
+
RunResult,
|
|
175
|
+
} from "./run/index.ts";
|
|
176
|
+
export {
|
|
177
|
+
defineRun,
|
|
178
|
+
executeRun,
|
|
179
|
+
isOrchestrationProgram,
|
|
180
|
+
isPauseSignal,
|
|
181
|
+
programDefinition,
|
|
182
|
+
RunPauseSignal,
|
|
172
183
|
} from "./run/index.ts";
|
|
173
|
-
export { defineRun, executeRun, isOrchestrationProgram, programDefinition } from "./run/index.ts";
|
|
174
184
|
export type {
|
|
175
185
|
AgentInfo,
|
|
176
186
|
AgentState,
|
package/src/model/index.ts
CHANGED
package/src/public-api.ts
CHANGED
|
@@ -59,6 +59,7 @@ export { isProfiledDefinition, useProfile } from "./profile/use-profile.ts";
|
|
|
59
59
|
export { prompt } from "./prompt/prompt.ts";
|
|
60
60
|
export type { OrchestrationProgram, ProgramDefinition } from "./run/define-run.ts";
|
|
61
61
|
export { defineRun } from "./run/define-run.ts";
|
|
62
|
+
export type { AskUserOptions, Question } from "./run/questions.ts";
|
|
62
63
|
export type { RunContext } from "./run/run-context.ts";
|
|
63
64
|
export type { YaagSystemPromptOptions } from "./system-prompt/agent-system-prompt.ts";
|
|
64
65
|
export { yaagSystemPrompt } from "./system-prompt/agent-system-prompt.ts";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public surface of the `question-summary/` module: the fork summarizer that
|
|
3
|
+
* fills `summary` on an Agent Question (ADR-0022). It is named for the glossary
|
|
4
|
+
* term, and stays apart from `summary/`, which owns the Run Summary fold.
|
|
5
|
+
* Files inside this directory import each other directly.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
prepareSessionCopy,
|
|
10
|
+
type SessionCopy,
|
|
11
|
+
type SessionCopyRequest,
|
|
12
|
+
SYNTHETIC_TOOL_RESULT_TEXT,
|
|
13
|
+
} from "./session-copy.ts";
|
|
14
|
+
export {
|
|
15
|
+
type InternalOpen,
|
|
16
|
+
type ParkedAgent,
|
|
17
|
+
type QuestionSummaryResult,
|
|
18
|
+
SUMMARIZER_PROMPT,
|
|
19
|
+
type SummarizeQuestionsRequest,
|
|
20
|
+
summarizeQuestions,
|
|
21
|
+
} from "./summarize-question.ts";
|
|
22
|
+
export { summarizes } from "./summary-policy.ts";
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session copy the fork summarizer reads (ADR-0022).
|
|
3
|
+
*
|
|
4
|
+
* The parked Agent is incomplete, so it cannot be forked: yaag copies its pi
|
|
5
|
+
* session file instead, and closes the pending `request_user_input` call with a
|
|
6
|
+
* synthetic `toolResult`. pi refuses to continue a session whose last assistant
|
|
7
|
+
* message has an unanswered tool call, and the copy keeps the parked Agent's
|
|
8
|
+
* own file untouched.
|
|
9
|
+
*/
|
|
10
|
+
import { copyFile, readFile, rm, writeFile } from "node:fs/promises";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What the summarizer session reads in place of the human's answer. It states
|
|
16
|
+
* three facts: no answer arrived, this session is a copy, and the task is over.
|
|
17
|
+
*/
|
|
18
|
+
export const SYNTHETIC_TOOL_RESULT_TEXT =
|
|
19
|
+
"The human has not answered yet. This session is a copy of your session, made " +
|
|
20
|
+
"only to summarize your question. Do not continue your task.";
|
|
21
|
+
|
|
22
|
+
/** One prepared copy: where it is, and how to remove it again. */
|
|
23
|
+
export interface SessionCopy {
|
|
24
|
+
/** Absolute path of the copy; hand it to `pi --session`. */
|
|
25
|
+
readonly path: string;
|
|
26
|
+
/** Removes the copy. Best effort: it never throws. */
|
|
27
|
+
remove(): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What one copy needs: the source session and the call to close. */
|
|
31
|
+
export interface SessionCopyRequest {
|
|
32
|
+
readonly sessionFile: string;
|
|
33
|
+
readonly toolCallId: string;
|
|
34
|
+
/** Where the copy goes; the OS temp directory by default. */
|
|
35
|
+
readonly directory?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Copies one pi session and appends the synthetic `toolResult`.
|
|
40
|
+
*
|
|
41
|
+
* Rejects when the source cannot be read, when its last
|
|
42
|
+
* line is not a complete JSON entry, or when no entry carries the parked tool
|
|
43
|
+
* call: a dangling result would corrupt the copy, and the summary is
|
|
44
|
+
* best-effort, so a refusal here is the correct outcome.
|
|
45
|
+
*/
|
|
46
|
+
export async function prepareSessionCopy(request: SessionCopyRequest): Promise<SessionCopy> {
|
|
47
|
+
const text = await readSession(request.sessionFile);
|
|
48
|
+
const entries = parseEntries(text, request.sessionFile);
|
|
49
|
+
if (!carriesToolCall(entries, request.toolCallId)) {
|
|
50
|
+
throw new Error(`session ${request.sessionFile} has no tool call ${request.toolCallId}`);
|
|
51
|
+
}
|
|
52
|
+
// The appended entry hangs below the current leaf. A leaf with no string id
|
|
53
|
+
// would detach it from pi's session tree, which is the very corruption the
|
|
54
|
+
// refusals above exist to prevent, so it refuses too.
|
|
55
|
+
const leaf = entries.at(-1);
|
|
56
|
+
if (typeof leaf?.id !== "string") {
|
|
57
|
+
throw new Error(`session ${request.sessionFile} ends with an entry that has no id`);
|
|
58
|
+
}
|
|
59
|
+
const parentId: string = leaf.id;
|
|
60
|
+
const path = join(
|
|
61
|
+
request.directory ?? tmpdir(),
|
|
62
|
+
`yaag-summary-${Date.now()}-${Math.random().toString(16).slice(2)}.jsonl`,
|
|
63
|
+
);
|
|
64
|
+
const copy: SessionCopy = {
|
|
65
|
+
path,
|
|
66
|
+
remove: async (): Promise<void> => {
|
|
67
|
+
try {
|
|
68
|
+
await rm(path, { force: true });
|
|
69
|
+
} catch {
|
|
70
|
+
// best effort: a leftover temp file must never fail a Run
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
await copyFile(request.sessionFile, path);
|
|
76
|
+
const line = JSON.stringify(syntheticEntry({ toolCallId: request.toolCallId, parentId }));
|
|
77
|
+
await writeFile(path, `${text.endsWith("\n") ? "" : "\n"}${line}\n`, { flag: "a" });
|
|
78
|
+
} catch (error) {
|
|
79
|
+
await copy.remove();
|
|
80
|
+
throw new Error(`cannot prepare a session copy: ${String(error)}`);
|
|
81
|
+
}
|
|
82
|
+
return copy;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One parsed session entry; only the fields this module reads are named. */
|
|
86
|
+
interface SessionEntry {
|
|
87
|
+
readonly id?: unknown;
|
|
88
|
+
readonly message?: unknown;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** One assistant tool call, as pi writes it into a session entry. */
|
|
92
|
+
interface ToolCallPart {
|
|
93
|
+
readonly type?: unknown;
|
|
94
|
+
readonly id?: unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
98
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function readSession(path: string): Promise<string> {
|
|
102
|
+
try {
|
|
103
|
+
return await readFile(path, "utf8");
|
|
104
|
+
} catch (error) {
|
|
105
|
+
throw new Error(`cannot read session ${path}: ${String(error)}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Every non-empty line, parsed. A truncated tail line fails the whole copy. */
|
|
110
|
+
function parseEntries(text: string, path: string): readonly SessionEntry[] {
|
|
111
|
+
const lines = text.split("\n").filter((line) => line.trim().length > 0);
|
|
112
|
+
return lines.map((line, index) => {
|
|
113
|
+
let parsed: unknown;
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(line);
|
|
116
|
+
} catch {
|
|
117
|
+
throw new Error(`session ${path} line ${index + 1} is not valid JSON`);
|
|
118
|
+
}
|
|
119
|
+
// Checked, never cast blind: a JSONL line is untrusted input, and a scalar
|
|
120
|
+
// or an array here would read as an entry with no id and no message.
|
|
121
|
+
if (!isRecord(parsed)) {
|
|
122
|
+
throw new Error(`session ${path} line ${index + 1} is not a session entry`);
|
|
123
|
+
}
|
|
124
|
+
return parsed;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* True when an entry holds the parked call as a real `toolCall` content part.
|
|
130
|
+
*
|
|
131
|
+
* Structural, never a substring scan of the serialized entry: the same id can
|
|
132
|
+
* appear inside message text, and this predicate carries the whole safety
|
|
133
|
+
* argument of the module — a false positive appends a dangling result.
|
|
134
|
+
*/
|
|
135
|
+
function carriesToolCall(entries: readonly SessionEntry[], toolCallId: string): boolean {
|
|
136
|
+
return entries.some((entry) => {
|
|
137
|
+
const message = entry.message;
|
|
138
|
+
if (!isRecord(message)) return false;
|
|
139
|
+
const content = message.content;
|
|
140
|
+
if (!Array.isArray(content)) return false;
|
|
141
|
+
return content.some((part: ToolCallPart) => part.type === "toolCall" && part.id === toolCallId);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function syntheticEntry(options: {
|
|
146
|
+
readonly toolCallId: string;
|
|
147
|
+
readonly parentId?: string;
|
|
148
|
+
}): unknown {
|
|
149
|
+
const now = new Date();
|
|
150
|
+
return {
|
|
151
|
+
type: "message",
|
|
152
|
+
id: randomEntryId(),
|
|
153
|
+
...(options.parentId === undefined ? {} : { parentId: options.parentId }),
|
|
154
|
+
timestamp: now.toISOString(),
|
|
155
|
+
message: {
|
|
156
|
+
role: "toolResult",
|
|
157
|
+
toolCallId: options.toolCallId,
|
|
158
|
+
toolName: "request_user_input",
|
|
159
|
+
content: [{ type: "text", text: SYNTHETIC_TOOL_RESULT_TEXT }],
|
|
160
|
+
isError: false,
|
|
161
|
+
timestamp: now.getTime(),
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** pi's entry ids are 8 hex characters. */
|
|
167
|
+
function randomEntryId(): string {
|
|
168
|
+
return Math.random().toString(16).slice(2, 10).padEnd(8, "0");
|
|
169
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fork summarizer (ADR-0022): it writes the Question Summary of every
|
|
3
|
+
* eligible Agent Question, after quiescence and after every Agent is reaped,
|
|
4
|
+
* and before the Checkpoint is published.
|
|
5
|
+
*
|
|
6
|
+
* Every step is best-effort. A failure produces one warning and no summary; it
|
|
7
|
+
* never fails the pause, because a paused Run must always publish.
|
|
8
|
+
*/
|
|
9
|
+
import type { SpawnGate } from "../agent/index.ts";
|
|
10
|
+
import type { QuestionSummaryConfig } from "../config/index.ts";
|
|
11
|
+
import type { AgentQuestions } from "../run/index.ts";
|
|
12
|
+
import { prepareSessionCopy } from "./session-copy.ts";
|
|
13
|
+
import { summarizes } from "./summary-policy.ts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The one Ask the summarizer sends. It states the audience, the length, and the
|
|
17
|
+
* three things the answer must not contain.
|
|
18
|
+
*/
|
|
19
|
+
export const SUMMARIZER_PROMPT =
|
|
20
|
+
"Summarize why you ask this question, for the human who answers it. Write 1 to " +
|
|
21
|
+
"3 sentences. Write no preamble, no greeting, and no question.";
|
|
22
|
+
|
|
23
|
+
/** What one summarizer Agent needs from the parked Agent it copies. */
|
|
24
|
+
export interface ParkedAgent {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
/** The concrete resolved model, so the summarizer never re-runs a fallback list. */
|
|
27
|
+
readonly model: string;
|
|
28
|
+
readonly sessionFile: string | undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The Run's internal open path. It is `SpawnGate.openInternal` itself, so this
|
|
33
|
+
* request shape cannot drift from the one the open path accepts.
|
|
34
|
+
*/
|
|
35
|
+
export type InternalOpen = SpawnGate["openInternal"];
|
|
36
|
+
|
|
37
|
+
export interface SummarizeQuestionsRequest {
|
|
38
|
+
readonly questions: AgentQuestions;
|
|
39
|
+
/** The Agents of this Run, already reaped; looked up by name. */
|
|
40
|
+
readonly agents: readonly ParkedAgent[];
|
|
41
|
+
readonly policy: QuestionSummaryConfig;
|
|
42
|
+
readonly openAgent: InternalOpen;
|
|
43
|
+
/**
|
|
44
|
+
* True when the Run replays a Cassette. The recorded summaries are already in
|
|
45
|
+
* the run block, and the temp session copy is long gone, so the summarizer is
|
|
46
|
+
* skipped whole (ADR-0022).
|
|
47
|
+
*/
|
|
48
|
+
readonly replaying?: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface QuestionSummaryResult {
|
|
52
|
+
/** One line for each failure, naming the Agent and the reason. */
|
|
53
|
+
readonly warnings: readonly string[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Summarizes every eligible Question, in order and one at a time.
|
|
58
|
+
*
|
|
59
|
+
* Sequential on purpose: a pause carries few questions, and a parallel fan-out
|
|
60
|
+
* of pi processes at pause time is a resource surprise.
|
|
61
|
+
*/
|
|
62
|
+
export async function summarizeQuestions(
|
|
63
|
+
request: SummarizeQuestionsRequest,
|
|
64
|
+
): Promise<QuestionSummaryResult> {
|
|
65
|
+
if (request.replaying === true) return { warnings: [] };
|
|
66
|
+
const warnings: string[] = [];
|
|
67
|
+
for (const question of request.questions.questions) {
|
|
68
|
+
if (!summarizes(request.policy.policy, question)) continue;
|
|
69
|
+
const parked = request.questions.parked.get(question.id);
|
|
70
|
+
const agent = request.agents.find((one) => one.name === question.agent);
|
|
71
|
+
// Requirement 6 is "any failure warns": a Question with no parked call, or
|
|
72
|
+
// an Agent this Run does not hold, is a failure like every other one.
|
|
73
|
+
if (parked === undefined || agent === undefined) {
|
|
74
|
+
warnings.push(`${question.agent}: question summary failed: the run holds no such agent`);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
const summary = await summarizeOne({ parked: agent, toolCallId: parked.toolCallId, request });
|
|
79
|
+
request.questions.setSummary(question.id, summary);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
warnings.push(`${agent.name}: question summary failed: ${reason(error)}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { warnings };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface OneRequest {
|
|
88
|
+
readonly parked: ParkedAgent;
|
|
89
|
+
readonly toolCallId: string;
|
|
90
|
+
readonly request: SummarizeQuestionsRequest;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Copies, spawns, asks, reaps, and deletes. The copy always goes away. */
|
|
94
|
+
async function summarizeOne({ parked, toolCallId, request }: OneRequest): Promise<string> {
|
|
95
|
+
if (parked.sessionFile === undefined) throw new Error("the agent reported no session file");
|
|
96
|
+
const copy = await prepareSessionCopy({ sessionFile: parked.sessionFile, toolCallId });
|
|
97
|
+
try {
|
|
98
|
+
const handle = await request.openAgent({
|
|
99
|
+
spawnOptions: {
|
|
100
|
+
name: `${parked.name}.summary`,
|
|
101
|
+
// No tools and no worktree: this Agent reads its own context and
|
|
102
|
+
// answers. It stays a normal Agent in lifecycle, events, and cost.
|
|
103
|
+
tools: [],
|
|
104
|
+
// The resolved model of the parked Agent by default, never its pattern.
|
|
105
|
+
model: request.policy.model ?? parked.model,
|
|
106
|
+
thinking: request.policy.thinking,
|
|
107
|
+
},
|
|
108
|
+
// The Parent Link is the parked Agent itself, so the tree shows where the
|
|
109
|
+
// summary came from.
|
|
110
|
+
parent: parked,
|
|
111
|
+
askDefaults: undefined,
|
|
112
|
+
definitionName: undefined,
|
|
113
|
+
sessionFile: copy.path,
|
|
114
|
+
});
|
|
115
|
+
try {
|
|
116
|
+
const text = (await handle.ask(SUMMARIZER_PROMPT)).trim();
|
|
117
|
+
if (text.length === 0) throw new Error("the summarizer answered with no text");
|
|
118
|
+
return text;
|
|
119
|
+
} finally {
|
|
120
|
+
await handle.close().catch(() => {});
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
await copy.remove();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function reason(error: unknown): string {
|
|
128
|
+
return error instanceof Error ? error.message : String(error);
|
|
129
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When the fork summarizer runs for one Question (ADR-0022). Pure: the decision
|
|
3
|
+
* table lives apart from the orchestration that acts on it.
|
|
4
|
+
*/
|
|
5
|
+
import type { QuestionSummaryPolicy } from "../config/index.ts";
|
|
6
|
+
import type { Question } from "../run/index.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* True when this Question earns a Question Summary.
|
|
10
|
+
*
|
|
11
|
+
* A program Question never does: it has no Agent, so there is no session to
|
|
12
|
+
* copy and no reasoning to summarize. `when-missing`, the default, runs only
|
|
13
|
+
* when the Agent supplied no `context` of its own.
|
|
14
|
+
*/
|
|
15
|
+
export function summarizes(policy: QuestionSummaryPolicy, question: Question): boolean {
|
|
16
|
+
if (question.agent === undefined) return false;
|
|
17
|
+
switch (policy) {
|
|
18
|
+
case "never":
|
|
19
|
+
return false;
|
|
20
|
+
case "always":
|
|
21
|
+
return true;
|
|
22
|
+
case "when-missing":
|
|
23
|
+
return (question.context ?? "").trim().length === 0;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Run-scoped sink of the questions an Agent asks (ADR-0023).
|
|
3
|
+
*
|
|
4
|
+
* It stays apart from `pause-questions.ts`, which owns the questions the
|
|
5
|
+
* program asks: a question raised from an Ask's frame handler must never throw,
|
|
6
|
+
* so this registry refuses nothing and repeats are inert.
|
|
7
|
+
*/
|
|
8
|
+
import { agentQuestionId } from "./question-id.ts";
|
|
9
|
+
import type { Question } from "./questions.ts";
|
|
10
|
+
|
|
11
|
+
/** One parked question, as the Ask that observed the frame reports it. */
|
|
12
|
+
export interface AgentQuestionRequest {
|
|
13
|
+
readonly agent: string;
|
|
14
|
+
readonly toolCallId: string;
|
|
15
|
+
readonly question: string;
|
|
16
|
+
readonly context?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The Agent questions of one Run, and the signal the Run races. */
|
|
20
|
+
export interface AgentQuestions {
|
|
21
|
+
/**
|
|
22
|
+
* Records one parked question, raises the Run's pause, and returns the
|
|
23
|
+
* durable id of the Question. Idempotent per id.
|
|
24
|
+
*/
|
|
25
|
+
raise(request: AgentQuestionRequest): string;
|
|
26
|
+
readonly questions: readonly Question[];
|
|
27
|
+
/**
|
|
28
|
+
* The parked calls, keyed by Question id. The fork summarizer reads the tool
|
|
29
|
+
* call from here rather than parsing it back out of the id (ADR-0022).
|
|
30
|
+
*/
|
|
31
|
+
readonly parked: ReadonlyMap<string, AgentQuestionRequest>;
|
|
32
|
+
/**
|
|
33
|
+
* Writes one Question Summary, before the Checkpoint is published, so the
|
|
34
|
+
* summary is durable in the Cassette (ADR-0022). An unknown id is inert.
|
|
35
|
+
*/
|
|
36
|
+
setSummary(id: string, summary: string): void;
|
|
37
|
+
/** Resolves at the first raised question; the Run races it and drains naturally. */
|
|
38
|
+
readonly raised: Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Builds the Agent question registry of one Run. */
|
|
42
|
+
export function createAgentQuestions(): AgentQuestions {
|
|
43
|
+
const byId = new Map<string, Question>();
|
|
44
|
+
const parked = new Map<string, AgentQuestionRequest>();
|
|
45
|
+
let signal: () => void = () => {};
|
|
46
|
+
const raised = new Promise<void>((resolve) => {
|
|
47
|
+
signal = resolve;
|
|
48
|
+
});
|
|
49
|
+
return {
|
|
50
|
+
raise(request: AgentQuestionRequest): string {
|
|
51
|
+
// The ADR's key: the Agent name and the tool call id of the parked call.
|
|
52
|
+
const id = agentQuestionId(request.agent, request.toolCallId);
|
|
53
|
+
if (byId.has(id)) return id;
|
|
54
|
+
parked.set(id, request);
|
|
55
|
+
byId.set(id, {
|
|
56
|
+
id,
|
|
57
|
+
agent: request.agent,
|
|
58
|
+
question: request.question,
|
|
59
|
+
...(request.context === undefined ? {} : { context: request.context }),
|
|
60
|
+
});
|
|
61
|
+
signal();
|
|
62
|
+
return id;
|
|
63
|
+
},
|
|
64
|
+
get questions(): readonly Question[] {
|
|
65
|
+
return [...byId.values()];
|
|
66
|
+
},
|
|
67
|
+
parked,
|
|
68
|
+
setSummary(id: string, summary: string): void {
|
|
69
|
+
const question = byId.get(id);
|
|
70
|
+
if (question === undefined) return;
|
|
71
|
+
byId.set(id, { ...question, summary });
|
|
72
|
+
},
|
|
73
|
+
raised,
|
|
74
|
+
};
|
|
75
|
+
}
|