pi-subagent-manager 0.15.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/README.md CHANGED
@@ -68,9 +68,10 @@ They inherit your current model until you set preferences. Details: [docs/defaul
68
68
  | ---------------- | ------------------------------------------------------ |
69
69
  | `/agents` | Settings (mode, limits, model picking, tool filtering) |
70
70
  | `/agents types` | Agent-type browser and editor |
71
- | `/agents tree` | Fullscreen tree and live viewer with manual steering (`/agents status` is an alias) |
71
+ | `/agents tree` | Fullscreen tree and live viewer with manual steering |
72
72
  | `/agents import` | Import agents from other subagent extensions |
73
73
  | `/agents reload` | Reload definitions and settings |
74
+ | `/agents reap` | Confirm the eligible count, then forget completed agents and free retained-thread slots (cannot be resumed); preserves active parents and ancestors of retained threads. Session files remain on disk. |
74
75
 
75
76
  A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line. A fresh prompt hides previously settled agents from the widget; they reappear only when resumed, and `/agents tree` always keeps them available. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. Press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
76
77
 
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,25 +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. `/agents status` is an alias. |
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 |
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. |
51
58
 
52
59
  ### `/agents tree` keys
53
60
 
54
- | Key | Action |
55
- | ----------- | ----------------- |
56
- | ↑↓ | Select |
57
- | ←→ | Collapse / expand |
58
- | PgUp / PgDn | Scroll |
59
- | 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 |
60
67
  | i | Existing actions: steer, stop, output, transcript |
61
- | Esc | Watcher → saved tree → Main |
62
- | Ctrl+Q | Return directly to Main |
68
+ | Esc | Watcher → saved tree → Main |
69
+ | Ctrl+Q | Return directly to Main |
63
70
 
64
71
  Refreshes every second and keeps your selection, collapse state and scroll position.
65
72
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.15.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
@@ -7,22 +7,26 @@ import { IMPORT_REQUEST_PREFIX, markImportOffered, offerAgentImport } from "./pr
7
7
  import { ThreadManager } from "./orch/manager.ts";
8
8
  import { loadManagerSettings } from "./prefs/settings.ts";
9
9
  import { configureAgents } from "./ui/settings-ui.ts";
10
- import { AgentNavigationController, showAgentStatus } from "./ui/status-ui.ts";
10
+ import { AgentNavigationController } from "./ui/status-ui.ts";
11
11
  import { AgentNavigationEditor } from "./ui/agent-navigation-editor.ts";
12
12
  import { createDriverFactory } from "./orch/runtime.ts";
13
13
  import { createInheritedToolSource } from "./orch/inherited-tools.ts";
14
14
  import { subagentPrompt } from "./orch/prompt.ts";
15
15
  import { agentTools } from "./orch/tools.ts";
16
16
  import { editAgentTypes, updateWidget } from "./ui/ui.ts";
17
+ import { canOpenDialog, dialogMenu } from "./ui/dialog.ts";
17
18
  import type { SavedThread, ThreadEvent } from "./types.ts";
18
19
 
19
20
  const REGISTRY_ENTRY = "pi-subagent:registry:v1";
20
21
  const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
21
22
  const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
23
+ const ROOT_WAKE_MESSAGE = "pi-subagent:wake";
22
24
  type RootNotification = {
23
25
  rootSessionId: string;
24
26
  content: string;
25
27
  finalRecap?: boolean;
28
+ /** Start a main-agent turn so it reacts to this event (async completion, spawn timeout). */
29
+ trigger?: boolean;
26
30
  details: { mailboxId: string; path: string; state: string };
27
31
  };
28
32
 
@@ -56,7 +60,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
56
60
  let summaryRunning = false;
57
61
  let suspendingSummaries = false;
58
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
+ };
59
70
  const cancelSummary = () => {
71
+ cancelWake();
60
72
  if (summaryTimer !== undefined) clearTimeout(summaryTimer);
61
73
  summaryTimer = undefined;
62
74
  summaryRunning = false;
@@ -183,6 +195,30 @@ export default function piSubagent(pi: ExtensionAPI): void {
183
195
  },
184
196
  { triggerTurn: false },
185
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);
186
222
  };
187
223
  const pendingSummaries = (ctx: ExtensionContext) => {
188
224
  const entries = ctx.sessionManager.getBranch();
@@ -202,14 +238,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
202
238
  };
