pi-subagent-manager 1.10.0 → 1.12.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.
Files changed (95) hide show
  1. package/README.md +9 -9
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +790 -0
  4. package/dist/orch/checklist-integration.js +176 -0
  5. package/dist/orch/context-entries.js +6 -0
  6. package/dist/orch/cost-ledger.js +38 -0
  7. package/dist/orch/diagnostics.js +86 -0
  8. package/dist/orch/extensions.js +66 -0
  9. package/dist/orch/housekeeping-usage.js +22 -0
  10. package/dist/orch/housekeeping.js +248 -0
  11. package/dist/orch/inherited-tools.js +57 -0
  12. package/dist/orch/mailbox.js +195 -0
  13. package/dist/orch/manager.js +970 -0
  14. package/dist/orch/paths.js +69 -0
  15. package/dist/orch/prompt.js +30 -0
  16. package/dist/orch/registry.js +115 -0
  17. package/dist/orch/runtime.js +835 -0
  18. package/dist/orch/tools.js +112 -0
  19. package/dist/orch/transcript.js +165 -0
  20. package/dist/prefs/agent-import.js +188 -0
  21. package/dist/prefs/config.js +878 -0
  22. package/dist/prefs/import-discovery.js +547 -0
  23. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
  24. package/dist/prefs/models.js +56 -0
  25. package/dist/prefs/settings.js +491 -0
  26. package/dist/types.js +1 -0
  27. package/dist/ui/agent-loader.js +63 -0
  28. package/dist/ui/agent-navigation-editor.js +168 -0
  29. package/dist/ui/cost-footer.js +209 -0
  30. package/dist/ui/dialog.js +505 -0
  31. package/dist/ui/import-picker.js +191 -0
  32. package/dist/ui/live-agent-view.js +527 -0
  33. package/dist/ui/model-picker.js +529 -0
  34. package/dist/ui/settings-ui.js +671 -0
  35. package/dist/ui/status-ui.js +470 -0
  36. package/dist/ui/thread-tree.js +142 -0
  37. package/dist/ui/tool-picker.js +331 -0
  38. package/dist/ui/transcript-tool.js +91 -0
  39. package/dist/ui/ui.js +1019 -0
  40. package/package.json +17 -5
  41. package/docs/assets/subagent-manager-demo.gif +0 -0
  42. package/docs/async-lifecycle.md +0 -153
  43. package/docs/custom-agents.md +0 -154
  44. package/docs/default-agents.md +0 -95
  45. package/docs/demo.md +0 -63
  46. package/docs/development.md +0 -74
  47. package/docs/importing-agents.md +0 -41
  48. package/docs/pi-footer.md +0 -128
  49. package/docs/research-claude.md +0 -258
  50. package/docs/research-codex.md +0 -143
  51. package/docs/research-default-agent-models.md +0 -121
  52. package/docs/research-model-audit-2026-10.md +0 -154
  53. package/docs/research-model-roles-coding.md +0 -99
  54. package/docs/research-model-roles-writing.md +0 -78
  55. package/docs/research-researcher-workflow.md +0 -97
  56. package/docs/settings.md +0 -293
  57. package/docs/subagent-extension-limitations.md +0 -98
  58. package/docs/threads.md +0 -73
  59. package/docs/tools-and-ui.md +0 -129
  60. package/src/index.ts +0 -920
  61. package/src/orch/checklist-integration.ts +0 -230
  62. package/src/orch/context-entries.ts +0 -15
  63. package/src/orch/cost-ledger.ts +0 -56
  64. package/src/orch/diagnostics.ts +0 -95
  65. package/src/orch/extensions.ts +0 -83
  66. package/src/orch/housekeeping-usage.ts +0 -47
  67. package/src/orch/housekeeping.ts +0 -348
  68. package/src/orch/inherited-tools.ts +0 -84
  69. package/src/orch/mailbox.ts +0 -261
  70. package/src/orch/manager.ts +0 -1084
  71. package/src/orch/paths.ts +0 -73
  72. package/src/orch/prompt.ts +0 -39
  73. package/src/orch/registry.ts +0 -168
  74. package/src/orch/runtime.ts +0 -1041
  75. package/src/orch/tools.ts +0 -190
  76. package/src/orch/transcript.ts +0 -186
  77. package/src/prefs/agent-import.ts +0 -245
  78. package/src/prefs/config.ts +0 -1017
  79. package/src/prefs/import-discovery.ts +0 -643
  80. package/src/prefs/models.ts +0 -74
  81. package/src/prefs/settings.ts +0 -614
  82. package/src/types.ts +0 -271
  83. package/src/ui/agent-loader.ts +0 -98
  84. package/src/ui/agent-navigation-editor.ts +0 -233
  85. package/src/ui/cost-footer.ts +0 -230
  86. package/src/ui/dialog.ts +0 -678
  87. package/src/ui/import-picker.ts +0 -231
  88. package/src/ui/live-agent-view.ts +0 -600
  89. package/src/ui/model-picker.ts +0 -701
  90. package/src/ui/settings-ui.ts +0 -830
  91. package/src/ui/status-ui.ts +0 -628
  92. package/src/ui/thread-tree.ts +0 -173
  93. package/src/ui/tool-picker.ts +0 -398
  94. package/src/ui/transcript-tool.ts +0 -142
  95. package/src/ui/ui.ts +0 -1407
