@yaag/runtime 0.26.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 +1 -1
- package/src/agent/agent.ts +29 -17
- package/src/agent/fork.ts +40 -12
- package/src/agent/host-fork.ts +85 -0
- package/src/agent/spawn-definition-request.ts +38 -3
- package/src/agent/spawn-open.ts +43 -103
- package/src/agent/spawn-plan.ts +114 -0
- package/src/agent/spawn-request.ts +16 -2
- package/src/agent/spawn.ts +20 -3
- package/src/ask/ask-exchange-options.ts +3 -6
- package/src/ask/ask-exchange.ts +48 -108
- package/src/ask/ask-guard.ts +207 -0
- package/src/ask/ask-timing.ts +12 -0
- package/src/ask/index.ts +1 -0
- package/src/cassette/cassette-loader.ts +9 -20
- package/src/cassette/cassette-schema.ts +10 -1
- package/src/cassette/cassette.ts +11 -34
- package/src/cassette/checkpoint.ts +306 -0
- package/src/cassette/index.ts +16 -7
- package/src/cassette/parked-asks.ts +38 -0
- package/src/cassette/replay-divergence.ts +7 -102
- package/src/cassette/resume-identity.ts +5 -1
- package/src/cassette/resume-preconditions.ts +14 -0
- package/src/cassette/resume-transport.ts +26 -32
- package/src/cassette/run-identity.ts +109 -0
- package/src/cassette/session-answer.ts +51 -114
- package/src/cassette/spawn-identity.ts +318 -0
- package/src/contract/error-codes.ts +1 -0
- package/src/contract/index.ts +1 -0
- package/src/contract/spawn-options.ts +33 -2
- package/src/error-factories.ts +8 -0
- package/src/events.ts +4 -2
- package/src/index.ts +4 -0
- 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/question-summary/index.ts +4 -8
- package/src/question-summary/summarize-question.ts +1 -1
- package/src/question-summary/summary-policy.ts +5 -2
- package/src/run/agent-questions.ts +82 -0
- package/src/run/answers.ts +22 -1
- package/src/run/host-session.ts +233 -0
- package/src/run/index.ts +7 -0
- package/src/run/run-context.ts +3 -0
- package/src/run/run.ts +191 -181
- package/src/transport/live-transport.ts +19 -0
- package/src/transport/pi-state.ts +10 -1
- package/src/transport/transport.ts +13 -9
- package/src/types.ts +1 -0
- package/src/cassette/checkpoint-flush.ts +0 -101
- package/src/cassette/run-checkpoint.ts +0 -272
- package/src/question-summary/session-copy.ts +0 -169
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spawn Identity: the one table of spawn fields.
|
|
3
|
+
*
|
|
4
|
+
* Every reader of a spawn's field roster — the Cassette spawn record, the spawn
|
|
5
|
+
* hash, the Divergence changed-fields list, and the argv builder — reads this
|
|
6
|
+
* table. Before this module the roster was written by hand in seven places, and
|
|
7
|
+
* nothing proved the seven agreed.
|
|
8
|
+
*
|
|
9
|
+
* To add one spawn option: add one row here and one property to `OpenOptions`.
|
|
10
|
+
* The two type asserts at the bottom fail the build when the two disagree.
|
|
11
|
+
*/
|
|
12
|
+
import type { OpenOptions } from "../transport/index.ts";
|
|
13
|
+
import type { CassetteSpawn } from "./cassette.ts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `identity` names the Agent across a record and a replay, so the Cassette
|
|
17
|
+
* stores it. `launch` is a fact of one process start that the Cassette never
|
|
18
|
+
* sees; a transport decorator may pass it down freely.
|
|
19
|
+
*/
|
|
20
|
+
export type FieldKind = "identity" | "launch";
|
|
21
|
+
|
|
22
|
+
/** How one field enters the hashed object. Absent means it never enters it. */
|
|
23
|
+
export type HashRule =
|
|
24
|
+
/** Assigned raw, always present. */
|
|
25
|
+
| "always"
|
|
26
|
+
/** Assigned as `value ?? null`; the key is always present. */
|
|
27
|
+
| "nullable"
|
|
28
|
+
/** Present when the value is not `undefined`. */
|
|
29
|
+
| "optional"
|
|
30
|
+
/** Present only when the value is exactly `true`. */
|
|
31
|
+
| "whenTrue"
|
|
32
|
+
/** Present when the value is defined and not empty. */
|
|
33
|
+
| "whenNonEmpty";
|
|
34
|
+
|
|
35
|
+
/** One spawn field and what every reader must know about it. */
|
|
36
|
+
export interface SpawnField {
|
|
37
|
+
readonly field: keyof OpenOptions;
|
|
38
|
+
readonly kind: FieldKind;
|
|
39
|
+
/** Absent when the field never enters the spawn hash. */
|
|
40
|
+
readonly hash?: HashRule;
|
|
41
|
+
/** True for the fields an Ask-marker context also compares (ADR-0039). */
|
|
42
|
+
readonly askContext?: true;
|
|
43
|
+
/** Whether the field may put anything on the pi command line. */
|
|
44
|
+
readonly argv: "flag" | "never";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The roster, in Divergence order: `changedFields` reports in this order, so
|
|
49
|
+
* the `changed …` clause of a `REPLAY_DIVERGED` message is unchanged.
|
|
50
|
+
*
|
|
51
|
+
* The `hash` column carries two readings. It says how the field enters the
|
|
52
|
+
* spawn hash, and `recordRule` below derives from it how the field enters a
|
|
53
|
+
* Cassette record. The two agree today except for `nullable`. A future row
|
|
54
|
+
* whose recorded presence differs from its hashed presence needs a column of
|
|
55
|
+
* its own rather than a special case in `fromOpenOptions`.
|
|
56
|
+
*/
|
|
57
|
+
const FIELD_TABLE = [
|
|
58
|
+
{ field: "name", kind: "identity", hash: "always", argv: "never" },
|
|
59
|
+
{ field: "cwd", kind: "identity", hash: "always", askContext: true, argv: "never" },
|
|
60
|
+
{ field: "model", kind: "identity", hash: "nullable", askContext: true, argv: "flag" },
|
|
61
|
+
{ field: "systemPrompt", kind: "identity", hash: "nullable", askContext: true, argv: "flag" },
|
|
62
|
+
{ field: "thinking", kind: "identity", hash: "optional", askContext: true, argv: "flag" },
|
|
63
|
+
{
|
|
64
|
+
field: "appendSystemPrompt",
|
|
65
|
+
kind: "identity",
|
|
66
|
+
hash: "optional",
|
|
67
|
+
askContext: true,
|
|
68
|
+
argv: "never",
|
|
69
|
+
},
|
|
70
|
+
{ field: "tools", kind: "identity", hash: "optional", askContext: true, argv: "flag" },
|
|
71
|
+
{ field: "disallowedTools", kind: "identity", hash: "optional", askContext: true, argv: "flag" },
|
|
72
|
+
{ field: "skills", kind: "identity", hash: "optional", askContext: true, argv: "never" },
|
|
73
|
+
{
|
|
74
|
+
field: "disallowedSkills",
|
|
75
|
+
kind: "identity",
|
|
76
|
+
hash: "optional",
|
|
77
|
+
askContext: true,
|
|
78
|
+
argv: "never",
|
|
79
|
+
},
|
|
80
|
+
{ field: "worktree", kind: "identity", hash: "whenTrue", askContext: true, argv: "never" },
|
|
81
|
+
{ field: "declaredExtensions", kind: "identity", hash: "whenNonEmpty", argv: "never" },
|
|
82
|
+
// `flag` because it loads the injected `request_user_input` extension: the
|
|
83
|
+
// command line gains `-e <fixed path>`, never the value of the field itself
|
|
84
|
+
// (ADR-0023).
|
|
85
|
+
{ field: "canAskUser", kind: "identity", hash: "optional", argv: "flag" },
|
|
86
|
+
// Identity but never hashed: a bumped protocol must refuse the reactivation,
|
|
87
|
+
// and a hash mismatch would start a fresh Agent instead (ADR-0023).
|
|
88
|
+
{ field: "askUserProtocol", kind: "identity", argv: "never" },
|
|
89
|
+
{ field: "parent", kind: "identity", hash: "optional", argv: "never" },
|
|
90
|
+
{ field: "origin", kind: "identity", hash: "optional", argv: "never" },
|
|
91
|
+
{ field: "forkOf", kind: "identity", hash: "optional", argv: "never" },
|
|
92
|
+
{ field: "forkAsks", kind: "identity", hash: "optional", argv: "never" },
|
|
93
|
+
{ field: "inherit", kind: "launch", argv: "flag" },
|
|
94
|
+
{ field: "sessionDir", kind: "launch", argv: "flag" },
|
|
95
|
+
{ field: "sessionFile", kind: "launch", argv: "flag" },
|
|
96
|
+
{ field: "forkSession", kind: "launch", argv: "flag" },
|
|
97
|
+
{ field: "worktreeFrom", kind: "launch", argv: "never" },
|
|
98
|
+
{ field: "resolvedSkillPaths", kind: "launch", argv: "flag" },
|
|
99
|
+
{ field: "resolvedExtensionPaths", kind: "launch", argv: "flag" },
|
|
100
|
+
// Spawn identity: it names the Host Session conversation a Host Fork was
|
|
101
|
+
// taken from. Omitted when undefined, so every Cassette recorded before this
|
|
102
|
+
// row keeps its hash, and never argv. The copy path (`forkSession`) stays a
|
|
103
|
+
// launch row below, because that path is machine-specific.
|
|
104
|
+
{ field: "hostHash", kind: "identity", hash: "optional", argv: "never" },
|
|
105
|
+
] as const satisfies readonly SpawnField[];
|
|
106
|
+
|
|
107
|
+
/** The table as a uniform row list; `FIELD_TABLE` keeps the literal field names. */
|
|
108
|
+
export const SPAWN_FIELDS: readonly SpawnField[] = FIELD_TABLE;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The hash key order, frozen. A Cassette recorded before a field existed keeps
|
|
112
|
+
* its hash only while this order and the per-field rules above stay put.
|
|
113
|
+
*/
|
|
114
|
+
const HASH_ORDER = [
|
|
115
|
+
"name",
|
|
116
|
+
"cwd",
|
|
117
|
+
"model",
|
|
118
|
+
"systemPrompt",
|
|
119
|
+
"tools",
|
|
120
|
+
"disallowedTools",
|
|
121
|
+
"skills",
|
|
122
|
+
"disallowedSkills",
|
|
123
|
+
"worktree",
|
|
124
|
+
"thinking",
|
|
125
|
+
"appendSystemPrompt",
|
|
126
|
+
"declaredExtensions",
|
|
127
|
+
"canAskUser",
|
|
128
|
+
"parent",
|
|
129
|
+
"origin",
|
|
130
|
+
"forkOf",
|
|
131
|
+
"forkAsks",
|
|
132
|
+
// Appended last: an absent `hostHash` adds no key, so no recorded hash moves.
|
|
133
|
+
"hostHash",
|
|
134
|
+
] as const;
|
|
135
|
+
|
|
136
|
+
/** The key order of the recorded spawn, frozen for the same reason. */
|
|
137
|
+
const RECORD_ORDER = [
|
|
138
|
+
"name",
|
|
139
|
+
"cwd",
|
|
140
|
+
"model",
|
|
141
|
+
"systemPrompt",
|
|
142
|
+
"thinking",
|
|
143
|
+
"appendSystemPrompt",
|
|
144
|
+
"tools",
|
|
145
|
+
"disallowedTools",
|
|
146
|
+
"skills",
|
|
147
|
+
"disallowedSkills",
|
|
148
|
+
"declaredExtensions",
|
|
149
|
+
"canAskUser",
|
|
150
|
+
"askUserProtocol",
|
|
151
|
+
"parent",
|
|
152
|
+
"origin",
|
|
153
|
+
"forkOf",
|
|
154
|
+
"forkAsks",
|
|
155
|
+
"worktree",
|
|
156
|
+
// Appended last, for the same reason as in `HASH_ORDER`.
|
|
157
|
+
"hostHash",
|
|
158
|
+
] as const;
|
|
159
|
+
|
|
160
|
+
const BY_FIELD = new Map(SPAWN_FIELDS.map((row) => [row.field, row]));
|
|
161
|
+
|
|
162
|
+
/** The orders above, exported so one structural test can check them for drift. */
|
|
163
|
+
export const FIELD_ORDERS: {
|
|
164
|
+
readonly hash: readonly (keyof OpenOptions)[];
|
|
165
|
+
readonly record: readonly (keyof OpenOptions)[];
|
|
166
|
+
} = { hash: HASH_ORDER, record: RECORD_ORDER };
|
|
167
|
+
|
|
168
|
+
type Source = CassetteSpawn | OpenOptions;
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Anything that carries some spawn fields. An Ask-marker context carries a
|
|
172
|
+
* subset of them, so the diff functions read this rather than a whole record.
|
|
173
|
+
*/
|
|
174
|
+
export type SpawnFieldSource = { readonly [Field in keyof OpenOptions]?: unknown };
|
|
175
|
+
|
|
176
|
+
function read<Field extends keyof OpenOptions>(source: SpawnFieldSource, field: Field): unknown {
|
|
177
|
+
return source[field];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** True when the rule keeps the value out of the built object. */
|
|
181
|
+
function omits(rule: HashRule, value: unknown): boolean {
|
|
182
|
+
if (rule === "always" || rule === "nullable") return false;
|
|
183
|
+
if (rule === "whenTrue") return value !== true;
|
|
184
|
+
// `Array.isArray` rather than a cast: a future non-array row given this rule
|
|
185
|
+
// is then omitted, not read for a `length` it does not have.
|
|
186
|
+
if (rule === "whenNonEmpty") return !Array.isArray(value) || value.length === 0;
|
|
187
|
+
return value === undefined;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Arrays are copied, so a later mutation of the caller's list cannot reach a record. */
|
|
191
|
+
function clone(value: unknown): unknown {
|
|
192
|
+
return Array.isArray(value) ? [...value] : value;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The Cassette spawn record of one open request: the identity rows, in record
|
|
197
|
+
* order. `name` and `cwd` open the record because `RECORD_ORDER` starts with
|
|
198
|
+
* them, which is what the recorded key order needs.
|
|
199
|
+
*/
|
|
200
|
+
export function fromOpenOptions(options: OpenOptions): CassetteSpawn {
|
|
201
|
+
const record: CassetteSpawn = { name: options.name, cwd: options.cwd };
|
|
202
|
+
for (const field of RECORD_ORDER) {
|
|
203
|
+
if (field === "name" || field === "cwd") continue;
|
|
204
|
+
const value = read(options, field);
|
|
205
|
+
if (omits(recordRule(field), value)) continue;
|
|
206
|
+
Object.assign(record, { [field]: clone(value) });
|
|
207
|
+
}
|
|
208
|
+
return record;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* How one field enters a record. It is derived from the `hash` column, with the
|
|
213
|
+
* one documented shift: a record keeps `model` and `systemPrompt` absent rather
|
|
214
|
+
* than null. A future row whose recorded presence differs from its hashed
|
|
215
|
+
* presence needs its own column here, not a special case.
|
|
216
|
+
*/
|
|
217
|
+
function recordRule(field: keyof OpenOptions): HashRule {
|
|
218
|
+
const rule = BY_FIELD.get(field)?.hash ?? "optional";
|
|
219
|
+
return rule === "nullable" ? "optional" : rule;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The hex digest of one spawn identity. The bytes are a frozen contract (story 8). */
|
|
223
|
+
export function hash(identity: Source): string {
|
|
224
|
+
const hashed: Record<string, unknown> = {};
|
|
225
|
+
for (const field of HASH_ORDER) {
|
|
226
|
+
const rule = BY_FIELD.get(field)?.hash;
|
|
227
|
+
if (rule === undefined) continue;
|
|
228
|
+
const value = read(identity, field);
|
|
229
|
+
if (omits(rule, value)) continue;
|
|
230
|
+
hashed[field] = rule === "nullable" ? (value ?? null) : value;
|
|
231
|
+
}
|
|
232
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
233
|
+
hasher.update(JSON.stringify(hashed));
|
|
234
|
+
return hasher.digest("hex");
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The listed fields whose canonical JSON differs between two identity records. */
|
|
238
|
+
function changedAmong(
|
|
239
|
+
fields: readonly (keyof OpenOptions)[],
|
|
240
|
+
expected: SpawnFieldSource,
|
|
241
|
+
actual: SpawnFieldSource,
|
|
242
|
+
): readonly string[] {
|
|
243
|
+
return fields.filter(
|
|
244
|
+
(field) => JSON.stringify(read(expected, field)) !== JSON.stringify(read(actual, field)),
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Every field the spawn hash covers, in Divergence order. Not every identity
|
|
250
|
+
* field: `askUserProtocol` is Spawn Identity that the hash leaves out.
|
|
251
|
+
*/
|
|
252
|
+
export function hashedFields(): readonly (keyof OpenOptions)[] {
|
|
253
|
+
return SPAWN_FIELDS.filter((row) => row.hash !== undefined).map((row) => row.field);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The identity fields an Ask-marker context compares. Extensions are the
|
|
258
|
+
* deliberate exception: they identify the process start, not an Ask.
|
|
259
|
+
*/
|
|
260
|
+
export function askContextFields(): readonly (keyof OpenOptions)[] {
|
|
261
|
+
return SPAWN_FIELDS.filter((row) => row.askContext === true).map((row) => row.field);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The rows the argv builder may turn into a pi flag. */
|
|
265
|
+
export function argvFields(): readonly (keyof OpenOptions)[] {
|
|
266
|
+
return SPAWN_FIELDS.filter((row) => row.argv === "flag").map((row) => row.field);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The Divergence field list of one spawn mismatch. */
|
|
270
|
+
export function changedFields(
|
|
271
|
+
expected: SpawnFieldSource,
|
|
272
|
+
actual: SpawnFieldSource,
|
|
273
|
+
): readonly string[] {
|
|
274
|
+
return changedAmong(hashedFields(), expected, actual);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The Divergence field list an Ask-marker context reports. */
|
|
278
|
+
export function askContextChangedFields(
|
|
279
|
+
expected: SpawnFieldSource,
|
|
280
|
+
actual: SpawnFieldSource,
|
|
281
|
+
): readonly string[] {
|
|
282
|
+
return changedAmong(askContextFields(), expected, actual);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* True when a live spawn matches the recorded one on every identity field
|
|
287
|
+
* except the resolved model and thinking, so a resume may adopt the recorded
|
|
288
|
+
* selection instead of re-running Model Resolution (ADR-0039).
|
|
289
|
+
*/
|
|
290
|
+
export function matchesExceptModel(expected: CassetteSpawn, actual: OpenOptions): boolean {
|
|
291
|
+
return (
|
|
292
|
+
hash({ ...expected, model: undefined, thinking: undefined }) ===
|
|
293
|
+
hash({ ...actual, model: undefined, thinking: undefined })
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// A key of `OpenOptions` without a row, or a row that is not a key, is a build
|
|
298
|
+
// failure here rather than a silent gap in the hash (story 3).
|
|
299
|
+
type Row = (typeof FIELD_TABLE)[number]["field"];
|
|
300
|
+
type Assert<A extends B, B> = [A, B] extends [B, A] ? true : never;
|
|
301
|
+
type _EveryKeyHasRow = Assert<keyof OpenOptions, Row>;
|
|
302
|
+
|
|
303
|
+
// `CassetteSpawn` is hand-written, and `fromOpenOptions` builds it field by
|
|
304
|
+
// field, so these two tie the record type back to the table: the record holds
|
|
305
|
+
// exactly the identity rows, and every value an open option carries fits the
|
|
306
|
+
// field the record declares for it.
|
|
307
|
+
type IdentityRow = Extract<(typeof FIELD_TABLE)[number], { kind: "identity" }>["field"];
|
|
308
|
+
type AssertTrue<T extends true> = T;
|
|
309
|
+
type _RecordHoldsEveryIdentityRow = Assert<keyof CassetteSpawn, IdentityRow>;
|
|
310
|
+
type _EveryIdentityRowIsRecorded = Assert<IdentityRow, keyof CassetteSpawn>;
|
|
311
|
+
type _RecordTakesOpenOptionValues = AssertTrue<
|
|
312
|
+
{
|
|
313
|
+
[Field in keyof CassetteSpawn]-?: OpenOptions[Field] extends CassetteSpawn[Field]
|
|
314
|
+
? true
|
|
315
|
+
: false;
|
|
316
|
+
}[keyof CassetteSpawn]
|
|
317
|
+
>;
|
|
318
|
+
type _EveryRowIsAKey = Assert<Row, keyof OpenOptions>;
|
|
@@ -57,6 +57,7 @@ export type YaagErrorCode =
|
|
|
57
57
|
| "OPTIONS_CONFLICT" // incompatible Run options were supplied
|
|
58
58
|
| "PAUSE_REFUSED" // two pause questions claim one id (ADR-0022)
|
|
59
59
|
| "RECORD_PATH_UNUSABLE" // the --record directory could not be created at Run start
|
|
60
|
+
| "HOST_SESSION_UNUSABLE" // the host session file cannot start a Run: missing, unreadable, empty, header-less, ill-formed, without the named tool call, or without a tool call id on a live run
|
|
60
61
|
| "REPLAY_DIVERGED" // replayed program differed from its Cassette
|
|
61
62
|
| "RESUME_REFUSED" // resume metadata is absent, the recorded tree moved, or an answer is unknown or conflicting (ADR-0022/0023)
|
|
62
63
|
| "PROFILE_NOT_FOUND" // a selected Profile is not declared by the program (ADR-0052)
|
package/src/contract/index.ts
CHANGED
|
@@ -8,6 +8,23 @@ import type { AgentPolicy } from "./agent-policy.ts";
|
|
|
8
8
|
import type { Handle } from "./handle.ts";
|
|
9
9
|
import type { ThinkingLevel } from "./model-spec.ts";
|
|
10
10
|
|
|
11
|
+
/** Not exported, so a HostSource is unreachable outside this module. */
|
|
12
|
+
declare const hostSource: unique symbol;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The Host Session's conversation, offered as a fork source.
|
|
16
|
+
*
|
|
17
|
+
* A program reads it as `ctx.host` and passes it back; it cannot build one,
|
|
18
|
+
* because the brand key is private to this module. It follows the fork rules of
|
|
19
|
+
* ADR-0044, with the Host Session in the place of an Agent as the source, and
|
|
20
|
+
* it stays type-only, so the author declaration tree carries no value
|
|
21
|
+
* (ADR-0045).
|
|
22
|
+
*/
|
|
23
|
+
export interface HostSource {
|
|
24
|
+
readonly kind: "host";
|
|
25
|
+
readonly [hostSource]: true;
|
|
26
|
+
}
|
|
27
|
+
|
|
11
28
|
/**
|
|
12
29
|
* Options for spawning one Agent: an Agent Policy plus its topology
|
|
13
30
|
* (ADR-0001, ADR-0009, ADR-0026).
|
|
@@ -22,6 +39,10 @@ export interface SpawnOptions extends AgentPolicy {
|
|
|
22
39
|
* no conversation channel and no lifetime rule.
|
|
23
40
|
*/
|
|
24
41
|
readonly parent?: Handle;
|
|
42
|
+
/** Fork the Host Session's conversation instead of starting a fresh one. */
|
|
43
|
+
readonly fork?: HostSource;
|
|
44
|
+
/** true = pi's default compaction; a string = pi custom instructions. */
|
|
45
|
+
readonly compact?: boolean | string;
|
|
25
46
|
}
|
|
26
47
|
|
|
27
48
|
/**
|
|
@@ -40,9 +61,15 @@ export interface SpawnOptions extends AgentPolicy {
|
|
|
40
61
|
* spawn-request seam, so no consumer of this shape can ever see a function
|
|
41
62
|
* (ADR-0064). An unset prompt stays unset here; the default text is filled in
|
|
42
63
|
* `openRequest` alone, so the Ask hash keeps hashing `systemPrompt: null`.
|
|
64
|
+
*
|
|
65
|
+
* `fork` and `compact` are omitted too: they are spawn verbs, not properties of
|
|
66
|
+
* the Agent, so they never enter Ask identity.
|
|
43
67
|
*/
|
|
44
68
|
export interface ResolvedSpawnOptions
|
|
45
|
-
extends Omit<
|
|
69
|
+
extends Omit<
|
|
70
|
+
SpawnOptions,
|
|
71
|
+
"model" | "thinking" | "parent" | "askDefaults" | "fork" | "compact" | "systemPrompt"
|
|
72
|
+
> {
|
|
46
73
|
readonly model?: string;
|
|
47
74
|
readonly systemPrompt?: string;
|
|
48
75
|
readonly thinking?: ThinkingLevel;
|
|
@@ -63,7 +90,7 @@ export interface ResolvedSpawnOptions
|
|
|
63
90
|
* source's branch, so only committed state transfers. The child re-runs the
|
|
64
91
|
* ADR-0026 Tool Contract probe against its own effective options.
|
|
65
92
|
*/
|
|
66
|
-
export interface ForkOptions extends SpawnOptions {
|
|
93
|
+
export interface ForkOptions extends Omit<SpawnOptions, "fork"> {
|
|
67
94
|
/** true = pi's default compaction; a string = pi custom instructions. */
|
|
68
95
|
readonly compact?: boolean | string;
|
|
69
96
|
}
|
|
@@ -78,4 +105,8 @@ export interface SpawnOverrides {
|
|
|
78
105
|
readonly worktree?: boolean;
|
|
79
106
|
/** Names this Agent's parent in the Run tree (Parent Link). Data only. */
|
|
80
107
|
readonly parent?: Handle;
|
|
108
|
+
/** Fork the Host Session's conversation instead of starting a fresh one. */
|
|
109
|
+
readonly fork?: HostSource;
|
|
110
|
+
/** true = pi's default compaction; a string = pi custom instructions. */
|
|
111
|
+
readonly compact?: boolean | string;
|
|
81
112
|
}
|
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
|
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,
|
|
@@ -240,6 +243,7 @@ export type {
|
|
|
240
243
|
AskOptions,
|
|
241
244
|
ForkOptions,
|
|
242
245
|
Handle,
|
|
246
|
+
HostSource,
|
|
243
247
|
LiteralPromptText,
|
|
244
248
|
PromptAudience,
|
|
245
249
|
PromptText,
|
|
@@ -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";
|