pi-subagent-manager 0.16.0 → 0.17.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/docs/settings.md CHANGED
@@ -76,6 +76,8 @@ The Labs preview shows every family's running animation frames and completed, pa
76
76
 
77
77
  When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent for an automatic summary. The summary is a main-thread response, so child notifications do not become the final visible message. Progress updates do not trigger summaries, and active main-agent work is not interrupted. **Subagent Mode Off** suppresses automatic summaries even if this setting is enabled.
78
78
 
79
+ With Final Recap on, async completion events no longer wake the main agent one by one; the recap turn starts once every outstanding async agent has reported (spawn-timeout events still wake it).
80
+
79
81
  **Enabling Final Recap may cause extra model turns and uses more tokens and context.** Leave it off if you prefer to inspect results manually in `/agents tree` or request a summary yourself.
80
82
 
81
83
  ## Model Picking (`modelSelection`)
@@ -1,13 +1,17 @@
1
1
  # Tools and UI
2
2
 
3
+ ## Tool picker
4
+
5
+ The allow/block tool picker lists session tools flat, except MCP tools named `mcp__<mcp>__<tool>`: those are grouped under one `mcp__<mcp>` row, collapsed by default. The row shows `[x]`, `[ ]` or `[-]` (mixed) and Enter toggles every tool in the group. Right expands the group, Left collapses it (Left on a child also collapses and selects the group). While searching, matching groups are expanded automatically.
6
+
3
7
  ## Model-facing tools
4
8
 
5
9
  | Tool | Purpose |
6
10
  | -------------- | ---------------------------------------------------- |
7
11
  | `agent_types` | Names, descriptions, resolved models and thinking |
8
- | `agent_spawn` | Start `{path, type, task, wait?}`. Waits by default. |
12
+ | `agent_spawn` | Start `{path, type, task, wait?, timeoutMs?}`. Waits by default. |
9
13
  | `agent_wait` | Wait for settlement; optional `timeoutMs` |
10
- | `agent_steer` | Send `{path, message}`; queues input or resumes |
14
+ | `agent_steer` | Send `{path, message?, timeoutMs?}`; queues/resumes and/or re-arms timeout|
11
15
  | `agent_status` | Inspect one path or list visible threads |
12
16
  | `agent_update` | Child: report progress |
13
17
  | `agent_pause` | Child: pause without an answer |
@@ -30,7 +34,9 @@ are omitted. Spawning under another parent path can change inherited settings.
30
34
 
31
35
  Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
32
36
 
33
- Child progress and completion notifications are retained in the main agent's context without adding visible chat messages. By default they do not start another turn, keeping the main agent's final response last in the conversation even when detached children finish later. The opt-in **[labs] Final Recap** setting asks an idle main agent to summarize newly completed or failed asynchronous agents; results arriving during a summary are handled after that summary finishes. Progress updates and foreground results do not trigger summaries. Enabling it uses more tokens and context. Use the Agents widget, `/agents tree`, or `agent_output` to inspect child status and answers.
37
+ Child progress and completion notifications are retained in the main agent's context without adding visible chat messages. When a detached (`wait: false`) agent completes, fails or is stopped, the main agent receives a message event that starts a new turn if it is idle (or right after its current turn settles), so it never has to poll. Progress updates and foreground results do not start a turn. The opt-in **[labs] Final Recap** setting changes this: completion messages for async agents are recorded without waking the main agent, and once **all outstanding async agents have reported**, one recap turn summarizes them. Enabling it uses more tokens and context. Use the Agents widget, `/agents tree`, or `agent_output` to inspect child status and answers.
38
+
39
+ `agent_spawn` accepts an optional `timeoutMs` (30000–300000, i.e. 30s–5min; out-of-range values are rejected; no timeout when omitted). If the child is still running when it elapses, the parent receives an event (always waking an idle main agent, even in recap mode) with the child's state, status, elapsed time, tokens and recent output. The child is **not** stopped; the parent decides to wait, steer or stop it. The timer is cleared when the child completes, fails, stops or is cancelled, and on session shutdown. It is not re-armed when a child is later resumed with `agent_steer`. `agent_steer` also accepts `timeoutMs` (same 30s–5min range) and `message` is then optional: `timeoutMs` alone only re-arms a running child's timer from now (no steering or resume; error if the child is not running), e.g. after a timeout event shows it is still progressing; with both, the child is steered/resumed and the timer re-armed. At least one of the two is required.
34
40
 
35
41
  ## Parallel and nested work
36
42
 
@@ -41,26 +47,26 @@ Child progress and completion notifications are retained in the main agent's con
41
47
 