@@ -0,0 +1,970 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { immutableTranscriptValue } from "./transcript.js";
3
+ import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.js";
4
+ import { DEFAULT_MANAGER_SETTINGS } from "../prefs/settings.js";
5
+ const RECENT_ACTIVITY_LIMIT = 12;
6
+ const active = (view) => view.state === "starting" || view.state === "running";
7
+ const MIN_SPAWN_TIMEOUT_MS = 30_000;
8
+ const MAX_SPAWN_TIMEOUT_MS = 300_000;
9
+ function assertSpawnTimeout(timeoutMs) {
10
+ if (!Number.isInteger(timeoutMs) ||
11
+ timeoutMs < MIN_SPAWN_TIMEOUT_MS ||
12
+ timeoutMs > MAX_SPAWN_TIMEOUT_MS)
13
+ throw new Error(`timeoutMs must be an integer between ${MIN_SPAWN_TIMEOUT_MS} (30s) and ${MAX_SPAWN_TIMEOUT_MS} (5min)`);
14
+ }
15
+ const errorText = (error) => (error instanceof Error ? error.message : String(error));
16
+ function abortable(work, signal) {
17
+ if (signal.aborted) {
18
+ void work.catch(() => { });
19
+ return Promise.reject(signal.reason);
20
+ }
21
+ return new Promise((resolve, reject) => {
22
+ const cancel = () => reject(signal.reason ?? new Error("Startup cancelled"));
23
+ signal.addEventListener("abort", cancel, { once: true });
24
+ work.then((value) => {
25
+ signal.removeEventListener("abort", cancel);
26
+ resolve(value);
27
+ }, (error) => {
28
+ signal.removeEventListener("abort", cancel);
29
+ reject(error);
30
+ });
31
+ });
32
+ }
33
+ export class ThreadManager {
34
+ options;
35
+ records = new Map();
36
+ disposed = false;
37
+ epoch = 0;
38
+ constructor(options) {
39
+ this.options = options;
40
+ }
41
+ setLimits(limits) {
42
+ this.options = { ...this.options, ...limits };
43
+ }
44
+ list() {
45
+ return [...this.records.values()].map((record) => this.view(record));
46
+ }
47
+ reapCandidates(only) {
48
+ this.assertLive();
49
+ const records = [...this.records.values()];
50
+ const eligible = new Set(records
51
+ .filter((record) => !only || only.includes(record.view.path))
52
+ .filter((record) => record.view.state === "completed" && (!record.initializing || record.driver))
53
+ .filter((record) => !records.some((other) => active(other.view) && isDescendant(record.view.path, other.view.path)))
54
+ .map((record) => record.view.path));
55
+ for (const record of records) {
56
+ if (eligible.has(record.view.path))
57
+ continue;
58
+ let parent = record.view.parent;
59
+ while (parent && parent !== "/root") {
60
+ eligible.delete(parent);
61
+ parent = this.records.get(parent)?.view.parent ?? null;
62
+ }
63
+ }
64
+ return records
65
+ .filter((record) => eligible.has(record.view.path))
66
+ .sort((a, b) => a.view.createdAt - b.view.createdAt)
67
+ .map((record) => record.view.path);
68
+ }
69
+ reap(only) {
70
+ const reaped = [];
71
+ for (const path of this.reapCandidates(only)) {
72
+ const record = this.records.get(path);
73
+ this.clearTimeout(record);
74
+ record.detachTranscript?.();
75
+ record.transcriptListeners?.clear();
76
+ record.driver?.dispose();
77
+ this.records.delete(record.view.path);
78
+ reaped.push(record.view.path);
79
+ }
80
+ return reaped;
81
+ }
82
+ scope(caller) {
83
+ caller = canonicalPath(caller);
84
+ return {
85
+ list: () => this.list().filter((thread) => caller === "/root" || thread.path === caller || isDescendant(thread.path, caller)),
86
+ get: (path) => this.get(path, caller),
87
+ output: (path) => this.output(path, caller),
88
+ transcript: (path) => this.transcript(caller, path),
89
+ observeTranscript: (path, listener) => this.observeTranscript(caller, path, listener),
90
+ spawn: (args, signal) => this.spawn(caller, args, signal),
91
+ steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
92
+ wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
93
+ update: (message) => this.update(caller, message),
94
+ pause: (reason) => this.pause(caller, reason),
95
+ stop: (path) => this.stop(caller, path),
96
+ };
97
+ }
98
+ get(path, caller = "/root") {
99
+ path = canonicalPath(path, caller);
100
+ this.assertAccess(caller, path, true);
101
+ if (path === "/root")
102
+ return {
103
+ path,
104
+ parent: null,
105
+ owner: path,
106
+ type: "main",
107
+ state: "running",
108
+ task: "Main Pi session",
109
+ status: "main",
110
+ createdAt: 0,
111
+ updatedAt: Date.now(),
112
+ };
113
+ return this.view(this.record(path));
114
+ }
115
+ output(path, caller = "/root") {
116
+ const view = this.get(path, caller);
117
+ if (view.state === "paused")
118
+ return "";
119
+ return view.output ?? "";
120
+ }
121
+ saved() {
122
+ return [...this.records.values()].map((record) => {
123
+ const current = this.view(record);
124
+ const view = {
125
+ path: current.path,
126
+ parent: current.parent,
127
+ owner: current.owner,
128
+ type: current.type,
129
+ color: current.color,
130
+ icon: current.icon,
131
+ model: current.model,
132
+ thinkingLevel: current.thinkingLevel,
133
+ state: current.state,
134
+ task: current.task,
135
+ status: current.status,
136
+ output: current.output,
137
+ error: current.error,
138
+ createdAt: current.createdAt,
139
+ ...(current.lastStartedAt !== undefined ? { lastStartedAt: current.lastStartedAt } : {}),
140
+ sessionFile: current.sessionFile,
141
+ elapsedMs: record.view.elapsedMs ?? 0,
142
+ inputTokens: record.view.inputTokens ?? 0,
143
+ outputTokens: record.view.outputTokens ?? 0,
144
+ costUsd: record.view.costUsd,
145
+ costId: record.view.costId,
146
+ };
147
+ const sessionLeafId = this.sessionLeafId(record);
148
+ if (sessionLeafId !== undefined)
149
+ view.sessionLeafId = sessionLeafId;
150
+ if (active(view))
151
+ view.status = view.state === "running" ? "Working" : "Starting";
152
+ return {
153
+ view,
154
+ definition: structuredClone(record.definition),
155
+ ...(!view.sessionFile && !record.contextPending
156
+ ? {
157
+ inherited: structuredClone(record.inherited),
158
+ inheritedContextEntries: structuredClone(record.inheritedContextEntries),
159
+ }
160
+ : {}),
161
+ };
162
+ });
163
+ }
164
+ restore(saved) {
165
+ if (this.records.size)
166
+ throw new Error("Restore requires an empty thread registry");
167
+ const restored = new Map();
168
+ for (const item of saved) {
169
+ const savedView = structuredClone(item.view);
170
+ const path = canonicalPath(savedView.path);
171
+ if (path === "/root" ||
172
+ restored.has(path) ||
173
+ !["starting", "running", "paused", "completed", "failed", "stopped"].includes(savedView.state))
174
+ throw new Error("Invalid saved thread registry");
175
+ const { sessionLeafId, ...storedView } = savedView;
176
+ const view = {
177
+ ...storedView,
178
+ costId: storedView.costId ??
179
+ `legacy:${storedView.sessionFile ?? `${storedView.path}:${storedView.createdAt}`}`,
180
+ icon: storedView.icon ?? item.definition.icon,
181
+ updatedAt: Date.now(),
182
+ elapsedMs: storedView.elapsedMs ?? 0,
183
+ inputTokens: storedView.inputTokens ?? 0,
184
+ outputTokens: storedView.outputTokens ?? 0,
185
+ };
186
+ delete view.startedAt;
187
+ if (view.parent !== parentPath(path))
188
+ throw new Error(`Invalid saved parent for ${path}`);
189
+ if (active(view)) {
190
+ view.state = "paused";
191
+ view.status = "Interrupted by reload; send input to resume";
192
+ delete view.output;
193
+ }
194
+ restored.set(path, {
195
+ view,
196
+ definition: structuredClone(item.definition),
197
+ inherited: structuredClone(item.inherited ?? []),
198
+ inheritedContextEntries: structuredClone(item.inheritedContextEntries ?? []),
199
+ contextPending: !view.sessionFile && item.inherited === undefined && view.parent !== null,
200
+ startup: new AbortController(),
201
+ ...(Object.prototype.hasOwnProperty.call(savedView, "sessionLeafId")
202
+ ? { sessionLeafId }
203
+ : {}),
204
+ pauseRequested: false,
205
+ stopRequested: false,
206
+ });
207
+ }
208
+ for (const record of restored.values()) {
209
+ if (record.view.parent && record.view.parent !== "/root" && !restored.has(record.view.parent))
210
+ throw new Error(`Missing saved parent ${record.view.parent}`);
211
+ }
212
+ this.records = restored;
213
+ }
214
+ async spawn(caller, args, signal) {
215
+ this.assertLive();
216
+ if (args.timeoutMs !== undefined)
217
+ assertSpawnTimeout(args.timeoutMs);
218
+ caller = canonicalPath(caller);
219
+ if (caller !== "/root" &&
220
+ (!active(this.record(caller).view) || this.record(caller).stopRequested))
221
+ throw new Error("Only a working agent may spawn children");
222
+ signal?.throwIfAborted();
223
+ const path = canonicalPath(args.path, caller);
224
+ this.assertAccess(caller, path);
225
+ if (path === "/root" || this.records.has(path))
226
+ throw new Error(`Thread ${path} already exists; use agent_steer to resume it`);
227
+ const parent = parentPath(path);
228
+ if (parent && parent !== "/root")
229
+ this.record(parent);
230
+ if (caller !== "/root" && parent !== caller)
231
+ throw new Error("An agent may spawn only its immediate children");
232
+ if (!args.task.trim())
233
+ throw new Error("Task must not be empty");
234
+ const segments = path.slice(1).split("/");
235
+ const level = segments.length + (segments[0] === "root" ? 0 : 1);
236
+ const maxLevels = this.options.maxLevels ?? DEFAULT_MANAGER_SETTINGS.maxLevels;
237
+ if (this.options.maxLevels === undefined && this.options.maxDepth !== undefined
238
+ ? segments.length - 1 > this.options.maxDepth
239
+ : level > maxLevels)
240
+ throw new Error("Agent depth limit reached");
241
+ if (this.records.size >= (this.options.maxThreads ?? DEFAULT_MANAGER_SETTINGS.maxThreads))
242
+ throw new Error("Total thread limit reached");
243
+ this.assertCapacity();
244
+ const type = structuredClone(this.options.getType(args.type));
245
+ const parentRecord = parent && parent !== "/root" ? this.record(parent) : undefined;
246
+ this.assertStartableAncestors(path);
247
+ const inherited = parent === "/root"
248
+ ? inheritContext(this.options.rootSnapshot())
249
+ : parentRecord?.driver
250
+ ? inheritContext(parentRecord.driver.snapshot())
251
+ : [];
252
+ const inheritedContextEntries = structuredClone(parent === "/root"
253
+ ? (this.options.rootContextEntries?.() ?? [])
254
+ : (parentRecord?.driver?.contextEntries?.() ?? []));
255
+ const now = Date.now();
256
+ const record = {
257
+ view: {
258
+ path,
259
+ parent,
260
+ owner: parent ?? caller,
261
+ type: type.name,
262
+ color: type.color,
263
+ icon: type.icon,
264
+ state: "starting",
265
+ task: args.task,
266
+ status: "Starting",
267
+ createdAt: now,
268
+ costId: randomUUID(),
269
+ updatedAt: now,
270
+ elapsedMs: 0,
271
+ inputTokens: 0,
272
+ outputTokens: 0,
273
+ },
274
+ definition: type,
275
+ inherited,
276
+ inheritedContextEntries,
277
+ contextPending: !!(parentRecord && !parentRecord.driver),
278
+ startup: new AbortController(),
279
+ pauseRequested: false,
280
+ stopRequested: false,
281
+ };
282
+ this.records.set(path, record);
283
+ if (record.contextPending)
284
+ this.prepareInheritedContext(record);
285
+ record.async = args.wait === false;
286
+ this.start(record, args.task);
287
+ if (args.timeoutMs !== undefined)
288
+ this.armTimeout(record, args.timeoutMs);
289
+ return args.wait === false ? this.view(record) : this.wait(caller, path, undefined, signal);
290
+ }
291
+ async steer(caller, path, message, timeoutMs) {
292
+ this.assertLive();
293
+ caller = canonicalPath(caller);
294
+ path = canonicalPath(path, caller);
295
+ this.assertAccess(caller, path);
296
+ if (message === undefined && timeoutMs === undefined)
297
+ throw new Error("Provide message, timeoutMs, or both");
298
+ if (timeoutMs !== undefined)
299
+ assertSpawnTimeout(timeoutMs);
300
+ if (message === undefined)
301
+ return this.extendTimeout(caller, path, timeoutMs);
302
+ if (!message.trim())
303
+ throw new Error("Steering message must not be empty");
304
+ const record = this.record(path);
305
+ const rearm = () => {
306
+ if (timeoutMs !== undefined && active(record.view) && !record.stopRequested)
307
+ this.armTimeout(record, timeoutMs);
308
+ return this.view(record);
309
+ };
310
+ for (;;) {
311
+ this.assertLive();
312
+ this.assertCallerMaySteer(caller);
313
+ if (!active(record.view))
314
+ this.assertStartableAncestors(path);
315
+ if (record.view.state === "starting") {
316
+ if (!record.started)
317
+ throw new Error("Thread start invariant violated");
318
+ await record.started;
319
+ continue;
320
+ }
321
+ if (record.stopRequested && active(record.view))
322
+ throw new Error("Thread is stopping; wait for stopped state before resuming");
323
+ if (record.view.state === "running") {
324
+ await record.driver.steer(message);
325
+ this.touch(record);
326
+ return rearm();
327
+ }
328
+ this.assertCapacity();
329
+ record.async = true;
330
+ this.start(record, message);
331
+ return rearm();
332
+ }
333
+ }
334
+ async wait(caller, path, timeoutMs, signal) {
335
+ path = canonicalPath(path, caller);
336
+ this.assertAccess(caller, path);
337
+ const record = this.record(path);
338
+ if (!active(record.view))
339
+ return this.view(record);
340
+ if (timeoutMs !== undefined &&
341
+ (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 3_600_000))
342
+ throw new Error("timeoutMs must be between 0 and 3600000");
343
+ if (signal?.aborted)
344
+ throw new Error("Waiting cancelled; thread remains running");
345
+ await new Promise((resolve, reject) => {
346
+ let timer;
347
+ const finish = (error) => {
348
+ if (timer)
349
+ clearTimeout(timer);
350
+ signal?.removeEventListener("abort", cancel);
351
+ error ? reject(error) : resolve();
352
+ };
353
+ const cancel = () => finish(new Error("Waiting cancelled; thread remains running"));
354
+ signal?.addEventListener("abort", cancel, { once: true });
355
+ if (timeoutMs !== undefined)
356
+ timer = setTimeout(() => finish(), timeoutMs);
357
+ record.run.then(() => finish(), (error) => finish(new Error(errorText(error))));
358
+ });
359
+ return this.view(record);
360
+ }
361
+ update(caller, message) {
362
+ const record = this.record(caller);
363
+ if (!active(record.view))
364
+ throw new Error("Only a working child may report progress");
365
+ if (!message.trim() || message.length > 8000)
366
+ throw new Error("Progress message must contain 1–8000 characters");
367
+ record.view.status = message;
368
+ delete record.view.summary;
369
+ this.touch(record);
370
+ this.emit({
371
+ kind: "update",
372
+ thread: this.view(record),
373
+ message,
374
+ recipient: record.view.parent ?? record.view.owner,
375
+ });
376
+ return this.view(record);
377
+ }
378
+ pause(caller, reason) {
379
+ const record = this.record(caller);
380
+ if (!active(record.view))
381
+ throw new Error("Only a working child may pause itself");
382
+ record.pauseRequested = true;
383
+ record.view.status = reason.trim() || "Awaiting further input";
384
+ delete record.view.summary;
385
+ this.touch(record);
386
+ return this.view(record);
387
+ }
388
+ async stop(caller, path) {
389
+ path = canonicalPath(path, caller);
390
+ this.assertAccess(caller, path);
391
+ const record = this.record(path);
392
+ const targets = [...this.records.values()].filter((item) => item === record || (isDescendant(item.view.path, path) && active(item.view)));
393
+ for (const item of targets) {
394
+ item.stopRequested = true;
395
+ item.startup.abort();
396
+ this.clearTimeout(item);
397
+ }
398
+ await Promise.all(targets.map(async (item) => {
399
+ if (item.driver)
400
+ await item.driver.abort();
401
+ await item.run;
402
+ item.view.state = "stopped";
403
+ item.view.status = "Stopped; session retained";
404
+ delete item.view.output;
405
+ this.touch(item);
406
+ }));
407
+ return this.view(record);
408
+ }
409
+ async transcript(caller, path) {
410
+ path = canonicalPath(path, caller);
411
+ this.assertAccess(caller, path, true);
412
+ const driver = await this.ensureDriver(this.record(path), true);
413
+ return JSON.stringify(driver.snapshot(), null, 2);
414
+ }
415
+ async observeTranscript(caller, path, listener) {
416
+ this.assertLive();
417
+ path = canonicalPath(path, caller);
418
+ this.assertAccess(caller, path, true);
419
+ if (path === "/root")
420
+ throw new Error("Main is not a child transcript observation target");
421
+ const record = this.record(path);
422
+ if (!active(record.view))
423
+ await this.ensureDriver(record, true);
424
+ this.assertLive();
425
+ const listeners = (record.transcriptListeners ??= new Set());
426
+ const registered = (snapshot) => listener(snapshot);
427
+ listeners.add(registered);
428
+ if (record.driver)
429
+ this.attachTranscript(record, record.driver);
430
+ else {
431
+ void this.ensureDriver(record, true).catch((error) => {
432
+ if (this.disposed || !listeners.has(registered))
433
+ return;
434
+ record.observationError = errorText(error);
435
+ this.publishTranscript(record);
436
+ });
437
+ }
438
+ return {
439
+ snapshot: this.transcriptSnapshot(record),
440
+ unsubscribe: () => {
441
+ listeners.delete(registered);
442
+ if (!listeners.size) {
443
+ record.detachTranscript?.();
444
+ record.detachTranscript = undefined;
445
+ record.transcriptSource = undefined;
446
+ }
447
+ },
448
+ };
449
+ }
450
+ extendTimeout(caller, path, timeoutMs) {
451
+ this.assertLive();
452
+ path = canonicalPath(path, caller);
453
+ this.assertAccess(caller, path);
454
+ assertSpawnTimeout(timeoutMs);
455
+ const record = this.record(path);
456
+ if (!active(record.view) || record.stopRequested)
457
+ throw new Error("Only a working agent has a timeout to extend");
458
+ this.armTimeout(record, timeoutMs);
459
+ return this.view(record);
460
+ }
461
+ outstandingAsync() {
462
+ return [...this.records.values()].filter((r) => r.async && active(r.view)).length;
463
+ }
464
+ clearTimeout(record) {
465
+ if (record.timeoutTimer !== undefined)
466
+ clearTimeout(record.timeoutTimer);
467
+ record.timeoutTimer = undefined;
468
+ }
469
+ armTimeout(record, timeoutMs) {
470
+ this.clearTimeout(record);
471
+ record.timeoutTimer = setTimeout(() => {
472
+ record.timeoutTimer = undefined;
473
+ if (this.disposed || !active(record.view) || record.stopRequested)
474
+ return;
475
+ this.emit({
476
+ kind: "timeout",
477
+ thread: this.view(record),
478
+ recipient: record.view.parent ?? record.view.owner,
479
+ timeoutMs,
480
+ recentOutput: this.recentOutput(record),
481
+ });
482
+ }, timeoutMs);
483
+ record.timeoutTimer.unref?.();
484
+ }
485
+ recentOutput(record) {
486
+ const parts = [];
487
+ try {
488
+ const messages = record.driver?.snapshot() ?? [];
489
+ for (const message of messages.slice(-6)) {
490
+ if (message.role !== "assistant")
491
+ continue;
492
+ const content = message.content;
493
+ const text = Array.isArray(content)
494
+ ? content
495
+ .filter((c) => c?.type === "text" && typeof c.text === "string")
496
+ .map((c) => c.text)
497
+ .join("\n")
498
+ : typeof content === "string"
499
+ ? content
500
+ : "";
501
+ if (text.trim())
502
+ parts.push(text.trim());
503
+ }
504
+ }
505
+ catch {
506
+ }
507
+ return parts.slice(-2).join("\n---\n").slice(-2000);
508
+ }
509
+ async deliver(path, content) {
510
+ const driver = await this.ensureDriver(this.record(path), true);
511
+ await driver.sendUpdate(content);
512
+ }
513
+ async shutdown() {
514
+ this.disposed = true;
515
+ this.epoch++;
516
+ const records = [...this.records.values()];
517
+ for (const record of records) {
518
+ record.detachTranscript?.();
519
+ record.detachTranscript = undefined;
520
+ record.transcriptSource = undefined;
521
+ record.transcriptListeners?.clear();
522
+ record.stopRequested = true;
523
+ record.startup.abort();
524
+ this.clearTimeout(record);
525
+ }
526
+ await Promise.all(records.map(async (record) => {
527
+ await record.driver?.abort();
528
+ await record.initializing?.catch(() => { });
529
+ await record.run;
530
+ await record.driver?.dispose();
531
+ }));
532
+ }
533
+ start(record, message) {
534
+ this.freezeElapsed(record);
535
+ record.pauseRequested = false;
536
+ record.stopRequested = false;
537
+ record.startup = new AbortController();
538
+ record.view.state = "starting";
539
+ record.view.status = "Starting";
540
+ record.view.startedAt = Date.now();
541
+ record.view.lastStartedAt = record.view.startedAt;
542
+ delete record.view.output;
543
+ delete record.view.error;
544
+ delete record.view.summary;
545
+ record.runId = (record.runId ?? 0) + 1;
546
+ record.recentActivity = [];
547
+ const epoch = this.epoch;
548
+ let markStarted;
549
+ record.started = new Promise((resolve) => {
550
+ markStarted = resolve;
551
+ });
552
+ record.run = Promise.resolve().then(async () => {
553
+ try {
554
+ const contextReady = this.prepareInheritedContext(record);
555
+ if (contextReady)
556
+ await abortable(contextReady, record.startup.signal);
557
+ record.startup.signal.throwIfAborted();
558
+ const driver = await this.ensureDriver(record);
559
+ if (record.stopRequested || this.disposed) {
560
+ record.view.state = "stopped";
561
+ return;
562
+ }
563
+ const task = driver.prompt(message);
564
+ record.view.state = "running";
565
+ record.view.status = "Working";
566
+ this.touch(record);
567
+ markStarted();
568
+ await task;
569
+ record.view.state = record.stopRequested
570
+ ? "stopped"
571
+ : record.pauseRequested
572
+ ? "paused"
573
+ : "completed";
574
+ if (record.view.state === "completed") {
575
+ record.view.output = driver.output();
576
+ record.view.status = "Completed; session retained";
577
+ }
578
+ else if (record.view.state === "stopped")
579
+ record.view.status = "Stopped; session retained";
580
+ }
581
+ catch (error) {
582
+ record.view.state = record.stopRequested ? "stopped" : "failed";
583
+ record.view.error = errorText(error);
584
+ record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
585
+ }
586
+ finally {
587
+ this.clearTimeout(record);
588
+ this.freezeElapsed(record);
589
+ delete record.view.summary;
590
+ record.liveInputTokens = 0;
591
+ record.liveOutputTokens = 0;
592
+ record.liveCostUsd = undefined;
593
+ markStarted();
594
+ this.touch(record);
595
+ if (!this.disposed && epoch === this.epoch)
596
+ this.emit({
597
+ kind: "settled",
598
+ thread: this.view(record),
599
+ recipient: record.view.parent ?? record.view.owner,
600
+ async: record.async === true,
601
+ });
602
+ }
603
+ });
604
+ this.touch(record);
605
+ }
606
+ ensureDriver(record, readOnly = false) {
607
+ this.assertLive();
608
+ if (record.driver)
609
+ return Promise.resolve(record.driver);
610
+ if (!record.initializing) {
611
+ const signal = readOnly && !active(record.view) ? new AbortController().signal : record.startup.signal;
612
+ let diagnosticDriver;
613
+ const creation = Promise.resolve()
614
+ .then(async () => {
615
+ const contextReady = this.prepareInheritedContext(record, readOnly);
616
+ if (contextReady)
617
+ await abortable(contextReady, signal);
618
+ if (!record.view.sessionFile && record.view.parent && record.view.parent !== "/root") {
619
+ const parentRecord = this.record(record.view.parent);
620
+ if (!parentRecord.driver)
621
+ await this.ensureDriver(parentRecord, readOnly);
622
+ }
623
+ const parentSessionFile = this.lexicalParentSessionFile(record);
624
+ const segments = record.view.path.slice(1).split("/");
625
+ const level = segments.length + (segments[0] === "root" ? 0 : 1);
626
+ const canSpawnChildren = this.options.maxLevels === undefined && this.options.maxDepth !== undefined
627
+ ? segments.length - 1 < this.options.maxDepth
628
+ : level < (this.options.maxLevels ?? DEFAULT_MANAGER_SETTINGS.maxLevels);
629
+ const options = {
630
+ path: record.view.path,
631
+ canSpawnChildren,
632
+ type: record.definition,
633
+ inherited: record.inherited,
634
+ inheritedContextEntries: record.inheritedContextEntries,
635
+ tools: this.options.toolsFor(record.view.path),
636
+ parentPath: record.view.parent,
637
+ sessionFile: record.view.sessionFile,
638
+ signal,
639
+ shouldPause: () => record.pauseRequested,
640
+ onEvent: (event) => {
641
+ if (event.kind === "diagnostic") {
642
+ if (this.disposed ||
643
+ this.records.get(record.view.path) !== record ||
644
+ (diagnosticDriver ? record.driver !== diagnosticDriver : signal.aborted))
645
+ return;
646
+ record.view.diagnostics = [
647
+ ...(record.view.diagnostics ?? []),
648
+ event.diagnostic,
649
+ ].slice(-20);
650
+ this.emit({
651
+ kind: "diagnostic",
652
+ thread: this.view(record),
653
+ diagnostic: event.diagnostic,
654
+ recipient: record.view.parent ?? record.view.owner,
655
+ });
656
+ return;
657
+ }
658
+ if (event.kind === "settings") {
659
+ if (record.view.model !== event.model ||
660
+ record.view.thinkingLevel !== event.thinkingLevel) {
661
+ record.view.model = event.model;
662
+ record.view.thinkingLevel = event.thinkingLevel;
663
+ this.touch(record);
664
+ }
665
+ return;
666
+ }
667
+ if (event.kind === "usage") {
668
+ this.applyUsage(record, event);
669
+ return;
670
+ }
671
+ if (event.kind === "checkpoint") {
672
+ this.touch(record);
673
+ return;
674
+ }
675
+ if (active(record.view) && !record.pauseRequested) {
676
+ record.view.status = event.text;
677
+ this.touch(record);
678
+ this.recordActivity(record, event.detail ? `${event.text} ${event.detail}` : event.text);
679
+ }
680
+ },
681
+ ...(parentSessionFile ? { parentSessionFile } : {}),
682
+ ...(record.sessionLeafId !== undefined ? { sessionLeafId: record.sessionLeafId } : {}),
683
+ };
684
+ return this.options.createDriver(options);
685
+ })
686
+ .then(async (driver) => {
687
+ if (this.disposed || signal.aborted) {
688
+ await driver.abort();
689
+ await driver.dispose();
690
+ throw new Error("Driver startup cancelled");
691
+ }
692
+ record.driver = driver;
693
+ diagnosticDriver = driver;
694
+ record.driverGeneration = (record.driverGeneration ?? 0) + 1;
695
+ record.observationError = undefined;
696
+ if (record.transcriptListeners?.size)
697
+ this.attachTranscript(record, driver);
698
+ record.usageCursor = { input: 0, output: 0 };
699
+ record.liveInputTokens = 0;
700
+ record.liveOutputTokens = 0;
701
+ record.liveCostUsd = undefined;
702
+ record.view.sessionFile = driver.sessionFile;
703
+ if (driver.sessionLeafId !== undefined)
704
+ record.sessionLeafId = driver.sessionLeafId;
705
+ this.touch(record);
706
+ return driver;
707
+ });
708
+ let initializing;
709
+ initializing = abortable(creation, signal).catch((error) => {
710
+ if (record.initializing === initializing)
711
+ record.initializing = undefined;
712
+ throw error;
713
+ });
714
+ record.initializing = initializing;
715
+ }
716
+ return record.initializing;
717
+ }
718
+ attachTranscript(record, driver) {
719
+ if (record.detachTranscript || !record.transcriptListeners?.size)
720
+ return;
721
+ const observation = driver.observeTranscript?.((snapshot) => {
722
+ if (this.disposed || record.driver !== driver || !record.transcriptListeners?.size)
723
+ return;
724
+ record.transcriptSource = snapshot;
725
+ this.publishTranscript(record);
726
+ });
727
+ if (observation) {
728
+ record.transcriptSource = observation.snapshot;
729
+ record.detachTranscript = observation.unsubscribe;
730
+ }
731
+ }
732
+ transcriptSnapshot(record) {
733
+ const source = record.transcriptSource;
734
+ return Object.freeze({
735
+ revision: record.observationRevision ?? 0,
736
+ generation: record.driverGeneration ?? 0,
737
+ messages: source?.messages ?? immutableTranscriptValue(record.driver?.snapshot() ?? record.inherited),
738
+ assistant: source?.assistant ?? null,
739
+ tools: source?.tools ?? Object.freeze([]),
740
+ inheritedCount: source?.inheritedCount ?? record.inherited.length,
741
+ thread: immutableTranscriptValue(this.view(record)),
742
+ ...(record.observationError || source?.error
743
+ ? { error: record.observationError ?? source?.error }
744
+ : {}),
745
+ });
746
+ }
747
+ publishTranscript(record) {
748
+ if (this.disposed || !record.transcriptListeners?.size)
749
+ return;
750
+ record.observationRevision = (record.observationRevision ?? 0) + 1;
751
+ const snapshot = this.transcriptSnapshot(record);
752
+ for (const listener of record.transcriptListeners) {
753
+ try {
754
+ listener(snapshot);
755
+ }
756
+ catch {
757
+ }
758
+ }
759
+ }
760
+ recordActivity(record, line) {
761
+ const recent = (record.recentActivity ??= []);
762
+ recent.push(line.slice(0, 600));
763
+ if (recent.length > RECENT_ACTIVITY_LIMIT)
764
+ recent.splice(0, recent.length - RECENT_ACTIVITY_LIMIT);
765
+ if (!this.options.onActivity || this.disposed)
766
+ return;
767
+ try {
768
+ this.options.onActivity({
769
+ path: record.view.path,
770
+ type: record.view.type,
771
+ task: record.view.task,
772
+ run: record.runId ?? 0,
773
+ recent: [...recent],
774
+ });
775
+ }
776
+ catch {
777
+ }
778
+ }
779
+ setSummary(path, run, summary) {
780
+ const record = this.records.get(path);
781
+ const text = summary.replace(/\s+/g, " ").trim();
782
+ if (this.disposed ||
783
+ !record ||
784
+ !text ||
785
+ record.runId !== run ||
786
+ !active(record.view) ||
787
+ record.pauseRequested ||
788
+ record.stopRequested)
789
+ return false;
790
+ if (record.view.summary === text)
791
+ return true;
792
+ record.view.summary = text;
793
+ if (!this.disposed)
794
+ this.emit({ kind: "metrics", thread: this.view(record) });
795
+ return true;
796
+ }
797
+ clearSummary(path, run) {
798
+ const record = this.records.get(path);
799
+ if (this.disposed || !record || record.runId !== run || record.view.summary === undefined)
800
+ return false;
801
+ delete record.view.summary;
802
+ this.emit({ kind: "metrics", thread: this.view(record) });
803
+ return true;
804
+ }
805
+ clearSummaries() {
806
+ for (const record of this.records.values()) {
807
+ if (record.view.summary === undefined)
808
+ continue;
809
+ delete record.view.summary;
810
+ if (!this.disposed)
811
+ this.emit({ kind: "metrics", thread: this.view(record) });
812
+ }
813
+ }
814
+ emit(event) {
815
+ try {
816
+ this.options.onEvent?.(event);
817
+ }
818
+ catch (error) {
819
+ try {
820
+ if (this.options.onEventError)
821
+ this.options.onEventError(error, event);
822
+ else
823
+ console.warn(`Subagent ${event.kind} notification failed: ${errorText(error)}`);
824
+ }
825
+ catch {
826
+ }
827
+ }
828
+ }
829
+ touch(record) {
830
+ record.view.updatedAt = Date.now();
831
+ this.publishTranscript(record);
832
+ if (!this.disposed)
833
+ this.emit({ kind: "change", thread: this.view(record) });
834
+ }
835
+ applyUsage(record, event) {
836
+ const cursor = record.usageCursor ?? { input: 0, output: 0 };
837
+ const costUsd = event.costUsd !== undefined && Number.isFinite(event.costUsd) && event.costUsd >= 0
838
+ ? Math.max(0, event.costUsd - (cursor.costUsd ?? 0))
839
+ : undefined;
840
+ if (event.partial) {
841
+ const input = Math.max(0, event.inputTokens - cursor.input);
842
+ const output = Math.max(0, event.outputTokens - cursor.output);
843
+ if (input === record.liveInputTokens &&
844
+ output === record.liveOutputTokens &&
845
+ costUsd === record.liveCostUsd)
846
+ return;
847
+ record.liveInputTokens = input;
848
+ record.liveOutputTokens = output;
849
+ record.liveCostUsd = costUsd;
850
+ if (!this.disposed)
851
+ this.emit({ kind: "metrics", thread: this.view(record) });
852
+ return;
853
+ }
854
+ record.view.inputTokens =
855
+ (record.view.inputTokens ?? 0) + Math.max(0, event.inputTokens - cursor.input);
856
+ record.view.outputTokens =
857
+ (record.view.outputTokens ?? 0) + Math.max(0, event.outputTokens - cursor.output);
858
+ if (costUsd !== undefined)
859
+ record.view.costUsd = (record.view.costUsd ?? 0) + costUsd;
860
+ record.usageCursor = {
861
+ input: event.inputTokens,
862
+ output: event.outputTokens,
863
+ costUsd: event.costUsd ?? cursor.costUsd,
864
+ };
865
+ record.liveInputTokens = 0;
866
+ record.liveOutputTokens = 0;
867
+ record.liveCostUsd = undefined;
868
+ this.touch(record);
869
+ }
870
+ freezeElapsed(record) {
871
+ const startedAt = record.view.startedAt;
872
+ if (startedAt === undefined)
873
+ return;
874
+ record.view.elapsedMs = (record.view.elapsedMs ?? 0) + Math.max(0, Date.now() - startedAt);
875
+ delete record.view.startedAt;
876
+ }
877
+ prepareInheritedContext(record, readOnly = false) {
878
+ if (!record.contextPending)
879
+ return record.contextReady;
880
+ if (record.contextReady)
881
+ return record.contextReady;
882
+ if (!record.view.parent || record.view.parent === "/root") {
883
+ record.inherited = inheritContext(this.options.rootSnapshot());
884
+ record.inheritedContextEntries = structuredClone(this.options.rootContextEntries?.() ?? []);
885
+ record.contextPending = false;
886
+ return undefined;
887
+ }
888
+ const parentRecord = this.record(record.view.parent);
889
+ let ready;
890
+ ready = this.ensureDriver(parentRecord, readOnly)
891
+ .then((driver) => {
892
+ record.inherited = inheritContext(driver.snapshot());
893
+ record.inheritedContextEntries = structuredClone(driver.contextEntries?.() ?? []);
894
+ record.contextPending = false;
895
+ if (record.contextReady === ready)
896
+ record.contextReady = undefined;
897
+ this.touch(record);
898
+ })
899
+ .catch((error) => {
900
+ if (record.contextReady === ready)
901
+ record.contextReady = undefined;
902
+ throw error;
903
+ });
904
+ record.contextReady = ready;
905
+ void ready.catch(() => { });
906
+ return ready;
907
+ }
908
+ sessionLeafId(record) {
909
+ const leaf = record.driver?.sessionLeafId;
910
+ return leaf !== undefined ? leaf : record.sessionLeafId;
911
+ }
912
+ lexicalParentSessionFile(record) {
913
+ const parent = record.view.parent;
914
+ if (!parent || parent === "/root")
915
+ return undefined;
916
+ const parentRecord = this.records.get(parent);
917
+ if (!parentRecord)
918
+ return undefined;
919
+ return parentRecord.driver?.sessionFile ?? parentRecord.view.sessionFile;
920
+ }
921
+ view(record) {
922
+ const view = structuredClone({
923
+ ...record.view,
924
+ sessionFile: record.driver ? record.driver.sessionFile : record.view.sessionFile,
925
+ });
926
+ if (record.liveInputTokens)
927
+ view.inputTokens = (view.inputTokens ?? 0) + record.liveInputTokens;
928
+ if (record.liveOutputTokens)
929
+ view.outputTokens = (view.outputTokens ?? 0) + record.liveOutputTokens;
930
+ if (record.liveCostUsd !== undefined)
931
+ view.costUsd = (view.costUsd ?? 0) + record.liveCostUsd;
932
+ return view;
933
+ }
934
+ record(path) {
935
+ const record = this.records.get(path);
936
+ if (!record)
937
+ throw new Error(`Unknown thread ${path}`);
938
+ return record;
939
+ }
940
+ assertLive() {
941
+ if (this.disposed)
942
+ throw new Error("Thread manager has shut down");
943
+ }
944
+ assertCallerMaySteer(caller) {
945
+ if (caller !== "/root" && this.record(caller).stopRequested)
946
+ throw new Error("Stopping agents may not steer descendants");
947
+ }
948
+ assertStartableAncestors(path) {
949
+ for (let ancestor = parentPath(path); ancestor && ancestor !== "/root"; ancestor = parentPath(ancestor)) {
950
+ const record = this.record(ancestor);
951
+ if (record.stopRequested || record.view.state === "stopped") {
952
+ throw new Error(`Cannot continue under stopped ancestor ${ancestor}; resume it first`);
953
+ }
954
+ }
955
+ }
956
+ assertCapacity() {
957
+ if ([...this.records.values()].filter((record) => active(record.view)).length >=
958
+ (this.options.maxConcurrent ?? DEFAULT_MANAGER_SETTINGS.maxConcurrent))
959
+ throw new Error("Concurrent thread limit reached; wait for a thread to settle");
960
+ }
961
+ assertAccess(caller, path, self = false) {
962
+ caller = canonicalPath(caller);
963
+ if (caller === "/root" && path !== "/root")
964
+ return;
965
+ if (self && path === caller)
966
+ return;
967
+ if (!isDescendant(path, caller))
968
+ throw new Error(`${caller} may address only its descendants (not siblings, unrelated trees or ancestors)`);
969
+ }
970
+ }