@yaag/runtime 0.25.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -3
- package/src/agent/agent.ts +75 -23
- package/src/agent/ask-user-capability.ts +36 -0
- package/src/agent/fork.ts +40 -12
- package/src/agent/host-fork.ts +85 -0
- package/src/agent/index.ts +2 -1
- package/src/agent/spawn-definition-request.ts +38 -3
- package/src/agent/spawn-open.ts +59 -100
- package/src/agent/spawn-plan.ts +114 -0
- package/src/agent/spawn-request.ts +34 -3
- package/src/agent/spawn.ts +41 -5
- package/src/ask/ask-exchange-options.ts +8 -6
- package/src/ask/ask-exchange.ts +102 -97
- package/src/ask/ask-guard.ts +207 -0
- package/src/ask/ask-settlement.ts +8 -0
- package/src/ask/ask-timing.ts +12 -0
- package/src/ask/idle-watch.ts +12 -2
- package/src/ask/index.ts +1 -0
- package/src/ask/stall-watchdog.ts +13 -3
- package/src/ask-contract/ask-limit.ts +24 -6
- package/src/ask-contract/index.ts +8 -0
- package/src/ask-contract/request-user-input-extension.ts +105 -0
- package/src/ask-contract/request-user-input.ts +58 -0
- package/src/cassette/cassette-loader.ts +56 -18
- package/src/cassette/cassette-schema.ts +37 -1
- package/src/cassette/cassette.ts +58 -32
- package/src/cassette/checkpoint.ts +306 -0
- package/src/cassette/index.ts +25 -7
- package/src/cassette/parked-asks.ts +38 -0
- package/src/cassette/replay-divergence.ts +7 -97
- package/src/cassette/resume-identity.ts +5 -1
- package/src/cassette/resume-preconditions.ts +24 -0
- package/src/cassette/resume-transport.ts +112 -13
- package/src/cassette/run-identity.ts +109 -0
- package/src/cassette/session-answer.ts +100 -0
- package/src/cassette/spawn-identity.ts +318 -0
- package/src/catalog/registry-reader.ts +1 -1
- package/src/config/config-schema.ts +33 -0
- package/src/config/effective-config.ts +53 -0
- package/src/config/index.ts +4 -0
- package/src/contract/agent-policy.ts +9 -0
- package/src/contract/error-codes.ts +3 -2
- package/src/contract/index.ts +1 -0
- package/src/contract/spawn-options.ts +33 -2
- package/src/control/index.ts +2 -0
- package/src/control/pause-drain.ts +81 -24
- package/src/error-factories.ts +8 -0
- package/src/events.ts +10 -2
- package/src/index.ts +15 -1
- package/src/model/index.ts +1 -1
- package/src/pi-session/append-tool-result.ts +165 -0
- package/src/pi-session/index.ts +30 -0
- package/src/pi-session/pi-session-error.ts +34 -0
- package/src/pi-session/session-copy.ts +113 -0
- package/src/pi-session/session-entries.ts +130 -0
- package/src/public-api.ts +1 -0
- package/src/question-summary/index.ts +18 -0
- package/src/question-summary/summarize-question.ts +129 -0
- package/src/question-summary/summary-policy.ts +28 -0
- package/src/run/agent-questions.ts +157 -0
- package/src/run/answers.ts +91 -0
- package/src/run/host-session.ts +233 -0
- package/src/run/index.ts +12 -0
- package/src/run/pause-questions.ts +98 -0
- package/src/run/pause-signal.ts +32 -0
- package/src/run/question-id.ts +18 -0
- package/src/run/questions.ts +31 -0
- package/src/run/run-context.ts +21 -0
- package/src/run/run-result.ts +21 -0
- package/src/run/run-settlement.ts +36 -4
- package/src/run/run.ts +248 -139
- package/src/system-prompt/agent-system-prompt.ts +1 -1
- package/src/transport/live-transport.ts +19 -0
- package/src/transport/pi-state.ts +31 -5
- package/src/transport/tool-probe.ts +4 -0
- package/src/transport/transport.ts +31 -1
- package/src/types.ts +1 -0
- package/src/cassette/checkpoint-flush.ts +0 -101
- package/src/cassette/run-checkpoint.ts +0 -223
|
@@ -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/error-factories.ts
CHANGED
|
@@ -68,3 +68,11 @@ export function modelResolutionError(
|
|
|
68
68
|
{ modelErrors: errors },
|
|
69
69
|
);
|
|
70
70
|
}
|
|
71
|
+
|
|
72
|
+
/** The HOST_SESSION_UNUSABLE refusal: it names the reason and the file. */
|
|
73
|
+
export function hostSessionUnusableError(sessionFile: string, reason: string): YaagError {
|
|
74
|
+
return new YaagError(
|
|
75
|
+
"HOST_SESSION_UNUSABLE",
|
|
76
|
+
`host session ${sessionFile} is unusable: ${reason}`,
|
|
77
|
+
);
|
|
78
|
+
}
|
package/src/events.ts
CHANGED
|
@@ -22,9 +22,11 @@ export type RunOutcome = "completed" | "failed" | "stopped" | "paused" | "interr
|
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* How an Agent came to be. An absent value on an event means "spawn"; "fork"
|
|
25
|
-
* marks an Agent created from a copy of another Agent's session (ADR-0044)
|
|
25
|
+
* marks an Agent created from a copy of another Agent's session (ADR-0044);
|
|
26
|
+
* "host-fork" marks one created from a copy of the Host Session's conversation.
|
|
27
|
+
* Every reader accepts all three.
|
|
26
28
|
*/
|
|
27
|
-
export type SpawnOrigin = "spawn" | "fork";
|
|
29
|
+
export type SpawnOrigin = "spawn" | "fork" | "host-fork";
|
|
28
30
|
|
|
29
31
|
/**
|
|
30
32
|
* Why a control request failed, or `BUSY` when a second Control Channel client
|
|
@@ -261,6 +263,12 @@ export type LifecycleEventBody =
|
|
|
261
263
|
* failed. Carries the publication error text. Absent on every other path.
|
|
262
264
|
*/
|
|
263
265
|
readonly checkpointLost?: string;
|
|
266
|
+
/**
|
|
267
|
+
* What went wrong beside the outcome: a sibling Ask that rejected during
|
|
268
|
+
* a pause drain, and (ticket 04) a summarizer failure. It never changes
|
|
269
|
+
* `outcome`. Absent when the Run has nothing to warn about.
|
|
270
|
+
*/
|
|
271
|
+
readonly warnings?: readonly string[];
|
|
264
272
|
/**
|
|
265
273
|
* Path of the Checkpoint this Run published, present only when the Run
|
|
266
274
|
* paused or stopped and publication succeeded (ADR-0054). The Reattach
|
package/src/index.ts
CHANGED
|
@@ -22,6 +22,7 @@ export {
|
|
|
22
22
|
loadCassette,
|
|
23
23
|
recordingTransport,
|
|
24
24
|
replayTransport,
|
|
25
|
+
resolveCheckpointDirectory,
|
|
25
26
|
resumeTransport,
|
|
26
27
|
} from "./cassette/index.ts";
|
|
27
28
|
export type {
|
|
@@ -80,7 +81,9 @@ export {
|
|
|
80
81
|
EMPTY_EFFECTIVE_CONFIG,
|
|
81
82
|
loadEffectiveConfig,
|
|
82
83
|
PROJECT_CONFIG_DIR,
|
|
84
|
+
projectConfigPath,
|
|
83
85
|
resolveGlobalConfigDirectory,
|
|
86
|
+
resolveGlobalConfigPath,
|
|
84
87
|
} from "./config/index.ts";
|
|
85
88
|
export type {
|
|
86
89
|
ControlCommand,
|
|
@@ -165,12 +168,22 @@ export {
|
|
|
165
168
|
} from "./profile/index.ts";
|
|
166
169
|
export { prompt, promptGist } from "./prompt/index.ts";
|
|
167
170
|
export type {
|
|
171
|
+
AskUserOptions,
|
|
168
172
|
OrchestrationProgram,
|
|
169
173
|
ProgramDefinition,
|
|
174
|
+
Question,
|
|
170
175
|
RunContext,
|
|
171
176
|
RunOptions,
|
|
177
|
+
RunResult,
|
|
178
|
+
} from "./run/index.ts";
|
|
179
|
+
export {
|
|
180
|
+
defineRun,
|
|
181
|
+
executeRun,
|
|
182
|
+
isOrchestrationProgram,
|
|
183
|
+
isPauseSignal,
|
|
184
|
+
programDefinition,
|
|
185
|
+
RunPauseSignal,
|
|
172
186
|
} from "./run/index.ts";
|
|
173
|
-
export { defineRun, executeRun, isOrchestrationProgram, programDefinition } from "./run/index.ts";
|
|
174
187
|
export type {
|
|
175
188
|
AgentInfo,
|
|
176
189
|
AgentState,
|
|
@@ -230,6 +243,7 @@ export type {
|
|
|
230
243
|
AskOptions,
|
|
231
244
|
ForkOptions,
|
|
232
245
|
Handle,
|
|
246
|
+
HostSource,
|
|
233
247
|
LiteralPromptText,
|
|
234
248
|
PromptAudience,
|
|
235
249
|
PromptText,
|
package/src/model/index.ts
CHANGED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one writer of a pi session file: the `toolResult` of a parked
|
|
3
|
+
* `request_user_input` call (ADR-0023).
|
|
4
|
+
*
|
|
5
|
+
* Two callers use it — the Question Summary's session copy, which closes the
|
|
6
|
+
* parked call with a synthetic text, and the resume's answer restoration,
|
|
7
|
+
* which writes the human's answer. It carries the three invariants both need:
|
|
8
|
+
*
|
|
9
|
+
* - **One parse policy.** It lives in `session-entries.ts` and is shared with
|
|
10
|
+
* the Host Session pre-flight, so no caller can be stricter than this writer.
|
|
11
|
+
* - **One parent rule.** The new entry parents on the entry that holds the
|
|
12
|
+
* `toolCall` part, as ADR-0023 states — never on the last entry of the file.
|
|
13
|
+
* When that entry has no string id, the parent is `null`.
|
|
14
|
+
* - **One id shape.** Eight hex characters, as pi writes.
|
|
15
|
+
*/
|
|
16
|
+
import { appendFile, copyFile, truncate } from "node:fs/promises";
|
|
17
|
+
import { REQUEST_USER_INPUT_TOOL_NAME } from "../ask-contract/index.ts";
|
|
18
|
+
import { PiSessionError } from "./pi-session-error.ts";
|
|
19
|
+
import {
|
|
20
|
+
contentParts,
|
|
21
|
+
findToolCall,
|
|
22
|
+
isRecord,
|
|
23
|
+
parseSession,
|
|
24
|
+
type SessionEntry,
|
|
25
|
+
} from "./session-entries.ts";
|
|
26
|
+
|
|
27
|
+
/** What one append needs: the session, the parked call, and the result text. */
|
|
28
|
+
export interface AppendToolResultRequest {
|
|
29
|
+
/** The session that is read; written only when `into` is absent. */
|
|
30
|
+
readonly sessionFile: string;
|
|
31
|
+
/** The tool call id of the parked `request_user_input` call. */
|
|
32
|
+
readonly toolCallId: string;
|
|
33
|
+
/** The tool result text: the human's answer, or a synthetic text. */
|
|
34
|
+
readonly text: string;
|
|
35
|
+
/**
|
|
36
|
+
* The tool name the result is recorded under; the parked `request_user_input`
|
|
37
|
+
* call by default. A caller that closes another call — the Host Fork closes
|
|
38
|
+
* the `yaag_run` call — gives the name it read from the holder entry's
|
|
39
|
+
* `toolCall` part. The name is never part of the same-or-refuse comparison,
|
|
40
|
+
* which stays text-only (ADR-0022).
|
|
41
|
+
*/
|
|
42
|
+
readonly toolName?: string;
|
|
43
|
+
/** Copy target. When given, `sessionFile` stays untouched. */
|
|
44
|
+
readonly into?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `appended` when the entry is new, `already-present` when the text was there. */
|
|
48
|
+
export type AppendToolResultOutcome = "appended" | "already-present";
|
|
49
|
+
|
|
50
|
+
export interface AppendToolResultResult {
|
|
51
|
+
readonly outcome: AppendToolResultOutcome;
|
|
52
|
+
/** The file the entry is in: `into` when given, else `sessionFile`. */
|
|
53
|
+
readonly path: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Appends the tool result of the parked call, and returns where it went.
|
|
58
|
+
*
|
|
59
|
+
* The same text already present is `already-present`, and nothing is written,
|
|
60
|
+
* so a retried resume changes nothing. A different text is a refusal: an
|
|
61
|
+
* answered question has one answer (ADR-0022). With `into`, the copy is made
|
|
62
|
+
* either way, because the summarizer needs a file to open.
|
|
63
|
+
*/
|
|
64
|
+
export async function appendToolResult(
|
|
65
|
+
request: AppendToolResultRequest,
|
|
66
|
+
): Promise<AppendToolResultResult> {
|
|
67
|
+
const path = request.into ?? request.sessionFile;
|
|
68
|
+
const text = await readSession(request.sessionFile);
|
|
69
|
+
const { entries, truncatedTailAtByte } = parseSession(text, request.sessionFile);
|
|
70
|
+
const holder = findToolCall(entries, request.toolCallId)?.entry;
|
|
71
|
+
if (holder === undefined) {
|
|
72
|
+
throw new PiSessionError(
|
|
73
|
+
"no-such-call",
|
|
74
|
+
`session ${request.sessionFile} has no tool call ${request.toolCallId}`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
const present = findResult(entries, request.toolCallId);
|
|
78
|
+
if (present !== undefined) {
|
|
79
|
+
// A result with no text part states no answer this one can equal, so it is
|
|
80
|
+
// a clash and never a match: a second result for one call is the dangling
|
|
81
|
+
// entry every refusal here exists to prevent.
|
|
82
|
+
if (present.text !== request.text) {
|
|
83
|
+
throw new PiSessionError(
|
|
84
|
+
"different-result",
|
|
85
|
+
`session ${request.sessionFile} already answers the tool call ` +
|
|
86
|
+
`${request.toolCallId} with a different text`,
|
|
87
|
+
present.text,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
if (request.into !== undefined) await copyFile(request.sessionFile, request.into);
|
|
91
|
+
return { outcome: "already-present", path };
|
|
92
|
+
}
|
|
93
|
+
const line = JSON.stringify(buildEntry(request, holder));
|
|
94
|
+
if (request.into !== undefined) await copyFile(request.sessionFile, request.into);
|
|
95
|
+
if (truncatedTailAtByte === undefined) {
|
|
96
|
+
await appendFile(path, `${text.endsWith("\n") ? "" : "\n"}${line}\n`);
|
|
97
|
+
} else {
|
|
98
|
+
// The half-written line goes, and the entry takes its place. Kept, it would
|
|
99
|
+
// sit mid-file on the next append, where the parse policy refuses it, and a
|
|
100
|
+
// retried resume would fail on the very crash this tolerance exists for.
|
|
101
|
+
//
|
|
102
|
+
// Truncate then append, never a rewrite of the whole file: this branch runs
|
|
103
|
+
// on a machine that just crashed mid-write, and a crash here must be able
|
|
104
|
+
// to lose the partial line only, never the session (ADR-0021).
|
|
105
|
+
await truncate(path, truncatedTailAtByte);
|
|
106
|
+
await appendFile(path, `${line}\n`);
|
|
107
|
+
}
|
|
108
|
+
return { outcome: "appended", path };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function readSession(path: string): Promise<string> {
|
|
112
|
+
try {
|
|
113
|
+
return await Bun.file(path).text();
|
|
114
|
+
} catch (error) {
|
|
115
|
+
throw new PiSessionError("unreadable", `cannot read session ${path}: ${String(error)}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** One result already recorded for the call. `text` is absent without a text part. */
|
|
120
|
+
interface RecordedResult {
|
|
121
|
+
readonly text?: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The result already recorded for the call, when the session holds one. */
|
|
125
|
+
function findResult(
|
|
126
|
+
entries: readonly SessionEntry[],
|
|
127
|
+
toolCallId: string,
|
|
128
|
+
): RecordedResult | undefined {
|
|
129
|
+
const entry = entries.find((candidate) => {
|
|
130
|
+
const message = candidate.message;
|
|
131
|
+
return isRecord(message) && message.role === "toolResult" && message.toolCallId === toolCallId;
|
|
132
|
+
});
|
|
133
|
+
if (entry === undefined) return undefined;
|
|
134
|
+
// The text stays absent when no text part carries one: it must not read as
|
|
135
|
+
// the empty string, which would make an empty append `already-present` and
|
|
136
|
+
// print `existing: ""` where there is no recorded answer at all.
|
|
137
|
+
const part = contentParts(entry).find((candidate) => candidate.type === "text");
|
|
138
|
+
return typeof part?.text === "string" ? { text: part.text } : {};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The entry one result becomes: a `toolResult` message correlated by call id. */
|
|
142
|
+
function buildEntry(request: AppendToolResultRequest, holder: SessionEntry): unknown {
|
|
143
|
+
const now = Date.now();
|
|
144
|
+
return {
|
|
145
|
+
type: "message",
|
|
146
|
+
id: entryId(),
|
|
147
|
+
parentId: typeof holder.id === "string" ? holder.id : null,
|
|
148
|
+
timestamp: new Date(now).toISOString(),
|
|
149
|
+
message: {
|
|
150
|
+
role: "toolResult",
|
|
151
|
+
toolCallId: request.toolCallId,
|
|
152
|
+
toolName: request.toolName ?? REQUEST_USER_INPUT_TOOL_NAME,
|
|
153
|
+
content: [{ type: "text", text: request.text }],
|
|
154
|
+
isError: false,
|
|
155
|
+
timestamp: now,
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Eight hex digits, pi's own entry id shape; the file never addresses this one. */
|
|
161
|
+
function entryId(): string {
|
|
162
|
+
return Math.floor(Math.random() * 0x1_0000_0000)
|
|
163
|
+
.toString(16)
|
|
164
|
+
.padStart(8, "0");
|
|
165
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public surface of the `pi-session/` module: the one writer of a pi session
|
|
3
|
+
* file, plus the session copies its two callers take. Internal to the package, like the callers it serves.
|
|
4
|
+
* Files inside this directory import each other directly.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
type AppendToolResultOutcome,
|
|
9
|
+
type AppendToolResultRequest,
|
|
10
|
+
type AppendToolResultResult,
|
|
11
|
+
appendToolResult,
|
|
12
|
+
} from "./append-tool-result.ts";
|
|
13
|
+
// The `PiSessionError` class stays inside the directory: a caller narrows with
|
|
14
|
+
// `isPiSessionError` and never constructs one. `PiSessionErrorReason` is here
|
|
15
|
+
// to name the `reason` a caller switches on, not because it is imported today.
|
|
16
|
+
export { isPiSessionError, type PiSessionErrorReason } from "./pi-session-error.ts";
|
|
17
|
+
export {
|
|
18
|
+
prepareSessionCopy,
|
|
19
|
+
type SessionCopy,
|
|
20
|
+
type SessionCopyRequest,
|
|
21
|
+
SYNTHETIC_TOOL_RESULT_TEXT,
|
|
22
|
+
} from "./session-copy.ts";
|
|
23
|
+
export {
|
|
24
|
+
findToolCall,
|
|
25
|
+
isRecord,
|
|
26
|
+
type ParsedSession,
|
|
27
|
+
parseSession,
|
|
28
|
+
type SessionEntry,
|
|
29
|
+
type ToolCallHolder,
|
|
30
|
+
} from "./session-entries.ts";
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one refusal type of the pi session editor.
|
|
3
|
+
*
|
|
4
|
+
* Not a `YaagError`: the editor has no `YaagErrorCode` of its own, and each
|
|
5
|
+
* caller maps the `reason` to its own error kind.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Why the editor refused to write. */
|
|
9
|
+
export type PiSessionErrorReason =
|
|
10
|
+
/** No entry holds the `toolCall` part with this id. */
|
|
11
|
+
| "no-such-call"
|
|
12
|
+
/** The call already has a result, and its text is another one (ADR-0022). */
|
|
13
|
+
| "different-result"
|
|
14
|
+
/** The session file cannot be read. */
|
|
15
|
+
| "unreadable"
|
|
16
|
+
/** A line other than the last one is not a session entry. */
|
|
17
|
+
| "bad-line";
|
|
18
|
+
|
|
19
|
+
export class PiSessionError extends Error {
|
|
20
|
+
readonly reason: PiSessionErrorReason;
|
|
21
|
+
/** The text already recorded for the call; set for `different-result` only. */
|
|
22
|
+
readonly existing?: string;
|
|
23
|
+
|
|
24
|
+
constructor(reason: PiSessionErrorReason, message: string, existing?: string) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "PiSessionError";
|
|
27
|
+
this.reason = reason;
|
|
28
|
+
if (existing !== undefined) this.existing = existing;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function isPiSessionError(error: unknown): error is PiSessionError {
|
|
33
|
+
return error instanceof PiSessionError;
|
|
34
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One pi session copy: the copy the fork summarizer opens (ADR-0022) and the
|
|
3
|
+
* copy a Host Fork is spawned from.
|
|
4
|
+
*
|
|
5
|
+
* A session with an open tool call cannot be continued: pi refuses a session
|
|
6
|
+
* whose last assistant message has an unanswered tool call. So yaag copies the
|
|
7
|
+
* session file and closes the open call in the copy with a result text. The
|
|
8
|
+
* source file stays untouched.
|
|
9
|
+
*
|
|
10
|
+
* The write belongs to the pi session editor, so the result parents on the
|
|
11
|
+
* entry that holds the call (ADR-0023), not on the last entry. This module owns
|
|
12
|
+
* the temp path, the removal, the result text and the tool name it gives down,
|
|
13
|
+
* and the option that tolerates a call which is already answered.
|
|
14
|
+
*/
|
|
15
|
+
import { copyFile, rm } from "node:fs/promises";
|
|
16
|
+
import { tmpdir } from "node:os";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { appendToolResult } from "./append-tool-result.ts";
|
|
19
|
+
import { isPiSessionError } from "./pi-session-error.ts";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* What the summarizer session reads in place of the human's answer. It states
|
|
23
|
+
* three facts: no answer arrived, this session is a copy, and the task is over.
|
|
24
|
+
*/
|
|
25
|
+
export const SYNTHETIC_TOOL_RESULT_TEXT =
|
|
26
|
+
"The human has not answered yet. This session is a copy of your session, made " +
|
|
27
|
+
"only to summarize your question. Do not continue your task.";
|
|
28
|
+
|
|
29
|
+
/** One prepared copy: where it is, and how to remove it again. */
|
|
30
|
+
export interface SessionCopy {
|
|
31
|
+
/** Absolute path of the copy; hand it to `pi --session`. */
|
|
32
|
+
readonly path: string;
|
|
33
|
+
/** Removes the copy. Best effort: it never throws. */
|
|
34
|
+
remove(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What one copy needs: the source session and the call to close. */
|
|
38
|
+
export interface SessionCopyRequest {
|
|
39
|
+
readonly sessionFile: string;
|
|
40
|
+
readonly toolCallId: string;
|
|
41
|
+
/** Where the copy goes; the OS temp directory by default. */
|
|
42
|
+
readonly directory?: string;
|
|
43
|
+
/** The result text written into the copy; the synthetic text by default. */
|
|
44
|
+
readonly text?: string;
|
|
45
|
+
/** The tool name the result is recorded under; `request_user_input` by default. */
|
|
46
|
+
readonly toolName?: string;
|
|
47
|
+
/**
|
|
48
|
+
* When true, a call that is already answered is not a refusal: the copy is
|
|
49
|
+
* made, nothing is appended, and the copy is used as it is. A result with the
|
|
50
|
+
* same text is a success in both cases; this field adds the result with
|
|
51
|
+
* another text (`different-result`) to it.
|
|
52
|
+
*/
|
|
53
|
+
readonly toleratesAnsweredCall?: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Copies one pi session and closes the named call in the copy.
|
|
58
|
+
*
|
|
59
|
+
* A refusal of the editor removes the copy and comes out as the
|
|
60
|
+
* `PiSessionError` the editor threw, so its `reason` reaches the caller. Only
|
|
61
|
+
* an error of another kind gets the wrapper below.
|
|
62
|
+
*/
|
|
63
|
+
export async function prepareSessionCopy(request: SessionCopyRequest): Promise<SessionCopy> {
|
|
64
|
+
const path = join(
|
|
65
|
+
request.directory ?? tmpdir(),
|
|
66
|
+
`yaag-summary-${Date.now()}-${Math.random().toString(16).slice(2)}.jsonl`,
|
|
67
|
+
);
|
|
68
|
+
const copy: SessionCopy = {
|
|
69
|
+
path,
|
|
70
|
+
remove: async (): Promise<void> => {
|
|
71
|
+
try {
|
|
72
|
+
await rm(path, { force: true });
|
|
73
|
+
} catch {
|
|
74
|
+
// best effort: a leftover temp file must never fail a Run
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
try {
|
|
79
|
+
await appendToolResult({
|
|
80
|
+
sessionFile: request.sessionFile,
|
|
81
|
+
toolCallId: request.toolCallId,
|
|
82
|
+
text: request.text ?? SYNTHETIC_TOOL_RESULT_TEXT,
|
|
83
|
+
...(request.toolName === undefined ? {} : { toolName: request.toolName }),
|
|
84
|
+
into: path,
|
|
85
|
+
});
|
|
86
|
+
} catch (error) {
|
|
87
|
+
return await onRefusal(request, copy, error);
|
|
88
|
+
}
|
|
89
|
+
return copy;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** What one refusal becomes: a tolerated copy, or the error the caller reads. */
|
|
93
|
+
async function onRefusal(
|
|
94
|
+
request: SessionCopyRequest,
|
|
95
|
+
copy: SessionCopy,
|
|
96
|
+
error: unknown,
|
|
97
|
+
): Promise<SessionCopy> {
|
|
98
|
+
if (
|
|
99
|
+
request.toleratesAnsweredCall === true &&
|
|
100
|
+
isPiSessionError(error) &&
|
|
101
|
+
error.reason === "different-result"
|
|
102
|
+
) {
|
|
103
|
+
// The editor refused before it made the copy, so this branch copies.
|
|
104
|
+
await copyFile(request.sessionFile, copy.path);
|
|
105
|
+
return copy;
|
|
106
|
+
}
|
|
107
|
+
await copy.remove();
|
|
108
|
+
// The `reason` must reach the runtime, which maps it to its own error kind.
|
|
109
|
+
if (isPiSessionError(error)) throw error;
|
|
110
|
+
throw new Error(
|
|
111
|
+
`cannot prepare a session copy: ${error instanceof Error ? error.message : String(error)}`,
|
|
112
|
+
);
|
|
113
|
+
}
|