pi-subagent-manager 0.0.0-stage → 0.1.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/src/manager.ts ADDED
@@ -0,0 +1,576 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type {
3
+ AgentDriver,
4
+ AgentType,
5
+ DriverOptions,
6
+ ManagerOptions,
7
+ SavedThread,
8
+ SavedThreadView,
9
+ ThreadService,
10
+ ThreadView,
11
+ } from "./types.ts";
12
+ import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.ts";
13
+
14
+ interface Record {
15
+ view: ThreadView;
16
+ definition: AgentType;
17
+ inherited: AgentMessage[];
18
+ contextReady?: Promise<void>;
19
+ contextPending?: boolean;
20
+ startup: AbortController;
21
+ driver?: AgentDriver;
22
+ initializing?: Promise<AgentDriver>;
23
+ run?: Promise<void>;
24
+ started?: Promise<void>;
25
+ sessionLeafId?: string | null;
26
+ pauseRequested: boolean;
27
+ stopRequested: boolean;
28
+ }
29
+ const active = (view: Pick<ThreadView, "state">) =>
30
+ view.state === "starting" || view.state === "running";
31
+ const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
32
+
33
+ function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
34
+ if (signal.aborted) {
35
+ void work.catch(() => {});
36
+ return Promise.reject(signal.reason);
37
+ }
38
+ return new Promise((resolve, reject) => {
39
+ const cancel = () => reject(signal.reason ?? new Error("Startup cancelled"));
40
+ signal.addEventListener("abort", cancel, { once: true });
41
+ work.then(
42
+ (value) => {
43
+ signal.removeEventListener("abort", cancel);
44
+ resolve(value);
45
+ },
46
+ (error) => {
47
+ signal.removeEventListener("abort", cancel);
48
+ reject(error);
49
+ },
50
+ );
51
+ });
52
+ }
53
+
54
+ /** Runtime-neutral thread ownership, context inheritance, lifecycle and durable registry. */
55
+ export class ThreadManager {
56
+ private records = new Map<string, Record>();
57
+ private disposed = false;
58
+ private epoch = 0;
59
+ constructor(private options: ManagerOptions) {}
60
+
61
+ list(): ThreadView[] {
62
+ return [...this.records.values()].map((record) => this.view(record));
63
+ }
64
+
65
+ /** Bind authority once; models and the user UI share this small composable service. */
66
+ scope(caller: string): ThreadService {
67
+ caller = canonicalPath(caller);
68
+ return {
69
+ list: () =>
70
+ this.list().filter(
71
+ (thread) =>
72
+ caller === "/root" || thread.path === caller || isDescendant(thread.path, caller),
73
+ ),
74
+ get: (path) => this.get(path, caller),
75
+ output: (path) => this.output(path, caller),
76
+ transcript: (path) => this.transcript(caller, path),
77
+ spawn: (args, signal) => this.spawn(caller, args, signal),
78
+ steer: (path, message) => this.steer(caller, path, message),
79
+ wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
80
+ update: (message) => this.update(caller, message),
81
+ pause: (reason) => this.pause(caller, reason),
82
+ stop: (path) => this.stop(caller, path),
83
+ };
84
+ }
85
+ get(path: string, caller = "/root"): ThreadView {
86
+ path = canonicalPath(path, caller);
87
+ this.assertAccess(caller, path, true);
88
+ if (path === "/root")
89
+ return {
90
+ path,
91
+ parent: null,
92
+ owner: path,
93
+ type: "main",
94
+ state: "running",
95
+ task: "Main Pi session",
96
+ status: "main",
97
+ createdAt: 0,
98
+ updatedAt: Date.now(),
99
+ };
100
+ return this.view(this.record(path));
101
+ }
102
+ output(path: string, caller = "/root"): string {
103
+ const view = this.get(path, caller);
104
+ if (view.state === "paused") return ""; // No answer handback from a paused turn.
105
+ return view.output ?? "";
106
+ }
107
+ saved(): SavedThread[] {
108
+ return [...this.records.values()].map((record) => {
109
+ const current = this.view(record);
110
+ // Explicit durable schema: adding UI fields must not silently change session storage.
111
+ const view: SavedThreadView = {
112
+ path: current.path,
113
+ parent: current.parent,
114
+ owner: current.owner,
115
+ type: current.type,
116
+ color: current.color,
117
+ state: current.state,
118
+ task: current.task,
119
+ status: current.status,
120
+ output: current.output,
121
+ error: current.error,
122
+ createdAt: current.createdAt,
123
+ sessionFile: current.sessionFile,
124
+ };
125
+ const sessionLeafId = this.sessionLeafId(record);
126
+ if (sessionLeafId !== undefined) view.sessionLeafId = sessionLeafId;
127
+ if (active(view)) view.status = view.state === "running" ? "Working" : "Starting";
128
+ return {
129
+ view,
130
+ definition: structuredClone(record.definition),
131
+ ...(!view.sessionFile && !record.contextPending
132
+ ? { inherited: structuredClone(record.inherited) }
133
+ : {}),
134
+ };
135
+ });
136
+ }
137
+ restore(saved: SavedThread[]): void {
138
+ if (this.records.size) throw new Error("Restore requires an empty thread registry");
139
+ const restored = new Map<string, Record>();
140
+ for (const item of saved) {
141
+ const savedView = structuredClone(item.view);
142
+ const path = canonicalPath(savedView.path);
143
+ if (
144
+ path === "/root" ||
145
+ restored.has(path) ||
146
+ !["starting", "running", "paused", "completed", "failed", "stopped"].includes(
147
+ savedView.state,
148
+ )
149
+ )
150
+ throw new Error("Invalid saved thread registry");
151
+ const { sessionLeafId, ...storedView } = savedView;
152
+ const view: ThreadView = { ...storedView, updatedAt: Date.now() };
153
+ if (view.parent !== parentPath(path)) throw new Error(`Invalid saved parent for ${path}`);
154
+ if (active(view)) {
155
+ view.state = "paused";
156
+ view.status = "Interrupted by reload; send input to resume";
157
+ delete view.output;
158
+ }
159
+ restored.set(path, {
160
+ view,
161
+ definition: structuredClone(item.definition),
162
+ inherited: structuredClone(item.inherited ?? []),
163
+ // A reservation saved before its lexical parent opened has no snapshot yet.
164
+ contextPending: !view.sessionFile && item.inherited === undefined && view.parent !== null,
165
+ startup: new AbortController(),
166
+ ...(Object.prototype.hasOwnProperty.call(savedView, "sessionLeafId")
167
+ ? { sessionLeafId }
168
+ : {}),
169
+ pauseRequested: false,
170
+ stopRequested: false,
171
+ });
172
+ }
173
+ for (const record of restored.values()) {
174
+ if (record.view.parent && record.view.parent !== "/root" && !restored.has(record.view.parent))
175
+ throw new Error(`Missing saved parent ${record.view.parent}`);
176
+ }
177
+ this.records = restored;
178
+ }
179
+
180
+ async spawn(
181
+ caller: string,
182
+ args: { path: string; type: string; task: string; wait?: boolean },
183
+ signal?: AbortSignal,
184
+ ): Promise<ThreadView> {
185
+ this.assertLive();
186
+ caller = canonicalPath(caller);
187
+ if (
188
+ caller !== "/root" &&
189
+ (!active(this.record(caller).view) || this.record(caller).stopRequested)
190
+ )
191
+ throw new Error("Only a working agent may spawn children");
192
+ signal?.throwIfAborted();
193
+ const path = canonicalPath(args.path, caller);
194
+ this.assertAccess(caller, path);
195
+ if (path === "/root" || this.records.has(path))
196
+ throw new Error(`Thread ${path} already exists; use agent_steer to resume it`);
197
+ const parent = parentPath(path);
198
+ if (parent && parent !== "/root") this.record(parent);
199
+ if (caller !== "/root" && parent !== caller)
200
+ throw new Error("An agent may spawn only its immediate children");
201
+ if (!args.task.trim()) throw new Error("Task must not be empty");
202
+ if (path.slice(1).split("/").length - 1 > (this.options.maxDepth ?? 8))
203
+ throw new Error("Agent depth limit reached");
204
+ if (this.records.size >= (this.options.maxThreads ?? 64))
205
+ throw new Error("Total thread limit reached");
206
+ this.assertCapacity();
207
+ const type = structuredClone(this.options.getType(args.type));
208
+ const parentRecord = parent && parent !== "/root" ? this.record(parent) : undefined;
209
+ this.assertStartableAncestors(path);
210
+ // Reservation is synchronous: subtree cancellation sees children even during lazy parent reopen.
211
+ const inherited =
212
+ parent === "/root"
213
+ ? inheritContext(this.options.rootSnapshot())
214
+ : parentRecord?.driver
215
+ ? inheritContext(parentRecord.driver.snapshot())
216
+ : [];
217
+ const now = Date.now();
218
+ const record: Record = {
219
+ view: {
220
+ path,
221
+ parent,
222
+ owner: parent ?? caller,
223
+ type: type.name,
224
+ color: type.color,
225
+ state: "starting",
226
+ task: args.task,
227
+ status: "Starting",
228
+ createdAt: now,
229
+ updatedAt: now,
230
+ },
231
+ definition: type,
232
+ inherited,
233
+ contextPending: !!(parentRecord && !parentRecord.driver),
234
+ startup: new AbortController(),
235
+ pauseRequested: false,
236
+ stopRequested: false,
237
+ };
238
+ this.records.set(path, record);
239
+ if (record.contextPending) this.prepareInheritedContext(record);
240
+ this.start(record, args.task);
241
+ return args.wait === false ? this.view(record) : this.wait(caller, path, undefined, signal);
242
+ }
243
+
244
+ async steer(caller: string, path: string, message: string): Promise<ThreadView> {
245
+ this.assertLive();
246
+ caller = canonicalPath(caller);
247
+ path = canonicalPath(path, caller);
248
+ this.assertAccess(caller, path);
249
+ if (!message.trim()) throw new Error("Steering message must not be empty");
250
+ const record = this.record(path);
251
+ for (;;) {
252
+ this.assertLive();
253
+ this.assertCallerMaySteer(caller);
254
+ if (!active(record.view)) this.assertStartableAncestors(path);
255
+ // A detached spawn reserves immediately, but its original task must reach prompt() before steering.
256
+ if (record.view.state === "starting") {
257
+ if (!record.started) throw new Error("Thread start invariant violated");
258
+ await record.started;
259
+ continue;
260
+ }
261
+ if (record.stopRequested && active(record.view))
262
+ throw new Error("Thread is stopping; wait for stopped state before resuming");
263
+ if (record.view.state === "running") {
264
+ await record.driver!.steer(message);
265
+ this.touch(record);
266
+ return this.view(record);
267
+ }
268
+ this.assertCapacity();
269
+ this.start(record, message);
270
+ return this.view(record);
271
+ }
272
+ }
273
+ async wait(
274
+ caller: string,
275
+ path: string,
276
+ timeoutMs?: number,
277
+ signal?: AbortSignal,
278
+ ): Promise<ThreadView> {
279
+ path = canonicalPath(path, caller);
280
+ this.assertAccess(caller, path);
281
+ const record = this.record(path);
282
+ if (!active(record.view)) return this.view(record);
283
+ if (
284
+ timeoutMs !== undefined &&
285
+ (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 3_600_000)
286
+ )
287
+ throw new Error("timeoutMs must be between 0 and 3600000");
288
+ if (signal?.aborted) throw new Error("Waiting cancelled; thread remains running");
289
+ await new Promise<void>((resolve, reject) => {
290
+ let timer: ReturnType<typeof setTimeout> | undefined;
291
+ const finish = (error?: Error) => {
292
+ if (timer) clearTimeout(timer);
293
+ signal?.removeEventListener("abort", cancel);
294
+ error ? reject(error) : resolve();
295
+ };
296
+ const cancel = () => finish(new Error("Waiting cancelled; thread remains running"));
297
+ signal?.addEventListener("abort", cancel, { once: true });
298
+ if (timeoutMs !== undefined) timer = setTimeout(() => finish(), timeoutMs);
299
+ record.run!.then(
300
+ () => finish(),
301
+ (error) => finish(new Error(errorText(error))),
302
+ );
303
+ });
304
+ return this.view(record);
305
+ }
306
+ update(caller: string, message: string): ThreadView {
307
+ const record = this.record(caller);
308
+ if (!active(record.view)) throw new Error("Only a working child may report progress");
309
+ if (!message.trim() || message.length > 8000)
310
+ throw new Error("Progress message must contain 1–8000 characters");
311
+ record.view.status = message;
312
+ this.touch(record);
313
+ this.options.onEvent?.({
314
+ kind: "update",
315
+ thread: this.view(record),
316
+ message,
317
+ recipient: record.view.parent ?? record.view.owner,
318
+ });
319
+ return this.view(record);
320
+ }
321
+ pause(caller: string, reason: string): ThreadView {
322
+ const record = this.record(caller);
323
+ if (!active(record.view)) throw new Error("Only a working child may pause itself");
324
+ record.pauseRequested = true;
325
+ record.view.status = reason.trim() || "Awaiting further input";
326
+ this.touch(record);
327
+ // Remains running until the SDK settles. No interim final answer leaks through wait().
328
+ return this.view(record);
329
+ }
330
+ async stop(caller: string, path: string): Promise<ThreadView> {
331
+ path = canonicalPath(path, caller);
332
+ this.assertAccess(caller, path);
333
+ const record = this.record(path);
334
+ const targets = [...this.records.values()].filter(
335
+ (item) => item === record || (isDescendant(item.view.path, path) && active(item.view)),
336
+ );
337
+ for (const item of targets) {
338
+ item.stopRequested = true;
339
+ item.startup.abort();
340
+ }
341
+ await Promise.all(
342
+ targets.map(async (item) => {
343
+ if (item.driver) await item.driver.abort();
344
+ await item.run;
345
+ item.view.state = "stopped";
346
+ item.view.status = "Stopped; session retained";
347
+ delete item.view.output;
348
+ this.touch(item);
349
+ }),
350
+ );
351
+ return this.view(record);
352
+ }
353
+ async transcript(caller: string, path: string): Promise<string> {
354
+ path = canonicalPath(path, caller);
355
+ this.assertAccess(caller, path, true);
356
+ const driver = await this.ensureDriver(this.record(path), true);
357
+ return JSON.stringify(driver.snapshot(), null, 2);
358
+ }
359
+ async deliver(path: string, content: string): Promise<void> {
360
+ // Restored parents may be idle and unopened; reports still belong in their retained transcript.
361
+ const driver = await this.ensureDriver(this.record(path), true);
362
+ await driver.sendUpdate(content);
363
+ }
364
+ async shutdown(): Promise<void> {
365
+ this.disposed = true;
366
+ this.epoch++;
367
+ const records = [...this.records.values()];
368
+ for (const record of records) {
369
+ record.stopRequested = true;
370
+ record.startup.abort();
371
+ }
372
+ await Promise.all(
373
+ records.map(async (record) => {
374
+ await record.driver?.abort();
375
+ await record.initializing?.catch(() => {});
376
+ await record.run;
377
+ record.driver?.dispose();
378
+ }),
379
+ );
380
+ }
381
+
382
+ private start(record: Record, message: string): void {
383
+ record.pauseRequested = false;
384
+ record.stopRequested = false;
385
+ record.startup = new AbortController();
386
+ record.view.state = "starting";
387
+ record.view.status = "Starting";
388
+ delete record.view.output;
389
+ delete record.view.error;
390
+ const epoch = this.epoch;
391
+ let markStarted!: () => void;
392
+ record.started = new Promise((resolve) => {
393
+ markStarted = resolve;
394
+ });
395
+ record.run = Promise.resolve().then(async () => {
396
+ try {
397
+ const contextReady = this.prepareInheritedContext(record);
398
+ if (contextReady) await abortable(contextReady, record.startup.signal);
399
+ record.startup.signal.throwIfAborted();
400
+ const driver = await this.ensureDriver(record);
401
+ if (record.stopRequested || this.disposed) {
402
+ record.view.state = "stopped";
403
+ return;
404
+ }
405
+ const task = driver.prompt(message);
406
+ record.view.state = "running";
407
+ record.view.status = "Working";
408
+ this.touch(record);
409
+ markStarted();
410
+ await task;
411
+ record.view.state = record.stopRequested
412
+ ? "stopped"
413
+ : record.pauseRequested
414
+ ? "paused"
415
+ : "completed";
416
+ if (record.view.state === "completed") {
417
+ record.view.output = driver.output();
418
+ record.view.status = "Completed; session retained";
419
+ } else if (record.view.state === "stopped")
420
+ record.view.status = "Stopped; session retained";
421
+ } catch (error) {
422
+ record.view.state = record.stopRequested ? "stopped" : "failed";
423
+ record.view.error = errorText(error);
424
+ record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
425
+ } finally {
426
+ markStarted(); // Failed/cancelled initialization must also release callers waiting to steer.
427
+ this.touch(record);
428
+ if (!this.disposed && epoch === this.epoch)
429
+ this.options.onEvent?.({
430
+ kind: "settled",
431
+ thread: this.view(record),
432
+ recipient: record.view.parent ?? record.view.owner,
433
+ });
434
+ }
435
+ });
436
+ this.touch(record);
437
+ }
438
+ private ensureDriver(record: Record, readOnly = false): Promise<AgentDriver> {
439
+ this.assertLive();
440
+ if (record.driver) return Promise.resolve(record.driver);
441
+ if (!record.initializing) {
442
+ const signal =
443
+ readOnly && !active(record.view) ? new AbortController().signal : record.startup.signal;
444
+ const creation = Promise.resolve()
445
+ .then(async () => {
446
+ // Inspection and delivery can initialize a reserved child before start().
447
+ const contextReady = this.prepareInheritedContext(record, readOnly);
448
+ if (contextReady) await abortable(contextReady, signal);
449
+ if (!record.view.sessionFile && record.view.parent && record.view.parent !== "/root") {
450
+ const parentRecord = this.record(record.view.parent);
451
+ if (!parentRecord.driver) await this.ensureDriver(parentRecord, readOnly);
452
+ }
453
+ const options: DriverOptions = {
454
+ path: record.view.path,
455
+ type: record.definition,
456
+ inherited: record.inherited,
457
+ tools: this.options.toolsFor(record.view.path),
458
+ parentPath: record.view.parent,
459
+ sessionFile: record.view.sessionFile,
460
+ signal,
461
+ shouldPause: () => record.pauseRequested,
462
+ onEvent: (event) => {
463
+ if (event.kind === "checkpoint") {
464
+ this.touch(record);
465
+ return;
466
+ }
467
+ if (active(record.view) && !record.pauseRequested) {
468
+ record.view.status = event.text;
469
+ this.touch(record);
470
+ }
471
+ },
472
+ ...(record.sessionLeafId !== undefined ? { sessionLeafId: record.sessionLeafId } : {}),
473
+ };
474
+ return this.options.createDriver(options);
475
+ })
476
+ .then(async (driver) => {
477
+ if (this.disposed || signal.aborted) {
478
+ await driver.abort();
479
+ driver.dispose();
480
+ throw new Error("Driver startup cancelled");
481
+ }
482
+ record.driver = driver;
483
+ record.view.sessionFile = driver.sessionFile;
484
+ if (driver.sessionLeafId !== undefined) record.sessionLeafId = driver.sessionLeafId;
485
+ this.touch(record);
486
+ return driver;
487
+ });
488
+ let initializing!: Promise<AgentDriver>;
489
+ initializing = abortable(creation, signal).catch((error) => {
490
+ if (record.initializing === initializing) record.initializing = undefined;
491
+ throw error;
492
+ });
493
+ record.initializing = initializing;
494
+ }
495
+ return record.initializing;
496
+ }
497
+ private touch(record: Record): void {
498
+ record.view.updatedAt = Date.now();
499
+ if (!this.disposed) this.options.onEvent?.({ kind: "change", thread: this.view(record) });
500
+ }
501
+ private prepareInheritedContext(record: Record, readOnly = false): Promise<void> | undefined {
502
+ if (!record.contextPending) return record.contextReady;
503
+ if (record.contextReady) return record.contextReady;
504
+ if (!record.view.parent || record.view.parent === "/root") {
505
+ record.inherited = inheritContext(this.options.rootSnapshot());
506
+ record.contextPending = false;
507
+ return undefined;
508
+ }
509
+ const parentRecord = this.record(record.view.parent);
510
+ let ready!: Promise<void>;
511
+ ready = this.ensureDriver(parentRecord, readOnly)
512
+ .then((driver) => {
513
+ record.inherited = inheritContext(driver.snapshot());
514
+ record.contextPending = false;
515
+ if (record.contextReady === ready) record.contextReady = undefined;
516
+ this.touch(record);
517
+ })
518
+ .catch((error) => {
519
+ if (record.contextReady === ready) record.contextReady = undefined;
520
+ throw error;
521
+ });
522
+ record.contextReady = ready;
523
+ void ready.catch(() => {});
524
+ return ready;
525
+ }
526
+ private sessionLeafId(record: Record): string | null | undefined {
527
+ const leaf = record.driver?.sessionLeafId;
528
+ return leaf !== undefined ? leaf : record.sessionLeafId;
529
+ }
530
+ private view(record: Record): ThreadView {
531
+ return structuredClone({
532
+ ...record.view,
533
+ sessionFile: record.driver ? record.driver.sessionFile : record.view.sessionFile,
534
+ });
535
+ }
536
+ private record(path: string): Record {
537
+ const record = this.records.get(path);
538
+ if (!record) throw new Error(`Unknown thread ${path}`);
539
+ return record;
540
+ }
541
+ private assertLive(): void {
542
+ if (this.disposed) throw new Error("Thread manager has shut down");
543
+ }
544
+ private assertCallerMaySteer(caller: string): void {
545
+ if (caller !== "/root" && this.record(caller).stopRequested)
546
+ throw new Error("Stopping agents may not steer descendants");
547
+ }
548
+ private assertStartableAncestors(path: string): void {
549
+ for (
550
+ let ancestor = parentPath(path);
551
+ ancestor && ancestor !== "/root";
552
+ ancestor = parentPath(ancestor)
553
+ ) {
554
+ const record = this.record(ancestor);
555
+ if (record.stopRequested || record.view.state === "stopped") {
556
+ throw new Error(`Cannot continue under stopped ancestor ${ancestor}; resume it first`);
557
+ }
558
+ }
559
+ }
560
+ private assertCapacity(): void {
561
+ if (
562
+ [...this.records.values()].filter((record) => active(record.view)).length >=
563
+ (this.options.maxConcurrent ?? 16)
564
+ )
565
+ throw new Error("Concurrent thread limit reached; wait for a thread to settle");
566
+ }
567
+ private assertAccess(caller: string, path: string, self = false): void {
568
+ caller = canonicalPath(caller);
569
+ if (caller === "/root" && path !== "/root") return;
570
+ if (self && path === caller) return;
571
+ if (!isDescendant(path, caller))
572
+ throw new Error(
573
+ `${caller} may address only its descendants (not siblings, unrelated trees or ancestors)`,
574
+ );
575
+ }
576
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+
3
+ const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
4
+ export function canonicalPath(value: string, caller = "/root"): string {
5
+ if (!value || value !== value.trim())
6
+ throw new Error("Agent path must not be empty or contain surrounding whitespace");
7
+ const path = value.startsWith("/") ? value : `${caller}/${value}`;
8
+ const parts = path.slice(1).split("/");
9
+ if (!parts.every((part) => SEGMENT.test(part)) || parts.length > 32) {
10
+ throw new Error(
11
+ "Agent paths require slash-separated names (letters, digits, - or _); no dot segments, escapes, empty segments or trailing slash",
12
+ );
13
+ }
14
+ return path;
15
+ }
16
+ export function parentPath(path: string): string | null {
17
+ canonicalPath(path);
18
+ const last = path.lastIndexOf("/");
19
+ return last === 0 ? null : path.slice(0, last);
20
+ }
21
+ export function isDescendant(path: string, ancestor: string): boolean {
22
+ return path.startsWith(`${ancestor}/`);
23
+ }
24
+
25
+ /** Snapshot conversation, not the parent's prompt/loadout; retain only matched tool exchanges. */
26
+ export function inheritContext(messages: readonly AgentMessage[]): AgentMessage[] {
27
+ const copy = structuredClone(messages);
28
+ const matchedCalls = new Set<string>();
29
+ const matchedResults = new Set<number>();
30
+ const pending = new Map<string, { messageIndex: number; blockIndex: number }[]>();
31
+
32
+ for (const [messageIndex, message] of copy.entries()) {
33
+ if (message.role === "assistant") {
34
+ if (message.stopReason === "error" || message.stopReason === "aborted") continue;
35
+ for (const [blockIndex, block] of message.content.entries()) {
36
+ if (block.type !== "toolCall") continue;
37
+ const queue = pending.get(block.id);
38
+ const occurrence = { messageIndex, blockIndex };
39
+ if (queue) queue.push(occurrence);
40
+ else pending.set(block.id, [occurrence]);
41
+ }
42
+ continue;
43
+ }
44
+ if (message.role !== "toolResult") continue;
45
+ const queue = pending.get(message.toolCallId);
46
+ const occurrence = queue?.shift();
47
+ if (!occurrence) continue;
48
+ matchedCalls.add(`${occurrence.messageIndex}:${occurrence.blockIndex}`);
49
+ matchedResults.add(messageIndex);
50
+ if (queue && !queue.length) pending.delete(message.toolCallId);
51
+ }
52
+
53
+ return copy.flatMap((message, messageIndex): AgentMessage[] => {
54
+ // Only the system prompt/loadout is replaced; custom and shell messages are real conversation context.
55
+ if (message.role === "system") return [];
56
+ if (message.role === "assistant") {
57
+ if (message.stopReason === "error" || message.stopReason === "aborted") return [];
58
+ message.content = message.content.filter(
59
+ (block, blockIndex) =>
60
+ block.type !== "toolCall" || matchedCalls.has(`${messageIndex}:${blockIndex}`),
61
+ );
62
+ if (!message.content.length) return [];
63
+ // A tools-only assistant without remaining calls should not claim a toolUse stop.
64
+ if (
65
+ message.stopReason === "toolUse" &&
66
+ !message.content.some((block) => block.type === "toolCall")
67
+ )
68
+ message.stopReason = "stop";
69
+ }
70
+ if (message.role === "toolResult" && !matchedResults.has(messageIndex)) return [];
71
+ return [message];
72
+ });
73
+ }