pi-subagent-manager 0.16.0 → 0.18.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.
@@ -0,0 +1,187 @@
1
+ import { homedir } from "node:os";
2
+ import type { Usage } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+
6
+ export function footerUsage(entries: readonly SessionEntry[]) {
7
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
8
+ let cacheHit: number | undefined;
9
+ const add = (usage: Usage | undefined) => {
10
+ if (!usage) return;
11
+ totals.input += usage.input;
12
+ totals.output += usage.output;
13
+ totals.cacheRead += usage.cacheRead;
14
+ totals.cacheWrite += usage.cacheWrite;
15
+ totals.cost += usage.cost.total;
16
+ };
17
+ for (const entry of entries) {
18
+ if (entry.type === "usage") add(entry.usage);
19
+ else if (entry.type === "message") {
20
+ if (entry.message.role === "assistant") {
21
+ add(entry.message.usage);
22
+ const usage = entry.message.usage;
23
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
24
+ cacheHit = prompt ? (usage.cacheRead / prompt) * 100 : undefined;
25
+ } else if (entry.message.role === "toolResult") add(entry.message.usage);
26
+ } else if (entry.type === "branch_summary" || entry.type === "compaction") add(entry.usage);
27
+ }
28
+ return { ...totals, cacheHit };
29
+ }
30
+ export const COST_WIDGET_ID = "subagent_cost";
31
+ export const COST_WIDGET_EVENT = "pi-footer:update-widget";
32
+ export const COST_ICON = "\uf0d6";
33
+
34
+ export function formatSubagentCost(cost: number, nerdFontIcons: boolean): string {
35
+ return `${nerdFontIcons ? COST_ICON + " " : ""}$${cost.toFixed(4)}`;
36
+ }
37
+
38
+ /** Any extension-owned /footer takes priority; never infer activity from installed packages alone. */
39
+ export function hasExternalFooter(pi: Pick<ExtensionAPI, "getCommands">): boolean {
40
+ return pi
41
+ .getCommands()
42
+ .some((command) => command.name === "footer" && command.source === "extension");
43
+ }
44
+
45
+ export class CostFooterController {
46
+ private installed = false;
47
+ private requestRender: (() => void) | undefined;
48
+
49
+ constructor(
50
+ private readonly pi: Pick<ExtensionAPI, "getCommands" | "events">,
51
+ private readonly subagentCost: () => number,
52
+ private readonly nerdFontIcons: () => boolean,
53
+ ) {}
54
+
55
+ refresh(ctx: ExtensionContext): void {
56
+ // Publishing is independent of which footer owns the screen, including headless sessions.
57
+ this.pi.events.emit(COST_WIDGET_EVENT, {
58
+ widgetId: COST_WIDGET_ID,
59
+ value: formatSubagentCost(this.subagentCost(), this.nerdFontIcons()),
60
+ });
61
+ if (hasExternalFooter(this.pi)) {
62
+ // Do not clear setFooter here: it could already belong to pi-footer.
63
+ this.installed = false;
64
+ this.requestRender = undefined;
65
+ return;
66
+ }
67
+ if (this.installed) {
68
+ this.requestRender?.();
69
+ return;
70
+ }
71
+ if (this.subagentCost() <= 0 || !ctx.hasUI || ctx.mode !== "tui") return;
72
+ this.requestRender = installCostFooter(ctx, this.subagentCost);
73
+ this.installed = true;
74
+ }
75
+
76
+ reset(ctx: ExtensionContext): void {
77
+ if (this.installed && !hasExternalFooter(this.pi)) ctx.ui.setFooter(undefined);
78
+ this.installed = false;
79
+ this.requestRender = undefined;
80
+ }
81
+
82
+ clear(): void {
83
+ this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value: null });
84
+ }
85
+ }
86
+
87
+ const tokens = (n: number) =>
88
+ n < 1000
89
+ ? String(n)
90
+ : n < 10000
91
+ ? `${(n / 1000).toFixed(1)}k`
92
+ : n < 1000000
93
+ ? `${Math.round(n / 1000)}k`
94
+ : `${(n / 1000000).toFixed(1)}M`;
95
+
96
+ /** Public extension UI APIs only: never inject fake usage/messages into Pi's transcript. */
97
+ export function installCostFooter(
98
+ ctx: ExtensionContext,
99
+ subagentCost: () => number,
100
+ ): (() => void) | undefined {
101
+ if (!ctx.hasUI || ctx.mode !== "tui" || !ctx.ui.setFooter) return;
102
+ let requestRender: (() => void) | undefined;
103
+ ctx.ui.setFooter((tui, theme, footerData) => {
104
+ requestRender = () => tui.requestRender();
105
+ const unsubscribe = footerData.onBranchChange(() => tui.requestRender());
106
+ let entryCount = -1;
107
+ let totals = footerUsage([]);
108
+ return {
109
+ dispose: unsubscribe,
110
+ invalidate() {
111
+ entryCount = -1;
112
+ },
113
+ render(width: number) {
114
+ const entries = ctx.sessionManager.getEntries();
115
+ const count = entries.length;
116
+ if (count !== entryCount) {
117
+ totals = footerUsage(entries);
118
+ entryCount = count;
119
+ }
120
+ const branch = footerData.getGitBranch();
121
+ const name = ctx.sessionManager.getSessionName();
122
+ const cwd =
123
+ ctx.cwd === homedir()
124
+ ? "~"
125
+ : ctx.cwd.startsWith(homedir() + "/")
126
+ ? "~" + ctx.cwd.slice(homedir().length)
127
+ : ctx.cwd;
128
+ const location = cwd + (branch ? ` (${branch})` : "") + (name ? ` • ${name}` : "");
129
+ const parts: string[] = [];
130
+ if (totals.input) parts.push(`↑${tokens(totals.input)}`);
131
+ if (totals.output) parts.push(`↓${tokens(totals.output)}`);
132
+ if (totals.cacheRead) parts.push(`R${tokens(totals.cacheRead)}`);
133
+ if (totals.cacheWrite) parts.push(`W${tokens(totals.cacheWrite)}`);
134
+ if ((totals.cacheRead || totals.cacheWrite) && totals.cacheHit !== undefined)
135
+ parts.push(`CH${totals.cacheHit.toFixed(1)}%`);
136
+ // Pi's own usage and each child's own usage are disjoint. Never aggregate a parent's descendants twice.
137
+ const subscription =
138
+ ctx.model &&
139
+ (ctx.model.provider === "kimi-coding" || ctx.modelRegistry?.isUsingOAuth(ctx.model));
140
+ parts.push(`$${(totals.cost + subagentCost()).toFixed(3)}${subscription ? " (sub)" : ""}`);
141
+ const context = ctx.getContextUsage();
142
+ if (context) {
143
+ const text = `${context.percent === null ? "?" : context.percent.toFixed(1) + "%"}/${tokens(context.contextWindow)}`;
144
+ parts.push(
145
+ theme.fg(
146
+ (context.percent ?? 0) > 90
147
+ ? "error"
148
+ : (context.percent ?? 0) > 70
149
+ ? "warning"
150
+ : "dim",
151
+ text,
152
+ ),
153
+ );
154
+ }
155
+ const left = truncateToWidth(parts.join(" "), width, "");
156
+ let right = ctx.model?.id ?? "no-model";
157
+ if (ctx.model?.reasoning) right += ` • ${ctx.thinkingLevel ?? "off"}`;
158
+ if (footerData.getAvailableProviderCount() > 1 && ctx.model) {
159
+ const withProvider = `(${ctx.model.provider}) ${right}`;
160
+ if (visibleWidth(left) + 2 + visibleWidth(withProvider) <= width) right = withProvider;
161
+ }
162
+ const available = width - visibleWidth(left) - 2;
163
+ const stats =
164
+ available > 0
165
+ ? left +
166
+ " ".repeat(
167
+ Math.max(2, width - visibleWidth(left) - Math.min(available, visibleWidth(right))),
168
+ ) +
169
+ truncateToWidth(right, available, "")
170
+ : left;
171
+ const lines = [truncateToWidth(theme.fg("dim", location), width), theme.fg("dim", stats)];
172
+ const statuses = [...footerData.getExtensionStatuses()]
173
+ .sort(([a], [b]) => a.localeCompare(b))
174
+ .map(([, text]) =>
175
+ text
176
+ .replace(/[\r\n\t]/g, " ")
177
+ .replace(/ +/g, " ")
178
+ .trim(),
179
+ );
180
+ if (statuses.length)
181
+ lines.push(truncateToWidth(theme.fg("dim", statuses.join(" ")), width));
182
+ return lines;
183
+ },
184
+ };
185
+ });
186
+ return () => requestRender?.();
187
+ }
@@ -11,6 +11,7 @@ import {
11
11
  matchesKey,
12
12
  type Keybinding,
13
13
  } from "@earendil-works/pi-tui";
