pi-subagent-manager 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +9 -9
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +790 -0
  4. package/dist/orch/checklist-integration.js +176 -0
  5. package/dist/orch/context-entries.js +6 -0
  6. package/dist/orch/cost-ledger.js +38 -0
  7. package/dist/orch/diagnostics.js +86 -0
  8. package/dist/orch/extensions.js +66 -0
  9. package/dist/orch/housekeeping-usage.js +22 -0
  10. package/dist/orch/housekeeping.js +248 -0
  11. package/dist/orch/inherited-tools.js +57 -0
  12. package/dist/orch/mailbox.js +195 -0
  13. package/dist/orch/manager.js +970 -0
  14. package/dist/orch/paths.js +69 -0
  15. package/dist/orch/prompt.js +30 -0
  16. package/dist/orch/registry.js +115 -0
  17. package/dist/orch/runtime.js +835 -0
  18. package/dist/orch/tools.js +112 -0
  19. package/dist/orch/transcript.js +165 -0
  20. package/dist/prefs/agent-import.js +188 -0
  21. package/dist/prefs/config.js +878 -0
  22. package/dist/prefs/import-discovery.js +547 -0
  23. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
  24. package/dist/prefs/models.js +56 -0
  25. package/dist/prefs/settings.js +491 -0
  26. package/dist/types.js +1 -0
  27. package/dist/ui/agent-loader.js +63 -0
  28. package/dist/ui/agent-navigation-editor.js +168 -0
  29. package/dist/ui/cost-footer.js +209 -0
  30. package/dist/ui/dialog.js +505 -0
  31. package/dist/ui/import-picker.js +191 -0
  32. package/dist/ui/live-agent-view.js +527 -0
  33. package/dist/ui/model-picker.js +529 -0
  34. package/dist/ui/settings-ui.js +671 -0
  35. package/dist/ui/status-ui.js +470 -0
  36. package/dist/ui/thread-tree.js +142 -0
  37. package/dist/ui/tool-picker.js +331 -0
  38. package/dist/ui/transcript-tool.js +91 -0
  39. package/dist/ui/ui.js +1019 -0
  40. package/package.json +17 -5
  41. package/docs/assets/subagent-manager-demo.gif +0 -0
  42. package/docs/async-lifecycle.md +0 -153
  43. package/docs/custom-agents.md +0 -154
  44. package/docs/default-agents.md +0 -95
  45. package/docs/demo.md +0 -63
  46. package/docs/development.md +0 -74
  47. package/docs/importing-agents.md +0 -41
  48. package/docs/pi-footer.md +0 -128
  49. package/docs/research-claude.md +0 -258
  50. package/docs/research-codex.md +0 -143
  51. package/docs/research-default-agent-models.md +0 -121
  52. package/docs/research-model-audit-2026-10.md +0 -154
  53. package/docs/research-model-roles-coding.md +0 -99
  54. package/docs/research-model-roles-writing.md +0 -78
  55. package/docs/research-researcher-workflow.md +0 -97
  56. package/docs/settings.md +0 -293
  57. package/docs/subagent-extension-limitations.md +0 -98
  58. package/docs/threads.md +0 -73
  59. package/docs/tools-and-ui.md +0 -129
  60. package/src/index.ts +0 -920
  61. package/src/orch/checklist-integration.ts +0 -230
  62. package/src/orch/context-entries.ts +0 -15
  63. package/src/orch/cost-ledger.ts +0 -56
  64. package/src/orch/diagnostics.ts +0 -95
  65. package/src/orch/extensions.ts +0 -83
  66. package/src/orch/housekeeping-usage.ts +0 -47
  67. package/src/orch/housekeeping.ts +0 -348
  68. package/src/orch/inherited-tools.ts +0 -84
  69. package/src/orch/mailbox.ts +0 -261
  70. package/src/orch/manager.ts +0 -1084
  71. package/src/orch/paths.ts +0 -73
  72. package/src/orch/prompt.ts +0 -39
  73. package/src/orch/registry.ts +0 -168
  74. package/src/orch/runtime.ts +0 -1041
  75. package/src/orch/tools.ts +0 -190
  76. package/src/orch/transcript.ts +0 -186
  77. package/src/prefs/agent-import.ts +0 -245
  78. package/src/prefs/config.ts +0 -1017
  79. package/src/prefs/import-discovery.ts +0 -643
  80. package/src/prefs/models.ts +0 -74
  81. package/src/prefs/settings.ts +0 -614
  82. package/src/types.ts +0 -271
  83. package/src/ui/agent-loader.ts +0 -98
  84. package/src/ui/agent-navigation-editor.ts +0 -233
  85. package/src/ui/cost-footer.ts +0 -230
  86. package/src/ui/dialog.ts +0 -678
  87. package/src/ui/import-picker.ts +0 -231
  88. package/src/ui/live-agent-view.ts +0 -600
  89. package/src/ui/model-picker.ts +0 -701
  90. package/src/ui/settings-ui.ts +0 -830
  91. package/src/ui/status-ui.ts +0 -628
  92. package/src/ui/thread-tree.ts +0 -173
  93. package/src/ui/tool-picker.ts +0 -398
  94. package/src/ui/transcript-tool.ts +0 -142
  95. package/src/ui/ui.ts +0 -1407