42
48
  ## Commands
43
49
 
44
- | Command | Does |
45
- | ----------------------------- | ---------------------------------------------------------------------------------- |
46
- | `/agents`, `/agents settings` | [Settings](settings.md) dialog. **Agent definitions** jumps to the type editor. |
47
- | `/agents types` | Type browser and editor — see [custom agents](custom-agents.md#editing-in-the-tui) |
48
- | `/agents tree [path]` | Live full tree; optional path preselects. |
49
- | `/agents import` | [Import picker](importing-agents.md) |
50
- | `/agents reload` | Reload definitions and settings; show diagnostics |
50
+ | Command | Does |
51
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
52
+ | `/agents`, `/agents settings` | [Settings](settings.md) dialog. **Agent definitions** jumps to the type editor. |
53
+ | `/agents types` | Type browser and editor — see [custom agents](custom-agents.md#editing-in-the-tui) |
54
+ | `/agents tree [path]` | Live full tree; optional path preselects. |
55
+ | `/agents import` | [Import picker](importing-agents.md) |
56
+ | `/agents reload` | Reload definitions and settings; show diagnostics |
51
57
  | `/agents reap` | Show the eligible count and a Confirm/Cancel dialog, then forget completed agents and free retained-thread slots. Active parents and ancestors of retained threads are preserved; reaped agents cannot be resumed. Session files are not deleted. |
52
58
 
53
59
  ### `/agents tree` keys
54
60
 
55
- | Key | Action |
56
- | ----------- | ----------------- |
57
- | ↑↓ | Select |
58
- | ←→ | Collapse / expand |
59
- | PgUp / PgDn | Scroll |
60
- | Enter | Watch thread; Main returns to the editor |
61
+ | Key | Action |
62
+ | ----------- | ------------------------------------------------- |
63
+ | ↑↓ | Select |
64
+ | ←→ | Collapse / expand |
65
+ | PgUp / PgDn | Scroll |
66
+ | Enter | Watch thread; Main returns to the editor |
61
67
  | i | Existing actions: steer, stop, output, transcript |
62
- | Esc | Watcher → saved tree → Main |
63
- | Ctrl+Q | Return directly to Main |
68
+ | Esc | Watcher → saved tree → Main |
69
+ | Ctrl+Q | Return directly to Main |
64
70
 
65
71
  Refreshes every second and keeps your selection, collapse state and scroll position.
66
72
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -20,10 +20,13 @@ import type { SavedThread, ThreadEvent } from "./types.ts";
20
20
  const REGISTRY_ENTRY = "pi-subagent:registry:v1";
21
21
  const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
22
22
  const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
23
+ const ROOT_WAKE_MESSAGE = "pi-subagent:wake";
23
24
  type RootNotification = {
24
25
  rootSessionId: string;
25
26
  content: string;
26
27
  finalRecap?: boolean;
28
+ /** Start a main-agent turn so it reacts to this event (async completion, spawn timeout). */
29
+ trigger?: boolean;
27
30
  details: { mailboxId: string; path: string; state: string };
28
31
  };
29
32
 
@@ -57,7 +60,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
57
60
  let summaryRunning = false;
58
61
  let suspendingSummaries = false;
59
62
  let summaryTimer: ReturnType<typeof setTimeout> | undefined;
63
+ let wakeRequested = false;
64
+ let wakeTimer: ReturnType<typeof setTimeout> | undefined;
65
+ const cancelWake = () => {
66
+ if (wakeTimer !== undefined) clearTimeout(wakeTimer);
67
+ wakeTimer = undefined;
68
+ wakeRequested = false;
69
+ };
60
70
  const cancelSummary = () => {
71
+ cancelWake();
61
72
  if (summaryTimer !== undefined) clearTimeout(summaryTimer);
62
73
  summaryTimer = undefined;
63
74
  summaryRunning = false;
@@ -184,6 +195,30 @@ export default function piSubagent(pi: ExtensionAPI): void {
184
195
  },
185
196
  { triggerTurn: false },
186
197
  );
198
+ if (notification.trigger === true) wakeRequested = true;
199
+ };
200
+ /** Wake an idle main agent once for all pending async events (coalesced, after the settle boundary). */
201
+ const scheduleWake = (ctx: ExtensionContext) => {
202
+ if (!wakeRequested || wakeTimer !== undefined || limits.subagentMode === "off") return;
203
+ const currentGeneration = generation;
204
+ wakeTimer = setTimeout(() => {
205
+ wakeTimer = undefined;
206
+ if (currentGeneration !== generation || context?.sessionManager !== ctx.sessionManager ||
207
+ limits.subagentMode === "off" || suspendingSummaries || !wakeRequested) return;
208
+ if (ctx.isIdle() === false) return; // agent_settled reschedules
209
+ wakeRequested = false;
210
+ try {
211
+ pi.sendMessage({
212
+ customType: ROOT_WAKE_MESSAGE,
213
+ content: "Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
214
+ "React: collect results with agent_output, and for a timeout event decide to wait, steer, stop or re-arm with agent_steer timeoutMs.",
215
+ display: false,
216
+ details: {},
217
+ }, { triggerTurn: true });
218
+ } catch (error) {
219
+ warnDelivery(error);
220
+ }
221
+ }, 0);
187
222
  };
188
223
  const pendingSummaries = (ctx: ExtensionContext) => {
189
224
  const entries = ctx.sessionManager.getBranch();
@@ -203,14 +238,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
203
238
  };
204
239
  const scheduleSummary = (ctx: ExtensionContext) => {
205
240
  if (!limits.finalRecap || limits.subagentMode === "off" || summaryRunning || suspendingSummaries ||
206
- summaryTimer !== undefined || ctx.isIdle() === false || !pendingSummaries(ctx).length) return;
241
+ summaryTimer !== undefined || ctx.isIdle() === false || (manager?.outstandingAsync() ?? 0) > 0 || !pendingSummaries(ctx).length) return;
207
242
  const currentGeneration = generation;
208
243
  // Coalesce siblings finishing together and leave the settlement boundary before
209
244
  // starting a new turn. Recheck settings/session/idle state after the deferral.
210
245
  summaryTimer = setTimeout(() => {
211
246
  summaryTimer = undefined;
212
247
  if (currentGeneration !== generation || context?.sessionManager !== ctx.sessionManager ||
213
- !limits.finalRecap || limits.subagentMode === "off" || suspendingSummaries || ctx.isIdle() === false) return;
248
+ !limits.finalRecap || limits.subagentMode === "off" || suspendingSummaries || ctx.isIdle() === false ||
249
+ (manager?.outstandingAsync() ?? 0) > 0) return;
214
250
  const notifications = pendingSummaries(ctx);
215
251
  if (!notifications.length) return;
216
252
  summaryRunning = true;
@@ -254,6 +290,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
254
290
  delivered.add(notification.details.mailboxId);
255
291
  }
256
292
  }