14
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
14
15
  import {
15
16
  canOpenDialog,
16
17
  DIALOG_OPTIONS,
@@ -27,7 +28,12 @@ import type { ThreadService } from "../types.ts";
27
28
  import type { LoaderStyle } from "../prefs/settings.ts";
28
29
  import { buildStatusTree, type StatusRow } from "./thread-tree.ts";
29
30
  import {
30
- AGENT_PROGRESS_INTERVAL, agentProgressIcon, agentTypeBadge, agentTypeLabel, showThreads, threadMetrics,
31
+ AGENT_PROGRESS_INTERVAL,
32
+ agentProgressIcon,
33
+ agentTypeBadge,
34
+ agentTypeLabel,
35
+ showThreads,
36
+ threadMetrics,
31
37
  } from "./ui.ts";
32
38
  import { LiveAgentView, fillViewport, type AgentViewportState } from "./live-agent-view.ts";
33
39
 
@@ -132,9 +138,16 @@ export class StatusDialog {
132
138
 
133
139
  private syncRefresh(): void {
134
140
  if (!this.refreshing) return;
135
- const delay = this.nerdFontIcons && this.service.list().some((thread) =>
136
- thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"))
137
- ? AGENT_PROGRESS_INTERVAL : 1000;
141
+ const delay =
142
+ this.nerdFontIcons &&
143
+ this.service
144
+ .list()
145
+ .some(
146
+ (thread) =>
147
+ thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"),
148
+ )
149
+ ? AGENT_PROGRESS_INTERVAL
150
+ : 1000;
138
151
  if (this.timer !== undefined && this.refreshDelay === delay) return;
139
152
  this.stopRefresh();
140
153
  this.refreshDelay = delay;
@@ -156,7 +169,10 @@ export class StatusDialog {
156
169
  private stopAll(): void {
157
170
  const live = this.service
158
171
  .list()
159
- .filter((thread) => thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"))
172
+ .filter(
173
+ (thread) =>
174
+ thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"),
175
+ )
160
176
  .map((thread) => thread.path);
161
177
  const tops = live.filter((path) => !live.some((other) => path.startsWith(`${other}/`)));
162
178
  for (const path of tops) {
@@ -243,38 +259,65 @@ export class StatusDialog {
243
259
  this.host.requestRender();
244
260
  }
245
261
 
246
- private line(row: StatusRow, selected: boolean): string {
262
+ private line(row: StatusRow, selected: boolean, width: number): string[] {
247
263
  const marker = row.hasChildren ? (this.collapsed.has(row.path) ? "▸ " : "▾ ") : "";
248
264
  const head = ` ${row.prefix}${selected ? "›" : " "} ${marker}`;
249
265
  const thread = row.thread;
250
266
  if (!thread) {
251
267
  const text = `${head}${label(row)}`;
252
- return selected ? this.theme.fg("accent", text) : text;
268
+ return [selected ? this.theme.fg("accent", text) : text, ""];
253
269
  }
254
270
  const inactive = INACTIVE_STATES.has(thread.state);
255
- if (inactive) {
256
- // Completed fades furthest (dim); the state word keeps a theme hint for done/failed.
257
- const base = thread.state === "completed" ? "dim" : "muted";
258
- const hint =
259
- thread.state === "completed" ? "success" : thread.state === "failed" ? "error" : base;
260
- const state = dialogText(thread.state);
261
- const path = dialogText(thread.path);
262
- const status = dialogText(thread.status);
263
- return [
264
- this.theme.fg(selected ? "accent" : base, head),
265
- this.theme.fg(base, `${agentTypeLabel(thread.type, thread.icon, this.nerdFontIcons, agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle))} ${path} `),
266
- this.theme.fg(hint, state),
267
- this.theme.fg(base, ` ${status}`),
268
- ].join("");
269
- }
270
- const rest = [thread.path, thread.state, thread.status]
271
+ const base = thread.state === "completed" ? "dim" : "muted";
272
+ const hint =
273
+ thread.state === "completed" ? "success" : thread.state === "failed" ? "error" : base;
274
+ const progress = agentProgressIcon(
275
+ thread,
276
+ this.nerdFontIcons,
277
+ Date.now(),
278
+ true,
279
+ this.loaderStyle,
280
+ );
281
+ const badge = inactive
282
+ ? this.theme.fg(base, agentTypeLabel(thread.type, thread.icon, this.nerdFontIcons, progress))
283
+ : agentTypeBadge(
284
+ thread.type,
285
+ thread.color,
286
+ this.theme,
287
+ thread.icon,
288
+ this.nerdFontIcons,
289
+ progress,
290
+ );
291
+ const identity = [
292
+ thread.path,
293
+ `${thread.model ?? "model pending"}${thread.thinkingLevel ? `:${thread.thinkingLevel}` : ""}`,
294
+ ]
271
295
  .map((part) => dialogText(part))
272
296
  .join(" ");
273
- const badge = agentTypeBadge(thread.type, thread.color, this.theme, thread.icon, this.nerdFontIcons,
274
- agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle));
275
- if (selected)
276
- return `${this.theme.fg("accent", head)}${badge} ${this.theme.fg("accent", rest)}`;
277
- return `${head}${badge} ${rest}`;
297
+ const first = [
298
+ selected ? this.theme.fg("accent", head) : head,
299
+ badge,
300
+ this.theme.fg(inactive ? base : selected ? "accent" : "text", ` ${identity} `),
301
+ this.theme.fg(inactive ? hint : "muted", dialogText(thread.state)),
302
+ ].join("");
303
+ // Continue the tree's vertical guides without repeating the branch or selection marker.
304
+ const stem = row.prefix.replace("├─ ", "│ ").replace("└─ ", " ");
305
+ const activity = ` ${stem} ${dialogText(thread.status || thread.task)}`;
306
+ const metrics = this.theme.fg(base, threadMetrics(thread));
307
+ const metricWidth = visibleWidth(metrics);
308
+ const second =
309
+ metricWidth >= width
310
+ ? truncateToWidth(metrics, width, "")
311
+ : (() => {
312
+ const left = truncateToWidth(
313
+ this.theme.fg(inactive ? base : selected ? "accent" : "muted", activity),
314
+ width - metricWidth - 1,
315
+ );
316
+ return (
317
+ left + " ".repeat(Math.max(1, width - visibleWidth(left) - metricWidth)) + metrics
318
+ );
319
+ })();
320
+ return [first, second];
278
321
  }
279
322
 
280
323
  private detail(row: StatusRow | undefined): string[] {
@@ -297,7 +340,7 @@ export class StatusDialog {
297
340
  if (rows[index]) this.selectedPath = rows[index].path;
298
341
  const budget = Math.max(0, height - 4);
299
342
  const detail = budget > 2 ? this.detail(rows[index]) : [];
300
- const treeCount = Math.max(0, budget - detail.length);
343
+ const treeCount = Math.max(0, Math.floor((budget - detail.length) / 2));
301
344
  this.viewport = Math.max(1, treeCount);
302
345
  const start = treeCount
303
346
  ? Math.max(0, Math.min(index - treeCount + 1, Math.max(0, rows.length - treeCount)))
@@ -305,7 +348,7 @@ export class StatusDialog {
305
348
  const body = [
306
349
  ...rows
307
350
  .slice(start, start + treeCount)
308
- .map((row) => this.line(row, row.path === this.selectedPath)),
351
+ .flatMap((row) => this.line(row, row.path === this.selectedPath, Math.max(0, width - 2))),
309
352
  ...detail,
310
353
  ];
311
354
  return frameDialog(
@@ -314,9 +357,7 @@ export class StatusDialog {
314
357
  height,
315
358
  this.heading(rows, start, treeCount),
316
359
  body,
317
- this.navigation
318
- ? "Esc main · ↑↓ select · ←→ fold · i Actions · Ctrl+C stop all"
319
- : FOOTER,
360
+ this.navigation ? "Esc main · ↑↓ select · ←→ fold · i Actions · Ctrl+C stop all" : FOOTER,
320
361
  );
321
362
  }
322
363
 
@@ -350,7 +391,17 @@ async function showAgentDialog(
350
391
  let dialog: StatusDialog | undefined;
351
392
  try {
352
393
  const chosen = await ctx.ui.custom<string | undefined>((host, theme, _keys, done) => {
353
- dialog = new StatusDialog(host, theme, service, done, selected, options.title, undefined, options.nerdFontIcons, options.loaderStyle);
394
+ dialog = new StatusDialog(
395
+ host,
396
+ theme,
397
+ service,
398
+ done,
399
+ selected,
400
+ options.title,
401
+ undefined,
402
+ options.nerdFontIcons,
403
+ options.loaderStyle,
404
+ );
354
405
  dialog.startRefresh();
355
406
  return dialog;
356
407
  }, DIALOG_OPTIONS);
@@ -394,7 +445,13 @@ export class AgentNavigationController {
394
445
  this.session = undefined;
395
446
  }
396
447
 
397
- open(ctx: ExtensionContext, service: ThreadService, selectedPath?: string, nerdFontIcons = false, loaderStyle: LoaderStyle = "circle"): Promise<void> {
448
+ open(
449
+ ctx: ExtensionContext,
450
+ service: ThreadService,
451
+ selectedPath?: string,
452
+ nerdFontIcons = false,
453
+ loaderStyle: LoaderStyle = "circle",
454
+ ): Promise<void> {
398
455
  if (this.opening) return this.opening;
399
456
  if (!canOpenDialog(ctx)) return Promise.resolve();
400
457
  if (selectedPath) this.tree.selectedPath = selectedPath;
@@ -493,7 +550,16 @@ export class AgentNavigationController {
493
550
  }
494
551
  const result = await session.mount<"back" | "main">(
495
552
  (tui, activeTheme, _keys, finish) =>
496
- new LiveAgentView(tui, activeTheme, service, chosen.path, viewport!, finish, nerdFontIcons, loaderStyle),
553
+ new LiveAgentView(
554
+ tui,
555
+ activeTheme,
556
+ service,
557
+ chosen.path,
558
+ viewport!,
559
+ finish,
560
+ nerdFontIcons,
561
+ loaderStyle,
562
+ ),
497
563
  );
498
564
  if (result !== "back") break;
499
565
  }
@@ -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);