203
239
  const scheduleSummary = (ctx: ExtensionContext) => {
204
240
  if (!limits.finalRecap || limits.subagentMode === "off" || summaryRunning || suspendingSummaries ||
205
- summaryTimer !== undefined || ctx.isIdle() === false || !pendingSummaries(ctx).length) return;
241
+ summaryTimer !== undefined || ctx.isIdle() === false || (manager?.outstandingAsync() ?? 0) > 0 || !pendingSummaries(ctx).length) return;
206
242
  const currentGeneration = generation;
207
243
  // Coalesce siblings finishing together and leave the settlement boundary before
208
244
  // starting a new turn. Recheck settings/session/idle state after the deferral.
209
245
  summaryTimer = setTimeout(() => {
210
246
  summaryTimer = undefined;
211
247
  if (currentGeneration !== generation || context?.sessionManager !== ctx.sessionManager ||
212
- !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;
213
250
  const notifications = pendingSummaries(ctx);
214
251
  if (!notifications.length) return;
215
252
  summaryRunning = true;
@@ -253,6 +290,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
253
290
  delivered.add(notification.details.mailboxId);
254
291
  }
255
292
  }
293
+ scheduleWake(ctx);
256
294
  scheduleSummary(ctx);
257
295
  };
258
296
  pi.on("agent_settled", async (_event, ctx) => {
@@ -264,22 +302,33 @@ export default function piSubagent(pi: ExtensionAPI): void {
264
302
  const delivery = (event: ThreadEvent) => {
265
303
  if (event.kind === "change" || event.kind === "metrics") return;
266
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);
267
307
  const message =
268
308
  event.kind === "update"
269
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."
270
316
  : thread.state === "completed"
271
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.]" : ""}`
272
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."}`;
273
319
  try {
274
320
  if (event.recipient === "/root") {
321
+ const recap = limits.finalRecap && !suspendingSummaries && event.kind === "settled" &&
322
+ event.async && ["completed", "failed", "stopped"].includes(thread.state);
275
323
  const notification: RootNotification = {
276
324
  rootSessionId: requireContext().sessionManager.getSessionId(),
277
325
  content: message,
278
326
  // Foreground results already handled by a busy main thread do not need
279
327
  // another turn. Completions during a summary do need a follow-up summary.
280
- finalRecap: limits.finalRecap && !suspendingSummaries && event.kind === "settled" &&
281
- (thread.state === "completed" || thread.state === "failed") &&
282
- (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)),
283
332
  details: {
284
333
  mailboxId: randomUUID(),
285
334
  path: thread.path,
@@ -477,7 +526,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
477
526
  manager = undefined;
478
527
  context = undefined;
479
528
  });
480
- const agentSubcommands = ["tree", "status", "settings", "types", "import", "reload"] as const;
529
+ const agentSubcommands = ["tree", "settings", "types", "import", "reload", "reap"] as const;
481
530
  pi.registerCommand("agents", {
482
531
  description: "Configure agent settings, import/edit definitions, or show the live tree",
483
532
  getArgumentCompletions: (argumentText) => {
@@ -504,7 +553,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
504
553
  if (command === "import") {
505
554
  await importAgents(ctx, false);
506
555
  } else if (command === "types") {
507
- await editAgentTypes(ctx, store, limits.nerdFontIcons);
556
+ await editAgentTypes(ctx, store, limits.nerdFontIcons, {
557
+ getAllTools: () => pi.getAllTools(),
558
+ toolFiltering: limits.toolFiltering,
559
+ });
508
560
  store.reload();
509
561
  } else if (command === "reload") {
510
562
  store.reload();
@@ -524,6 +576,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
524
576
  store,
525
577
  settings: limits,
526
578
  agentDir: getAgentDir(),
579
+ getAllTools: () => pi.getAllTools(),
527
580
  apply: () => {
528
581
  const diagnostics = loadLimits(ctx);
529
582
  requireManager().setLimits(limits);
@@ -533,13 +586,35 @@ export default function piSubagent(pi: ExtensionAPI): void {
533
586
  if (diagnostics.length) ctx.ui.notify(diagnostics.join("\n"), "warning");
534
587
  },
535
588
  });
536
- } else if (command === "status") {
537
- await showAgentStatus(ctx, requireManager().scope("/root"), undefined, limits.nerdFontIcons, limits.loaderStyle);
589
+ } else if (command === "reap") {
590
+ const current = requireManager();
591
+ const candidates = current.reapCandidates();
592
+ if (!candidates.length) {
593
+ ctx.ui.notify("No completed agents eligible for reaping.", "info");
594
+ return;
595
+ }
596
+ if (!canOpenDialog(ctx)) return;
597
+ closeNavigation();
598
+ const warning = `${candidates.length} completed agent${candidates.length === 1 ? "" : "s"} will be reaped.\nYou will not be able to resume them anymore.`;
599
+ const choice = await dialogMenu(ctx, "Reap completed agents?", [
600
+ { id: "confirm", label: "Confirm", help: warning },
601
+ { id: "cancel", label: "Cancel", help: warning },
602
+ ], { selectedId: "cancel" });
603
+ if (choice !== "confirm" || manager !== current) return;
604
+ const reaped = current.reap(candidates);
605
+ persist();
606
+ refreshWidget(ctx);
607
+ ctx.ui.notify(
608
+ reaped.length
609
+ ? `Reaped ${reaped.length} completed agent(s); their sessions can no longer be resumed.`
610
+ : "No completed agents eligible for reaping.",
611
+ "info",
612
+ );
538
613
  } else if (command === "tree") {
539
614
  await navigation.open(ctx, requireManager().scope("/root"), rest.join(" ") || undefined, limits.nerdFontIcons, limits.loaderStyle);
540
615
  } else
541
616
  ctx.ui.notify(
542
- "Usage: /agents [tree [path] | status | settings | types | import | reload]",
617
+ "Usage: /agents [tree [path] | settings | types | import | reload | reap]",
543
618
  "warning",
544
619
  );
545
620
  },
@@ -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> {
@@ -84,6 +99,51 @@ export class ThreadManager {
84
99
  return [...this.records.values()].map((record) => this.view(record));
85
100
  }
86
101
 
102
+ /** Preview eligible completed sessions without changing retained records. */
103
+ reapCandidates(only?: readonly string[]): string[] {
104
+ this.assertLive();
105
+ const records = [...this.records.values()];
106
+ const eligible = new Set(
107
+ records
108
+ .filter((record) => !only || only.includes(record.view.path))
109
+ .filter((record) => record.view.state === "completed" && (!record.initializing || record.driver))
110
+ .filter((record) =>
111
+ !records.some(
112
+ (other) => active(other.view) && isDescendant(record.view.path, other.view.path),
113
+ ),
114
+ )
115
+ .map((record) => record.view.path),
116
+ );
117
+ // Any retained descendant still needs its lexical ancestors.
118
+ for (const record of records) {
119
+ if (eligible.has(record.view.path)) continue;
120
+ let parent = record.view.parent;
121
+ while (parent && parent !== "/root") {
122
+ eligible.delete(parent);
123
+ parent = this.records.get(parent)?.view.parent ?? null;
124
+ }
125
+ }
126
+ return records
127
+ .filter((record) => eligible.has(record.view.path))
128
+ .sort((a, b) => a.view.createdAt - b.view.createdAt)
129
+ .map((record) => record.view.path);
130
+ }
131
+
132
+ /** Revalidate an optional confirmed snapshot before forgetting sessions. */
133
+ reap(only?: readonly string[]): string[] {
134
+ const reaped: string[] = [];
135
+ for (const path of this.reapCandidates(only)) {
136
+ const record = this.records.get(path)!;
137
+ this.clearTimeout(record);
138
+ record.detachTranscript?.();
139
+ record.transcriptListeners?.clear();
140
+ record.driver?.dispose();
141
+ this.records.delete(record.view.path);
142
+ reaped.push(record.view.path);
143
+ }
144
+ return reaped;
145
+ }
146
+
87
147
  /** Bind authority once; models and the user UI share this small composable service. */
88
148
  scope(caller: string): ThreadService {
89
149
  caller = canonicalPath(caller);
@@ -98,7 +158,7 @@ export class ThreadManager {
98
158
  transcript: (path) => this.transcript(caller, path),
99
159
  observeTranscript: (path, listener) => this.observeTranscript(caller, path, listener),
100
160
  spawn: (args, signal) => this.spawn(caller, args, signal),
101
- steer: (path, message) => this.steer(caller, path, message),
161
+ steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
102
162
  wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
103
163
  update: (message) => this.update(caller, message),
104
164
  pause: (reason) => this.pause(caller, reason),
@@ -216,10 +276,11 @@ export class ThreadManager {
216
276
 
217
277
  async spawn(
218
278
  caller: string,
219
- args: { path: string; type: string; task: string; wait?: boolean },
279
+ args: { path: string; type: string; task: string; wait?: boolean; timeoutMs?: number },
220
280
  signal?: AbortSignal,
221
281
  ): Promise<ThreadView> {
222
282
  this.assertLive();
283
+ if (args.timeoutMs !== undefined) assertSpawnTimeout(args.timeoutMs);
223
284
  caller = canonicalPath(caller);
224
285
  if (
225
286
  caller !== "/root" &&
@@ -286,17 +347,37 @@ export class ThreadManager {
286
347
  };
287
348
  this.records.set(path, record);
288
349
  if (record.contextPending) this.prepareInheritedContext(record);
350
+ record.async = args.wait === false;
289
351
  this.start(record, args.task);
352
+ if (args.timeoutMs !== undefined) this.armTimeout(record, args.timeoutMs);
290
353
  return args.wait === false ? this.view(record) : this.wait(caller, path, undefined, signal);
291
354
  }
292
355
 
293
- 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> {
294
366
  this.assertLive();
295
367
  caller = canonicalPath(caller);
296
368
  path = canonicalPath(path, caller);
297
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!);
298
374
  if (!message.trim()) throw new Error("Steering message must not be empty");
299
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
+ };
300
381
  for (;;) {
301
382
  this.assertLive();
302
383
  this.assertCallerMaySteer(caller);
@@ -312,11 +393,11 @@ export class ThreadManager {
312
393
  if (record.view.state === "running") {
313
394
  await record.driver!.steer(message);
314
395
  this.touch(record);
315
- return this.view(record);
396
+ return rearm();
316
397
  }
317
398
  this.assertCapacity();
318
399
  this.start(record, message);
319
- return this.view(record);
400
+ return rearm();
320
401
  }
321
402
  }
322
403
  async wait(
@@ -386,6 +467,7 @@ export class ThreadManager {
386
467
  for (const item of targets) {
387
468
  item.stopRequested = true;
388
469
  item.startup.abort();
470
+ this.clearTimeout(item);
389
471
  }
390
472
  await Promise.all(
391
473
  targets.map(async (item) => {
@@ -442,6 +524,63 @@ export class ThreadManager {
442
524
  },
443
525
  };
444
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
+ }
445
584
  async deliver(path: string, content: string): Promise<void> {
446
585
  // Restored parents may be idle and unopened; reports still belong in their retained transcript.
447
586
  const driver = await this.ensureDriver(this.record(path), true);
@@ -458,6 +597,7 @@ export class ThreadManager {
458
597
  record.transcriptListeners?.clear();
459
598
  record.stopRequested = true;
460
599
  record.startup.abort();
600
+ this.clearTimeout(record);
461
601
  }
462
602
  await Promise.all(
463
603
  records.map(async (record) => {
@@ -516,6 +656,7 @@ export class ThreadManager {
516
656
  record.view.error = errorText(error);
517
657
  record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
518
658
  } finally {
659
+ this.clearTimeout(record);
519
660
  this.freezeElapsed(record);
520
661
  record.liveInputTokens = 0;
521
662
  record.liveOutputTokens = 0;
@@ -526,6 +667,7 @@ export class ThreadManager {
526
667
  kind: "settled",
527
668
  thread: this.view(record),
528
669
  recipient: record.view.parent ?? record.view.owner,
670
+ async: record.async === true,
529
671
  });
530
672
  }
531
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[];
@@ -32,9 +32,9 @@ export const AGENT_LOADERS: Record<
32
32
  },
33
33
  hourglass: {
34
34
  label: "Hourglass",
35
- // Nerd Fonts fa-hourglass-start/half/end, pause, times-circle, stop.
35
+ // Nerd Fonts fa-hourglass-start/half/end, check-square, pause, times-circle, stop.
36
36
  frames: ["\uf251", "\uf252", "\uf253"],
37
- states: { completed: "\uf253", paused: "\uf04c", failed: "\uf057", stopped: "\uf04d" },
37
+ states: { completed: "\uf14a", paused: "\uf04c", failed: "\uf057", stopped: "\uf04d" },
38
38
  },
39
39
  };
40
40
 
@@ -20,6 +20,7 @@ import {
20
20
  type WidgetMode,
21
21
  } from "../prefs/settings.ts";
22
22
  import { editAgentTypes } from "./ui.ts";
23
+ import type { ToolEditorOptions } from "./tool-picker.ts";
23
24
  import { AGENT_LOADERS } from "./agent-loader.ts";
24
25
 
25
26
  const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
@@ -146,6 +147,7 @@ export async function configureAgents(
146
147
  store: ConfigStore;
147
148
  settings: ManagerSettings;
148
149
  agentDir: string;
150
+ getAllTools?: ToolEditorOptions["getAllTools"];
149
151
  apply(): void;
150
152
  },
151
153
  ): Promise<void> {
@@ -161,6 +163,7 @@ async function configureAgentsDialog(
161
163
  store: ConfigStore;
162
164
  settings: ManagerSettings;
163
165
  agentDir: string;
166
+ getAllTools?: ToolEditorOptions["getAllTools"];
164
167
  apply(): void;
165
168
  },
166
169
  ): Promise<void> {
@@ -325,7 +328,10 @@ async function configureAgentsDialog(
325
328
  }
326
329
  } else if (action === "defaults") draft = { ...DEFAULT_MANAGER_SETTINGS };
327
330
  else if (action === "types") {
328
- await editAgentTypes(ctx, options.store, draft.nerdFontIcons);
331
+ await editAgentTypes(ctx, options.store, draft.nerdFontIcons, {
332
+ getAllTools: options.getAllTools ?? (() => []),
333
+ toolFiltering: draft.toolFiltering,
334
+ });
329
335
  options.store.reload();
330
336
  } else if (action === "save") {
331
337
  const file = saveManagerSettings({
@@ -0,0 +1,398 @@
1
+ import fuzzysort from "fuzzysort";
2
+ import {
3
+ getSelectListTheme,
4
+ type ExtensionAPI,
5
+ type ExtensionCommandContext,
6
+ type Theme,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import {
9
+ Container,
10
+ getKeybindings,
11
+ Input,
12
+ Key,
13
+ matchesKey,
14
+ SelectList,
15
+ wrapTextWithAnsi,
16
+ type SelectItem,
17
+ } from "@earendil-works/pi-tui";
18
+ import type { ToolFilteringMode } from "../prefs/settings.ts";
19
+ import {
20
+ dialogHeight,
21
+ dialogText,
22
+ frameDialog,
23
+ DIALOG_OPTIONS,
24
+ type DialogHost,
25
+ } from "./dialog.ts";
26
+
27
+ export type SessionTool = Pick<
28
+ ReturnType<ExtensionAPI["getAllTools"]>[number],
29
+ "name" | "description"
30
+ >;
31
+ export interface ToolEditorOptions {
32
+ getAllTools(): readonly SessionTool[];
33
+ toolFiltering: ToolFilteringMode;
34
+ }
35
+ export const TOOL_EDITOR_CANCEL = Symbol("tool-editor-cancel");
36
+
37
+ export function toolPolicyNotice(
38
+ field: "allow" | "block",
39
+ policy: ToolFilteringMode,
40
+ ): string | undefined {
41
+ if (field === "allow" && policy !== "allowed") {
42
+ return "Allow list is not used until Tool Filtering policy is changed to Allowed (except blocked).";
43
+ }
44
+ if (field === "block" && policy === "all") {
45
+ return "Block list is not used until Tool Filtering policy is changed from All.";
46
+ }
47
+ return undefined;
48
+ }
49
+
50
+ const LAYOUT = { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 52 };
51
+ interface ToolItem extends SelectItem {
52
+ group: string;
53
+ }
54
+ const MCP_TOOL = /^mcp__(.+?)__(.+)$/;
55
+ export function mcpServerOf(name: string): string | undefined {
56
+ return MCP_TOOL.exec(name)?.[1];
57
+ }
58
+
59
+ export class ToolPickerComponent extends Container {
60
+ private readonly searchInput = new Input({ placeholder: "Search tools" });
61
+ private selectList = new SelectList([], 1, getSelectListTheme(), LAYOUT);
62
+ private currentItems: ToolItem[] = [];
63
+ private readonly tools: SessionTool[];
64
+ private readonly byName: Map<string, SessionTool>;
65
+ private draft: string[] | undefined;
66
+ private query = "";
67
+ private readonly expanded = new Set<string>();
68
+ private _focused = false;
69
+
70
+ constructor(
71
+ private readonly options: {
72
+ tui: DialogHost;
73
+ theme: Theme;
74
+ tools: readonly SessionTool[];
75
+ field: "allow" | "block";
76
+ toolFiltering: ToolFilteringMode;
77
+ initialTools?: readonly string[];
78
+ onDone(tools: string[] | undefined): void;
79
+ onCancel(): void;
80
+ },
81
+ ) {
82
+ super();
83
+ this.byName = new Map(options.tools.map((tool) => [tool.name, tool]));
84
+ this.tools = [...this.byName.values()].sort((a, b) => a.name.localeCompare(b.name));
85
+ this.draft =
86
+ options.initialTools === undefined ? undefined : [...new Set(options.initialTools)];
87
+ this.addChild(this.searchInput);
88
+ this.refresh();
89
+ }
90
+
91
+ get focused(): boolean {
92
+ return this._focused;
93
+ }
94
+ set focused(value: boolean) {
95
+ this._focused = value;
96
+ this.searchInput.focused = value;
97
+ }
98
+ getDraftTools(): readonly string[] | undefined {
99
+ return this.draft;
100
+ }
101
+ getCurrentItems(): readonly SelectItem[] {
102
+ return this.currentItems;
103
+ }
104
+ getSelectList(): SelectList {
105
+ return this.selectList;
106
+ }
107
+ getSearchInput(): Input {
108
+ return this.searchInput;
109
+ }
110
+
111
+ render(width: number): string[] {
112
+ const { tui, theme, field, toolFiltering } = this.options;
113
+ const height = dialogHeight(tui);
114
+ const inner = Math.max(1, width - 4);
115
+ const notice = toolPolicyNotice(field, toolFiltering);
116
+ const header = [
117
+ ...(notice ? wrapTextWithAnsi(theme.fg("warning", notice), inner) : []),
118
+ theme.fg(
119
+ "muted",
120
+ this.draft === undefined
121
+ ? "Unset (use default policy). Select tools to create a list."
122
+ : `${this.draft.length} selected · selected tools first · type to search`,
123
+ ),
124
+ ...this.searchInput.render(inner),
125
+ ];
126
+ const selected = this.selectList.getSelectedItem()?.value;
127
+ const displayRows: (ToolItem | string)[] = [];
128
+ let previous: string | undefined;
129
+ for (const item of this.currentItems) {
130
+ if (item.group !== previous) {
131
+ if (
132
+ item.group === "Actions" &&
133
+ !this.currentItems.some((row) => row.group === "Session tools · A–Z")
134
+ ) {
135
+ displayRows.push(
136
+ this.tools.length
137
+ ? "No unselected matching tools"
138
+ : "No tools available in this session",
139
+ );
140
+ }
141
+ displayRows.push(item.group);
142
+ }
143
+ previous = item.group;
144
+ displayRows.push(item);
145
+ }
146
+ const budget = Math.max(1, height - 4 - header.length);
147
+ const index = Math.max(
148
+ 0,
149
+ displayRows.findIndex((row) => typeof row !== "string" && row.value === selected),
150
+ );
151
+ const start = Math.max(0, Math.min(index - budget + 1, displayRows.length - budget));
152
+ const rows = displayRows.slice(start, start + budget).map((row) => {
153
+ if (typeof row === "string") return theme.fg("muted", row);
154
+ const text = `${row.value === selected ? "›" : " "} ${row.label} ${theme.fg("muted", row.description ?? "")}`;
155
+ return row.value === selected ? theme.fg("accent", text) : text;
156
+ });
157
+ return frameDialog(
158
+ theme,
159
+ width,
160
+ height,
161
+ field === "allow" ? "Allowed tools" : "Blocked tools",
162
+ [...header, ...rows].map((line) => ` ${line}`),
163
+ "↑↓ select · Enter toggle/action · ←→ collapse/expand MCP · Ctrl+S done · Esc cancel",
164
+ );
165
+ }
166
+
167
+ handleInput(data: string): void {
168
+ if (matchesKey(data, Key.ctrl("s"))) {
169
+ this.finish();
170
+ return;
171
+ }
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
+ }
192
+ if (
193
+ kb.matches(data, "tui.select.up") ||
194
+ kb.matches(data, "tui.select.down") ||
195
+ kb.matches(data, "tui.select.confirm") ||
196
+ kb.matches(data, "tui.select.cancel")
197
+ ) {
198
+ this.selectList.handleInput(data);
199
+ } else {
200
+ this.searchInput.handleInput(data);
201
+ const query = this.searchInput.getValue();
202
+ if (query !== this.query) {
203
+ this.query = query;
204
+ this.refresh(undefined, true);
205
+ }
206
+ }
207
+ this.options.tui.requestRender();
208
+ }
209
+
210
+ private finish(): void {
211
+ this.options.onDone(this.draft === undefined ? undefined : [...this.draft]);
212
+ }
213
+
214
+ private refresh(selectedValue?: string, focusResult = false): void {
215
+ const previousIndex = this.currentItems.findIndex(
216
+ (row) => row.value === this.selectList.getSelectedItem()?.value,
217
+ );
218
+ const selected = new Set(this.draft ?? []);
219
+ const matches = this.query.trim()
220
+ ? fuzzysort
221
+ .go(this.query.trim(), this.tools, {
222
+ keys: ["name", "description"],
223
+ limit: 0,
224
+ threshold: 0,
225
+ })
226
+ .map((result) => result.obj)
227
+ : this.tools;
228
+ const toolItem = (name: string, checked: boolean): ToolItem => ({
229
+ value: `tool:${name}`,
230
+ label: `[${checked ? "x" : " "}] ${dialogText(name)}`,
231
+ description: this.byName.has(name)
232
+ ? dialogText(this.byName.get(name)!.description)
233
+ : "unavailable in current session · preserved",
234
+ group: checked ? "Selected tools" : "Session tools · A–Z",
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));
296
+ this.currentItems = [
297
+ ...flatSelected.map((name) => toolItem(name, true)),
298
+ ...rows.flatMap((row) => row.items),
299
+ {
300
+ value: "action:done",
301
+ label: "Done",
302
+ description: "Apply this list to the agent draft",
303
+ group: "Actions",
304
+ },
305
+ {
306
+ value: "action:empty",
307
+ label: "Empty list",
308
+ description: "Set an explicit empty list",
309
+ group: "Actions",
310
+ },
311
+ {
312
+ value: "action:unset",
313
+ label: "Unset (use default policy)",
314
+ description: "Remove the explicit list",
315
+ group: "Actions",
316
+ },
317
+ {
318
+ value: "action:cancel",
319
+ label: "Cancel",
320
+ description: "Discard tool list changes",
321
+ group: "Actions",
322
+ },
323
+ ];
324
+ const list = new SelectList(
325
+ this.currentItems,
326
+ Math.min(this.currentItems.length, 10),
327
+ getSelectListTheme(),
328
+ LAYOUT,
329
+ );
330
+ const preferred = focusResult
331
+ ? this.currentItems.findIndex((row) => row.group === "Session tools · A–Z")
332
+ : this.currentItems.findIndex((row) => row.value === selectedValue);
333
+ list.setSelectedIndex(
334
+ preferred >= 0
335
+ ? preferred
336
+ : focusResult
337
+ ? 0
338
+ : Math.max(0, Math.min(previousIndex, this.currentItems.length - 1)),
339
+ );
340
+ list.onSelect = (item) => {
341
+ if (item.value === "action:done") this.finish();
342
+ else if (item.value === "action:cancel") this.options.onCancel();
343
+ else {
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;
353
+ else if (item.value === "action:empty") this.draft = [];
354
+ else {
355
+ const name = item.value.slice("tool:".length);
356
+ this.draft ??= [];
357
+ const index = this.draft.indexOf(name);
358
+ if (index >= 0) this.draft.splice(index, 1);
359
+ else this.draft.push(name);
360
+ }
361
+ this.refresh(item.value);
362
+ this.options.tui.requestRender();
363
+ }
364
+ };
365
+ list.onCancel = () => this.options.onCancel();
366
+ list.onSelectionChange = () => this.options.tui.requestRender();
367
+ this.selectList = list;
368
+ if (this.children[1]) this.children[1] = list;
369
+ else this.addChild(list);
370
+ }
371
+ }
372
+
373
+ export async function editToolSelection(
374
+ ctx: ExtensionCommandContext,
375
+ field: "allow" | "block",
376
+ current: readonly string[] | undefined,
377
+ options: ToolEditorOptions,
378
+ ): Promise<readonly string[] | undefined | typeof TOOL_EDITOR_CANCEL> {
379
+ if (ctx.mode !== "tui") {
380
+ if (ctx.hasUI)
381
+ ctx.ui.notify("Tool selection requires interactive TUI mode; draft unchanged.", "warning");
382
+ return TOOL_EDITOR_CANCEL;
383
+ }
384
+ return ctx.ui.custom<readonly string[] | undefined | typeof TOOL_EDITOR_CANCEL>(
385
+ (tui, theme, _keys, done) =>
386
+ new ToolPickerComponent({
387
+ tui,
388
+ theme,
389
+ tools: options.getAllTools(),
390
+ field,
391
+ toolFiltering: options.toolFiltering,
392
+ initialTools: current,
393
+ onDone: (tools) => done(tools),
394
+ onCancel: () => done(TOOL_EDITOR_CANCEL),
395
+ }),
396
+ DIALOG_OPTIONS,
397
+ );
398
+ }
package/src/ui/ui.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  serializeAgentType,
30
30
  } from "../prefs/config.ts";
31
31
  import { editModelPreferences, MODEL_EDITOR_CANCEL } from "./model-picker.ts";
32
+ import { editToolSelection, TOOL_EDITOR_CANCEL, type ToolEditorOptions } from "./tool-picker.ts";
32
33
  import {
33
34
  canOpenDialog,
34
35
  dialogEditor,
@@ -647,44 +648,15 @@ async function editToolList(
647
648
  ctx: ExtensionCommandContext,
648
649
  type: AgentType,
649
650
  field: "allow" | "block",
651
+ options: ToolEditorOptions,
650
652
  ): Promise<void> {
651
- const modes = [
652
- "Unset (use default policy)",
653
- "Empty list",
654
- "Enter exact tool names",
655
- ];
656
- const current = type.tools?.[field];
657
- const mode = await dialogMenu(
658
- ctx,
659
- `tools.${field} (${sanitizeText(toolListMenuValue(current))})`,
660
- modes.map((label) => ({ id: label, label })),
661
- {
662
- selectedId:
663
- current === undefined
664
- ? modes[0]
665
- : current.length === 0
666
- ? modes[1]
667
- : modes[2],
668
- },
669
- );
670
- if (!mode) return;
671
- if (mode === "Unset (use default policy)") {
653
+ const value = await editToolSelection(ctx, field, type.tools?.[field], options);
654
+ if (value === TOOL_EDITOR_CANCEL) return;
655
+ if (value === undefined) {
672
656
  if (type.tools) delete type.tools[field];
673
657
  } else {
674
- const value =
675
- mode === "Empty list"
676
- ? ""
677
- : await dialogEditor(
678
- ctx,
679
- `tools.${field}: comma-separated exact names`,
680
- type.tools?.[field]?.join(", ") ?? "",
681
- );
682
- if (value === undefined) return;
683
658
  type.tools ??= {};
684
- type.tools[field] = value
685
- .split(",")
686
- .map((name) => name.trim())
687
- .filter(Boolean);
659
+ type.tools[field] = [...value];
688
660
  }
689
661
  if (type.tools && !Object.keys(type.tools).length) delete type.tools;
690
662
  }
@@ -996,8 +968,8 @@ const EDIT_FIELD_HELP: Record<EditMenuAction, string> = {
996
968
  "Advisory display names to help pick a model. Not provider/model pins; never selected or required. One name per line; empty clears.",
997
969
  thinkingLevel: "Reasoning effort. Default follows the parent session.",
998
970
  "tools.allow":
999
- "Unset uses default policy; an empty list explicitly allows no tools.",
1000
- "tools.block": "Exact tool names to remove from the allowed set.",
971
+ "Pick session tools with checkboxes. Under Allowed (except blocked), an unset or empty allow list allows no tools.",
972
+ "tools.block": "Pick session tools to block. Blocked tools take precedence when the policy uses this list.",
1001
973
  color: "Thread widget color with live preview.",
1002
974
  icon: "Paste a single Nerd Font glyph from nerdfonts.com/cheat-sheet (not its name or codepoint).\nLeave blank to remove. Display requires [labs] Nerd Font icons in settings and a Nerd Font in your terminal.",
1003
975
  systemPrompt: "Edit the Markdown prompt body in a multiline dialog.",
@@ -1123,15 +1095,17 @@ export async function editAgentTypes(
1123
1095
  ctx: ExtensionCommandContext,
1124
1096
  store: ConfigStore,
1125
1097
  nerdFontIcons = false,
1098
+ toolEditor: ToolEditorOptions = { getAllTools: () => [], toolFiltering: "allowed" },
1126
1099
  ): Promise<void> {
1127
1100
  if (!canOpenDialog(ctx)) return;
1128
- await withDialogSession(ctx, (scoped) => editAgentTypesDialog(scoped, store, nerdFontIcons));
1101
+ await withDialogSession(ctx, (scoped) => editAgentTypesDialog(scoped, store, nerdFontIcons, toolEditor));
1129
1102
  }
1130
1103
 
1131
1104
  async function editAgentTypesDialog(
1132
1105
  ctx: ExtensionCommandContext,
1133
1106
  store: ConfigStore,
1134
1107
  nerdFontIcons: boolean,
1108
+ toolEditor: ToolEditorOptions,
1135
1109
  ): Promise<void> {
1136
1110
  while (true) {
1137
1111
  const types = store.list();
@@ -1437,6 +1411,7 @@ async function editAgentTypesDialog(
1437
1411
  ctx,
1438
1412
  candidate,
1439
1413
  field === "tools.allow" ? "allow" : "block",
1414
+ toolEditor,
1440
1415
  );
1441
1416
  }
1442
1417
  parseAgentType(serializeAgentType(candidate));