293
+ scheduleWake(ctx);
257
294
  scheduleSummary(ctx);
258
295
  };
259
296
  pi.on("agent_settled", async (_event, ctx) => {
@@ -265,22 +302,33 @@ export default function piSubagent(pi: ExtensionAPI): void {
265
302
  const delivery = (event: ThreadEvent) => {
266
303
  if (event.kind === "change" || event.kind === "metrics") return;
267
304
  const thread = event.thread;
305
+ const fmtMs = (ms: number) => `${Math.round(ms / 1000)}s`;
306
+ const elapsed = (thread.elapsedMs ?? 0) + (thread.startedAt ? Date.now() - thread.startedAt : 0);
268
307
  const message =
269
308
  event.kind === "update"
270
309
  ? `Progress from ${thread.path}: ${event.message}`
310
+ : event.kind === "timeout"
311
+ ? `Agent ${thread.path} hit its ${fmtMs(event.timeoutMs)} spawn timeout and is STILL RUNNING (not stopped). ` +
312
+ `State: ${thread.state}; status: ${thread.status}; elapsed: ${fmtMs(elapsed)}; ` +
313
+ `tokens: ${thread.inputTokens ?? 0} in / ${thread.outputTokens ?? 0} out.\n` +
314
+ `Recent output:\n${event.recentOutput || "(none yet)"}\n` +
315
+ "Decide: agent_steer with timeoutMs only (no message) to be notified again later without disturbing it, agent_wait for it, agent_steer to redirect, agent_stop to cancel, or let it continue."
271
316
  : thread.state === "completed"
272
317
  ? `Agent ${thread.path} completed. Final answer:\n${thread.output?.slice(0, 16000) ?? "(no text)"}${(thread.output?.length ?? 0) > 16000 ? "\n[Output truncated; use agent_output for more.]" : ""}`
273
318
  : `Agent ${thread.path} is ${thread.state}: ${thread.status}. ${thread.state === "paused" ? "No answer handback; send input to resume the same session." : "Session retained for further input."}`;
274
319
  try {
275
320
  if (event.recipient === "/root") {
321
+ const recap = limits.finalRecap && !suspendingSummaries && event.kind === "settled" &&
322
+ event.async && ["completed", "failed", "stopped"].includes(thread.state);
276
323
  const notification: RootNotification = {
277
324
  rootSessionId: requireContext().sessionManager.getSessionId(),
278
325
  content: message,
279
326
  // Foreground results already handled by a busy main thread do not need
280
327
  // another turn. Completions during a summary do need a follow-up summary.
281
- finalRecap: limits.finalRecap && !suspendingSummaries && event.kind === "settled" &&
282
- (thread.state === "completed" || thread.state === "failed") &&
283
- (requireContext().isIdle() || summaryRunning),
328
+ finalRecap: recap,
329
+ // Recap mode defers the turn until every outstanding async agent has reported.
330
+ trigger: !suspendingSummaries && (event.kind === "timeout" ||
331
+ (event.kind === "settled" && event.async && !recap)),
284
332
  details: {
285
333
  mailboxId: randomUUID(),
286
334
  path: thread.path,
@@ -34,6 +34,9 @@ interface Record {
34
34
  /** In-progress message usage. Shown live, never persisted. */
35
35
  liveInputTokens?: number;
36
36
  liveOutputTokens?: number;
37
+ /** Detached (spawned with wait:false): completion is reported as an event. */
38
+ async?: boolean;
39
+ timeoutTimer?: ReturnType<typeof setTimeout>;
37
40
  pauseRequested: boolean;
38
41
  stopRequested: boolean;
39
42
  observationRevision?: number;
@@ -45,6 +48,18 @@ interface Record {
45
48
  }
46
49
  const active = (view: Pick<ThreadView, "state">) =>
47
50
  view.state === "starting" || view.state === "running";
51
+ export const MIN_SPAWN_TIMEOUT_MS = 30_000;
52
+ export const MAX_SPAWN_TIMEOUT_MS = 300_000;
53
+ function assertSpawnTimeout(timeoutMs: number): void {
54
+ if (
55
+ !Number.isInteger(timeoutMs) ||
56
+ timeoutMs < MIN_SPAWN_TIMEOUT_MS ||
57
+ timeoutMs > MAX_SPAWN_TIMEOUT_MS
58
+ )
59
+ throw new Error(
60
+ `timeoutMs must be an integer between ${MIN_SPAWN_TIMEOUT_MS} (30s) and ${MAX_SPAWN_TIMEOUT_MS} (5min)`,
61
+ );
62
+ }
48
63
  const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
49
64
 
50
65
  function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
@@ -119,6 +134,7 @@ export class ThreadManager {
119
134
  const reaped: string[] = [];
120
135
  for (const path of this.reapCandidates(only)) {
121
136
  const record = this.records.get(path)!;
137
+ this.clearTimeout(record);
122
138
  record.detachTranscript?.();
123
139
  record.transcriptListeners?.clear();
124
140
  record.driver?.dispose();
@@ -142,7 +158,7 @@ export class ThreadManager {
142
158
  transcript: (path) => this.transcript(caller, path),
143
159
  observeTranscript: (path, listener) => this.observeTranscript(caller, path, listener),
144
160
  spawn: (args, signal) => this.spawn(caller, args, signal),
145
- steer: (path, message) => this.steer(caller, path, message),
161
+ steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
146
162
  wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
147
163
  update: (message) => this.update(caller, message),
148
164
  pause: (reason) => this.pause(caller, reason),
@@ -260,10 +276,11 @@ export class ThreadManager {
260
276
 
261
277
  async spawn(
262
278
  caller: string,
263
- args: { path: string; type: string; task: string; wait?: boolean },
279
+ args: { path: string; type: string; task: string; wait?: boolean; timeoutMs?: number },
264
280
  signal?: AbortSignal,
265
281
  ): Promise<ThreadView> {
266
282
  this.assertLive();
283
+ if (args.timeoutMs !== undefined) assertSpawnTimeout(args.timeoutMs);
267
284
  caller = canonicalPath(caller);
268
285
  if (
269
286
  caller !== "/root" &&
@@ -330,17 +347,37 @@ export class ThreadManager {
330
347
  };
331
348
  this.records.set(path, record);
332
349
  if (record.contextPending) this.prepareInheritedContext(record);
350
+ record.async = args.wait === false;
333
351
  this.start(record, args.task);
352
+ if (args.timeoutMs !== undefined) this.armTimeout(record, args.timeoutMs);
334
353
  return args.wait === false ? this.view(record) : this.wait(caller, path, undefined, signal);
335
354
  }
336
355
 
337
- async steer(caller: string, path: string, message: string): Promise<ThreadView> {
356
+ /**
357
+ * Steer/resume a thread and/or re-arm its report-only timeout.
358
+ * timeoutMs without message only re-arms (the child must be running); both does steer then re-arm.
359
+ */
360
+ async steer(
361
+ caller: string,
362
+ path: string,
363
+ message?: string,
364
+ timeoutMs?: number,
365
+ ): Promise<ThreadView> {
338
366
  this.assertLive();
339
367
  caller = canonicalPath(caller);
340
368
  path = canonicalPath(path, caller);
341
369
  this.assertAccess(caller, path);
370
+ if (message === undefined && timeoutMs === undefined)
371
+ throw new Error("Provide message, timeoutMs, or both");
372
+ if (timeoutMs !== undefined) assertSpawnTimeout(timeoutMs);
373
+ if (message === undefined) return this.extendTimeout(caller, path, timeoutMs!);
342
374
  if (!message.trim()) throw new Error("Steering message must not be empty");
343
375
  const record = this.record(path);
376
+ const rearm = (): ThreadView => {
377
+ if (timeoutMs !== undefined && active(record.view) && !record.stopRequested)
378
+ this.armTimeout(record, timeoutMs);
379
+ return this.view(record);
380
+ };
344
381
  for (;;) {
345
382
  this.assertLive();
346
383
  this.assertCallerMaySteer(caller);
@@ -356,11 +393,11 @@ export class ThreadManager {
356
393
  if (record.view.state === "running") {
357
394
  await record.driver!.steer(message);
358
395
  this.touch(record);
359
- return this.view(record);
396
+ return rearm();
360
397
  }
361
398
  this.assertCapacity();
362
399
  this.start(record, message);
363
- return this.view(record);
400
+ return rearm();
364
401
  }
365
402
  }
366
403
  async wait(
@@ -430,6 +467,7 @@ export class ThreadManager {
430
467
  for (const item of targets) {
431
468
  item.stopRequested = true;
432
469
  item.startup.abort();
470
+ this.clearTimeout(item);
433
471
  }
434
472
  await Promise.all(
435
473
  targets.map(async (item) => {
@@ -486,6 +524,63 @@ export class ThreadManager {
486
524
  },
487
525
  };
488
526
  }
527
+ /** Re-arm a running child's report-only timeout from now (replaces any pending timer). */
528
+ extendTimeout(caller: string, path: string, timeoutMs: number): ThreadView {
529
+ this.assertLive();
530
+ path = canonicalPath(path, caller);
531
+ this.assertAccess(caller, path);
532
+ assertSpawnTimeout(timeoutMs);
533
+ const record = this.record(path);
534
+ if (!active(record.view) || record.stopRequested)
535
+ throw new Error("Only a working agent has a timeout to extend");
536
+ this.armTimeout(record, timeoutMs);
537
+ return this.view(record);
538
+ }
539
+ /** Number of detached agents still working; recap waits for this to reach zero. */
540
+ outstandingAsync(): number {
541
+ return [...this.records.values()].filter((r) => r.async && active(r.view)).length;
542
+ }
543
+ private clearTimeout(record: Record): void {
544
+ if (record.timeoutTimer !== undefined) clearTimeout(record.timeoutTimer);
545
+ record.timeoutTimer = undefined;
546
+ }
547
+ private armTimeout(record: Record, timeoutMs: number): void {
548
+ this.clearTimeout(record);
549
+ record.timeoutTimer = setTimeout(() => {
550
+ record.timeoutTimer = undefined;
551
+ if (this.disposed || !active(record.view) || record.stopRequested) return;
552
+ this.emit({
553
+ kind: "timeout",
554
+ thread: this.view(record),
555
+ recipient: record.view.parent ?? record.view.owner,
556
+ timeoutMs,
557
+ recentOutput: this.recentOutput(record),
558
+ });
559
+ }, timeoutMs);
560
+ record.timeoutTimer.unref?.();
561
+ }
562
+ private recentOutput(record: Record): string {
563
+ const parts: string[] = [];
564
+ try {
565
+ const messages = record.driver?.snapshot() ?? [];
566
+ for (const message of messages.slice(-6)) {
567
+ if (message.role !== "assistant") continue;
568
+ const content = message.content as unknown;
569
+ const text = Array.isArray(content)
570
+ ? content
571
+ .filter((c: any) => c?.type === "text" && typeof c.text === "string")
572
+ .map((c: any) => c.text)
573
+ .join("\n")
574
+ : typeof content === "string"
575
+ ? content
576
+ : "";
577
+ if (text.trim()) parts.push(text.trim());
578
+ }
579
+ } catch {
580
+ /* best effort */
581
+ }
582
+ return parts.slice(-2).join("\n---\n").slice(-2000);
583
+ }
489
584
  async deliver(path: string, content: string): Promise<void> {
490
585
  // Restored parents may be idle and unopened; reports still belong in their retained transcript.
491
586
  const driver = await this.ensureDriver(this.record(path), true);
@@ -502,6 +597,7 @@ export class ThreadManager {
502
597
  record.transcriptListeners?.clear();
503
598
  record.stopRequested = true;
504
599
  record.startup.abort();
600
+ this.clearTimeout(record);
505
601
  }
506
602
  await Promise.all(
507
603
  records.map(async (record) => {
@@ -560,6 +656,7 @@ export class ThreadManager {
560
656
  record.view.error = errorText(error);
561
657
  record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
562
658
  } finally {
659
+ this.clearTimeout(record);
563
660
  this.freezeElapsed(record);
564
661
  record.liveInputTokens = 0;
565
662
  record.liveOutputTokens = 0;
@@ -570,6 +667,7 @@ export class ThreadManager {
570
667
  kind: "settled",
571
668
  thread: this.view(record),
572
669
  recipient: record.view.parent ?? record.view.owner,
670
+ async: record.async === true,
573
671
  });
574
672
  }
575
673
  });
@@ -17,7 +17,7 @@ export function subagentPrompt(settings: ManagerSettings): string | undefined {
17
17
  policy,
18
18
  "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
19
19
  waitingPolicy,
20
- "Use agent_status to inspect and agent_output for full results. Detached notifications do not resume your turn.",
20
+ "Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. When a timeout event shows a child still progressing, call agent_steer with only timeoutMs (no message; re-arms without steering) to re-arm it, or agent_wait/agent_steer/agent_stop.",
21
21
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
22
22
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
23
23
  ].join("\n");
package/src/orch/tools.ts CHANGED
@@ -81,7 +81,7 @@ export function agentTools(
81
81
  ),
82
82
  make(
83
83
  "agent_spawn",
84
- "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached. For parallel work, spawn every independent sibling with wait:false before calling agent_wait; child agents with delegation tools should do the same. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
84
+ "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached: when it completes, fails or is stopped, you receive a message event that wakes you, so do not poll. Optional timeoutMs (30000–300000; none if unset): if the child is still running after that many ms you receive an event with its status, elapsed time, tokens and recent output (the child is NOT stopped; you decide whether to wait, steer, stop it or re-arm with agent_steer timeoutMs). For parallel work, spawn every independent sibling with wait:false before calling agent_wait; child agents with delegation tools should do the same. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
85
85
  Type.Object({
86
86
  path: Type.String({
87
87
  description:
@@ -90,6 +90,14 @@ export function agentTools(
90
90
  type: text,
91
91
  task: text,
92
92
  wait: Type.Optional(Type.Boolean()),
93
+ timeoutMs: Type.Optional(
94
+ Type.Integer({
95
+ minimum: 30000,
96
+ maximum: 300000,
97
+ description:
98
+ "Optional report-only timeout, 30000–300000 ms (30s–5min). If the child is still running after this many ms, a status event is sent to you; the child keeps running.",
99
+ }),
100
+ ),
93
101
  }),
94
102
  async (params, signal) => result(compact(await threads().spawn(params, signal))),
95
103
  ),
@@ -105,9 +113,14 @@ export function agentTools(
105
113
  ),
106
114
  make(
107
115
  "agent_steer",
108
- "Send input to a descendant. Working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. Returns immediately; use agent_wait for the result.",
109
- Type.Object({ path, message: text }),
110
- async (params) => result(compact(await threads().steer(params.path, params.message))),
116
+ "Send input to a descendant and/or re-arm its report-only timeout. With message: working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. With timeoutMs (30000–300000): the timeout fires that many ms from now, replacing any pending timer. timeoutMs WITHOUT message only re-arms the timeout of a running child (error if not running) and does not steer or resume it; with both, steer and re-arm. At least one is required. Returns immediately; use agent_wait for the result.",
117
+ Type.Object({
118
+ path,
119
+ message: Type.Optional(text),
120
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 30000, maximum: 300000 })),
121
+ }),
122
+ async (params) =>
123
+ result(compact(await threads().steer(params.path, params.message, params.timeoutMs))),
111
124
  ),
112
125
  make(
113
126
  "agent_status",
package/src/types.ts CHANGED
@@ -172,10 +172,11 @@ export interface ThreadService {
172
172
  /** Optional for portable adapters; the runtime manager always implements this. */
173
173
  observeTranscript?(path: string, listener: TranscriptListener): Promise<TranscriptObservation>;
174
174
  spawn(
175
- args: { path: string; type: string; task: string; wait?: boolean },
175
+ args: { path: string; type: string; task: string; wait?: boolean; timeoutMs?: number },
176
176
  signal?: AbortSignal,
177
177
  ): Promise<ThreadView>;
178
- steer(path: string, message: string): Promise<ThreadView>;
178
+ /** message and/or timeoutMs (30s–5min). timeoutMs alone only re-arms a running child's report-only timeout. */
179
+ steer(path: string, message?: string, timeoutMs?: number): Promise<ThreadView>;
179
180
  wait(path: string, timeoutMs?: number, signal?: AbortSignal): Promise<ThreadView>;
180
181
  update(message: string): ThreadView;
181
182
  pause(reason: string): ThreadView;
@@ -186,7 +187,9 @@ export type ThreadEvent =
186
187
  | { kind: "change"; thread: ThreadView }
187
188
  | { kind: "metrics"; thread: ThreadView }
188
189
  | { kind: "update"; thread: ThreadView; message: string; recipient: string }
189
- | { kind: "settled"; thread: ThreadView; recipient: string };
190
+ | { kind: "settled"; thread: ThreadView; recipient: string; async: boolean }
191
+ /** A spawn timeout elapsed while the child is still running. The child is NOT stopped. */
192
+ | { kind: "timeout"; thread: ThreadView; recipient: string; timeoutMs: number; recentOutput: string };
190
193
  export interface ManagerOptions {
191
194
  createDriver: DriverFactory;
192
195
  rootSnapshot(): AgentMessage[];
@@ -51,6 +51,10 @@ const LAYOUT = { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 52 };
51
51
  interface ToolItem extends SelectItem {
52
52
  group: string;
53
53
  }
54
+ const MCP_TOOL = /^mcp__(.+?)__(.+)$/;
55
+ export function mcpServerOf(name: string): string | undefined {
56
+ return MCP_TOOL.exec(name)?.[1];
57
+ }
54
58
 
55
59
  export class ToolPickerComponent extends Container {
56
60
  private readonly searchInput = new Input({ placeholder: "Search tools" });
@@ -60,6 +64,7 @@ export class ToolPickerComponent extends Container {
60
64
  private readonly byName: Map<string, SessionTool>;
61
65
  private draft: string[] | undefined;
62
66
  private query = "";
67
+ private readonly expanded = new Set<string>();
63
68
  private _focused = false;
64
69
 
65
70
  constructor(
@@ -155,7 +160,7 @@ export class ToolPickerComponent extends Container {
155
160
  height,
156
161
  field === "allow" ? "Allowed tools" : "Blocked tools",
157
162
  [...header, ...rows].map((line) => ` ${line}`),
158
- "↑↓ select · Enter toggle/action · Ctrl+S done · Esc cancel",
163
+ "↑↓ select · Enter toggle/action · ←→ collapse/expand MCP · Ctrl+S done · Esc cancel",
159
164
  );
160
165
  }
161
166
 
@@ -165,6 +170,25 @@ export class ToolPickerComponent extends Container {
165
170
  return;
166
171
  }
167
172
  const kb = getKeybindings();
173
+ const current = this.selectList.getSelectedItem()?.value;
174
+ const isRight = matchesKey(data, Key.right);
175
+ const isLeft = matchesKey(data, Key.left);
176
+ if ((isRight || isLeft) && current) {
177
+ const server = current.startsWith("group:")
178
+ ? current.slice("group:".length)
179
+ : isLeft && current.startsWith("tool:")
180
+ ? mcpServerOf(current.slice("tool:".length))
181
+ : undefined;
182
+ const key =
183
+ server === undefined ? undefined : current.startsWith("group:") ? server : `mcp__${server}`;
184
+ if (key !== undefined) {
185
+ if (isRight && current.startsWith("group:")) this.expanded.add(key);
186
+ else if (isLeft) this.expanded.delete(key);
187
+ this.refresh(`group:${key}`);
188
+ this.options.tui.requestRender();
189
+ return;
190
+ }
191
+ }
168
192
  if (
169
193
  kb.matches(data, "tui.select.up") ||
170
194
  kb.matches(data, "tui.select.down") ||
@@ -209,11 +233,69 @@ export class ToolPickerComponent extends Container {
209
233
  : "unavailable in current session · preserved",
210
234
  group: checked ? "Selected tools" : "Session tools · A–Z",
211
235
  });
236
+ const searching = this.query.trim().length > 0;
237
+ const groups = new Map<string, string[]>();
238
+ const flat: string[] = [];
239
+ const addName = (name: string) => {
240
+ const server = mcpServerOf(name);
241
+ if (server === undefined) return flat.push(name);
242
+ const key = `mcp__${server}`;
243
+ const list = groups.get(key) ?? [];
244
+ if (!list.includes(name)) list.push(name);
245
+ groups.set(key, list);
246
+ };
247
+ for (const name of selected) if (mcpServerOf(name) === undefined) addName(name);
248
+ const matchedNames = new Set(matches.map((tool) => tool.name));
249
+ for (const tool of matches) if (!selected.has(tool.name)) addName(tool.name);
250
+ // Group members: all session tools plus preserved draft names (so toggling affects the whole MCP).
251
+ const members = new Map<string, string[]>();
252
+ for (const name of [...this.tools.map((t) => t.name), ...selected]) {
253
+ const server = mcpServerOf(name);
254
+ if (server === undefined) continue;
255
+ const list = members.get(`mcp__${server}`) ?? [];
256
+ if (!list.includes(name)) list.push(name);
257
+ members.set(`mcp__${server}`, list);
258
+ }
259
+ for (const name of selected) if (mcpServerOf(name) !== undefined && !searching) addName(name);
260
+ for (const key of [...groups.keys()]) {
261
+ // Show a group when not searching, or when any member matches the search.
262
+ if (searching && !members.get(key)!.some((n) => matchedNames.has(n))) groups.delete(key);
263
+ }
264
+ if (!searching) for (const key of members.keys()) if (!groups.has(key)) groups.set(key, []);
265
+ const flatSelected = flat.filter((n) => selected.has(n));
266
+ const flatUnselected = flat.filter((n) => !selected.has(n));
267
+ const rows: { sort: string; items: ToolItem[] }[] = flatUnselected.map((n) => ({
268
+ sort: n,
269
+ items: [toolItem(n, false)],
270
+ }));
271
+ for (const key of groups.keys()) {
272
+ const all = members.get(key)!.sort((a, b) => a.localeCompare(b));
273
+ const on = all.filter((n) => selected.has(n)).length;
274
+ const open = searching || this.expanded.has(key);
275
+ const mark = on === 0 ? " " : on === all.length ? "x" : "-";
276
+ const items: ToolItem[] = [
277
+ {
278
+ value: `group:${key}`,
279
+ label: `${open ? "▾" : "▸"} [${mark}] ${dialogText(key)}`,
280
+ description: `${on}/${all.length} tools · ${open ? "← collapse" : "→ expand"}`,
281
+ group: "Session tools · A–Z",
282
+ },
283
+ ];
284
+ if (open) {
285
+ for (const n of all) {
286
+ if (searching && !matchedNames.has(n)) continue;
287
+ const item = toolItem(n, selected.has(n));
288
+ item.label = ` ${item.label}`;
289
+ item.group = "Session tools · A–Z";
290
+ items.push(item);
291
+ }
292
+ }
293
+ rows.push({ sort: key, items });
294
+ }
295
+ rows.sort((x, y) => x.sort.localeCompare(y.sort));
212
296
  this.currentItems = [
213
- ...[...selected].map((name) => toolItem(name, true)),
214
- ...matches
215
- .filter((tool) => !selected.has(tool.name))
216
- .map((tool) => toolItem(tool.name, false)),
297
+ ...flatSelected.map((name) => toolItem(name, true)),
298
+ ...rows.flatMap((row) => row.items),
217
299
  {
218
300
  value: "action:done",
219
301
  label: "Done",
@@ -259,7 +341,15 @@ export class ToolPickerComponent extends Container {
259
341
  if (item.value === "action:done") this.finish();
260
342
  else if (item.value === "action:cancel") this.options.onCancel();
261
343
  else {
262
- if (item.value === "action:unset") this.draft = undefined;
344
+ if (item.value.startsWith("group:")) {
345
+ const key = item.value.slice("group:".length);
346
+ const names = [
347
+ ...new Set([...this.tools.map((t) => t.name), ...(this.draft ?? [])]),
348
+ ].filter((n) => mcpServerOf(n) !== undefined && `mcp__${mcpServerOf(n)}` === key);
349
+ const allOn = names.every((n) => this.draft?.includes(n));
350
+ const rest = (this.draft ?? []).filter((n) => !names.includes(n));
351
+ this.draft = allOn ? rest : [...rest, ...names];
352
+ } else if (item.value === "action:unset") this.draft = undefined;
263
353
  else if (item.value === "action:empty") this.draft = [];
264
354
  else {
265
355
  const name = item.value.slice("tool:".length);