@@ -1,173 +0,0 @@
1
- import type { ThreadView } from "../types.ts";
2
-
3
- const ROOT = "/root";
4
-
5
- /**
6
- * A [labs] housekeeping summary is shown only while the agent is active.
7
- * Detailed rows fall back to status/task; the compact widget supplies its task-only fallback.
8
- */
9
- export function threadActivity(
10
- thread: ThreadView,
11
- fallback = thread.status || thread.task,
12
- ): string {
13
- const active = thread.state === "starting" || thread.state === "running";
14
- const summary = typeof thread.summary === "string" ? thread.summary.trim() : "";
15
- return (active && summary) || fallback;
16
- }
17
-
18
- export interface StatusRow {
19
- path: string;
20
- prefix: string;
21
- thread?: ThreadView;
22
- hasChildren: boolean;
23
- }
24
-
25
- interface StatusNode {
26
- path: string;
27
- thread?: ThreadView;
28
- children: StatusNode[];
29
- }
30
-
31
- function lexicalParent(path: string): string | null {
32
- const index = path.lastIndexOf("/");
33
- return index > 0 ? path.slice(0, index) : null;
34
- }
35
-
36
- function comparePath(a: string, b: string): number {
37
- return a < b ? -1 : a > b ? 1 : 0;
38
- }
39
-
40
- function chainHas(parentOf: Map<string, string | null>, start: string, target: string): boolean {
41
- const seen = new Set<string>();
42
- let current: string | null = start;
43
- while (current) {
44
- if (current === target || seen.has(current)) return true;
45
- seen.add(current);
46
- current = parentOf.get(current) ?? null;
47
- }
48
- return false;
49
- }
50
-
51
- /** When an agent last (re)started; older saves fall back to creation time. */
52
- export function lastStarted(thread: ThreadView | undefined): number {
53
- const value = thread?.lastStartedAt ?? thread?.createdAt;
54
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
55
- }
56
-
57
- /** Newest branch first: a branch ranks by its most recently started agent. Cycles are guarded. */
58
- export function recencyComparator(threads: ThreadView[]): (a: string, b: string) => number {
59
- const byPath = new Map<string, ThreadView>();
60
- for (const thread of threads) {
61
- if (thread?.path && !byPath.has(thread.path)) byPath.set(thread.path, thread);
62
- }
63
- const latest = new Map<string, number>();
64
- for (const thread of byPath.values()) {
65
- const time = lastStarted(thread);
66
- const seen = new Set<string>();
67
- let current: string | null = thread.path;
68
- while (current && !seen.has(current)) {
69
- seen.add(current);
70
- latest.set(current, Math.max(latest.get(current) ?? 0, time));
71
- const view = byPath.get(current);
72
- current = view
73
- ? view.parent && view.parent !== current
74
- ? view.parent
75
- : null
76
- : lexicalParent(current);
77
- }
78
- }
79
- return (a, b) => (latest.get(b) ?? 0) - (latest.get(a) ?? 0) || comparePath(a, b);
80
- }
81
-
82
- /** Flatten retained agents. Parent links win over path shape; /root is always present.
83
- * `comparePaths` orders siblings and roots only (default: most recently started branch first).
84
- * Cycle repair stays lexical.
85
- */
86
- export function buildStatusTree(
87
- threads: ThreadView[],
88
- collapsed: Set<string>,
89
- comparePaths: (a: string, b: string) => number = recencyComparator(threads),
90
- ): StatusRow[] {
91
- const threadsByPath = new Map<string, ThreadView>();
92
- for (const thread of threads) {
93
- if (thread?.path && !threadsByPath.has(thread.path)) threadsByPath.set(thread.path, thread);
94
- }
95
- const nodes = new Map<string, StatusNode>();
96
- const parentOf = new Map<string, string | null>();
97
- const nodeFor = (path: string): StatusNode => {
98
- let node = nodes.get(path);
99
- if (!node) {
100
- node = { path, thread: threadsByPath.get(path), children: [] };
101
- nodes.set(path, node);
102
- }
103
- return node;
104
- };
105
- const declaredParent = (path: string): string | null => {
106
- if (path === ROOT) return null;
107
- const thread = threadsByPath.get(path);
108
- if (thread) return thread.parent && thread.parent !== path ? thread.parent : null;
109
- return lexicalParent(path);
110
- };
111
- const ensure = (path: string, seen = new Set<string>()): void => {
112
- if (!path || seen.has(path)) return;
113
- seen.add(path);
114
- nodeFor(path);
115
- if (parentOf.has(path)) return;
116
- const parent = declaredParent(path);
117
- parentOf.set(path, parent);
118
- if (parent) ensure(parent, seen);
119
- };
120
- ensure(ROOT);
121
- for (const path of threadsByPath.keys()) ensure(path);
122
-
123
- const linked = new Set<string>();
124
- for (const path of [...parentOf.keys()].sort(comparePath)) {
125
- const parent = parentOf.get(path);
126
- if (!parent || parent === path) continue;
127
- if (chainHas(parentOf, parent, path)) {
128
- parentOf.set(path, null);
129
- continue;
130
- }
131
- const parentNode = nodeFor(parent);
132
- const child = nodeFor(path);
133
- if (!parentNode.children.includes(child)) parentNode.children.push(child);
134
- linked.add(path);
135
- }
136
-
137
- const rows: StatusRow[] = [];
138
- const visited = new Set<string>();
139
- const conceal = (node: StatusNode) => {
140
- for (const child of node.children) {
141
- if (visited.has(child.path)) continue;
142
- visited.add(child.path);
143
- conceal(child);
144
- }
145
- };
146
- const walk = (list: StatusNode[], ancestors: boolean[], top: boolean) => {
147
- const ordered = [...list]
148
- .filter((node) => !visited.has(node.path))
149
- .sort((a, b) => comparePaths(a.path, b.path));
150
- for (const [index, node] of ordered.entries()) {
151
- visited.add(node.path);
152
- const last = index === ordered.length - 1;
153
- const stem = ancestors.map((isLast) => (isLast ? " " : "│ ")).join("");
154
- rows.push({
155
- path: node.path,
156
- prefix: stem + (top ? "" : last ? "└ " : "├ "),
157
- hasChildren: node.children.length > 0,
158
- ...(node.thread ? { thread: node.thread } : {}),
159
- });
160
- if (collapsed.has(node.path)) conceal(node);
161
- else if (node.children.length > 0)
162
- walk(node.children, top ? [] : [...ancestors, last], false);
163
- }
164
- };
165
- walk(
166
- [...nodes.values()].filter((node) => !linked.has(node.path)),
167
- [],
168
- true,
169
- );
170
- const missed = [...nodes.values()].filter((node) => !visited.has(node.path));
171
- if (missed.length) walk(missed, [], true);
172
- return rows;
173
- }
@@ -1,398 +0,0 @@
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
- }