pi-subagent-manager 0.14.0 → 0.16.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,308 @@
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
+
55
+ export class ToolPickerComponent extends Container {
56
+ private readonly searchInput = new Input({ placeholder: "Search tools" });
57
+ private selectList = new SelectList([], 1, getSelectListTheme(), LAYOUT);
58
+ private currentItems: ToolItem[] = [];
59
+ private readonly tools: SessionTool[];
60
+ private readonly byName: Map<string, SessionTool>;
61
+ private draft: string[] | undefined;
62
+ private query = "";
63
+ private _focused = false;
64
+
65
+ constructor(
66
+ private readonly options: {
67
+ tui: DialogHost;
68
+ theme: Theme;
69
+ tools: readonly SessionTool[];
70
+ field: "allow" | "block";
71
+ toolFiltering: ToolFilteringMode;
72
+ initialTools?: readonly string[];
73
+ onDone(tools: string[] | undefined): void;
74
+ onCancel(): void;
75
+ },
76
+ ) {
77
+ super();
78
+ this.byName = new Map(options.tools.map((tool) => [tool.name, tool]));
79
+ this.tools = [...this.byName.values()].sort((a, b) => a.name.localeCompare(b.name));
80
+ this.draft =
81
+ options.initialTools === undefined ? undefined : [...new Set(options.initialTools)];
82
+ this.addChild(this.searchInput);
83
+ this.refresh();
84
+ }
85
+
86
+ get focused(): boolean {
87
+ return this._focused;
88
+ }
89
+ set focused(value: boolean) {
90
+ this._focused = value;
91
+ this.searchInput.focused = value;
92
+ }
93
+ getDraftTools(): readonly string[] | undefined {
94
+ return this.draft;
95
+ }
96
+ getCurrentItems(): readonly SelectItem[] {
97
+ return this.currentItems;
98
+ }
99
+ getSelectList(): SelectList {
100
+ return this.selectList;
101
+ }
102
+ getSearchInput(): Input {
103
+ return this.searchInput;
104
+ }
105
+
106
+ render(width: number): string[] {
107
+ const { tui, theme, field, toolFiltering } = this.options;
108
+ const height = dialogHeight(tui);
109
+ const inner = Math.max(1, width - 4);
110
+ const notice = toolPolicyNotice(field, toolFiltering);
111
+ const header = [
112
+ ...(notice ? wrapTextWithAnsi(theme.fg("warning", notice), inner) : []),
113
+ theme.fg(
114
+ "muted",
115
+ this.draft === undefined
116
+ ? "Unset (use default policy). Select tools to create a list."
117
+ : `${this.draft.length} selected · selected tools first · type to search`,
118
+ ),
119
+ ...this.searchInput.render(inner),
120
+ ];
121
+ const selected = this.selectList.getSelectedItem()?.value;
122
+ const displayRows: (ToolItem | string)[] = [];
123
+ let previous: string | undefined;
124
+ for (const item of this.currentItems) {
125
+ if (item.group !== previous) {
126
+ if (
127
+ item.group === "Actions" &&
128
+ !this.currentItems.some((row) => row.group === "Session tools · A–Z")
129
+ ) {
130
+ displayRows.push(
131
+ this.tools.length
132
+ ? "No unselected matching tools"
133
+ : "No tools available in this session",
134
+ );
135
+ }
136
+ displayRows.push(item.group);
137
+ }
138
+ previous = item.group;
139
+ displayRows.push(item);
140
+ }
141
+ const budget = Math.max(1, height - 4 - header.length);
142
+ const index = Math.max(
143
+ 0,
144
+ displayRows.findIndex((row) => typeof row !== "string" && row.value === selected),
145
+ );
146
+ const start = Math.max(0, Math.min(index - budget + 1, displayRows.length - budget));
147
+ const rows = displayRows.slice(start, start + budget).map((row) => {
148
+ if (typeof row === "string") return theme.fg("muted", row);
149
+ const text = `${row.value === selected ? "›" : " "} ${row.label} ${theme.fg("muted", row.description ?? "")}`;
150
+ return row.value === selected ? theme.fg("accent", text) : text;
151
+ });
152
+ return frameDialog(
153
+ theme,
154
+ width,
155
+ height,
156
+ field === "allow" ? "Allowed tools" : "Blocked tools",
157
+ [...header, ...rows].map((line) => ` ${line}`),
158
+ "↑↓ select · Enter toggle/action · Ctrl+S done · Esc cancel",
159
+ );
160
+ }
161
+
162
+ handleInput(data: string): void {
163
+ if (matchesKey(data, Key.ctrl("s"))) {
164
+ this.finish();
165
+ return;
166
+ }
167
+ const kb = getKeybindings();
168
+ if (
169
+ kb.matches(data, "tui.select.up") ||
170
+ kb.matches(data, "tui.select.down") ||
171
+ kb.matches(data, "tui.select.confirm") ||
172
+ kb.matches(data, "tui.select.cancel")
173
+ ) {
174
+ this.selectList.handleInput(data);
175
+ } else {
176
+ this.searchInput.handleInput(data);
177
+ const query = this.searchInput.getValue();
178
+ if (query !== this.query) {
179
+ this.query = query;
180
+ this.refresh(undefined, true);
181
+ }
182
+ }
183
+ this.options.tui.requestRender();
184
+ }
185
+
186
+ private finish(): void {
187
+ this.options.onDone(this.draft === undefined ? undefined : [...this.draft]);
188
+ }
189
+
190
+ private refresh(selectedValue?: string, focusResult = false): void {
191
+ const previousIndex = this.currentItems.findIndex(
192
+ (row) => row.value === this.selectList.getSelectedItem()?.value,
193
+ );
194
+ const selected = new Set(this.draft ?? []);
195
+ const matches = this.query.trim()
196
+ ? fuzzysort
197
+ .go(this.query.trim(), this.tools, {
198
+ keys: ["name", "description"],
199
+ limit: 0,
200
+ threshold: 0,
201
+ })
202
+ .map((result) => result.obj)
203
+ : this.tools;
204
+ const toolItem = (name: string, checked: boolean): ToolItem => ({
205
+ value: `tool:${name}`,
206
+ label: `[${checked ? "x" : " "}] ${dialogText(name)}`,
207
+ description: this.byName.has(name)
208
+ ? dialogText(this.byName.get(name)!.description)
209
+ : "unavailable in current session · preserved",
210
+ group: checked ? "Selected tools" : "Session tools · A–Z",
211
+ });
212
+ 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)),
217
+ {
218
+ value: "action:done",
219
+ label: "Done",
220
+ description: "Apply this list to the agent draft",
221
+ group: "Actions",
222
+ },
223
+ {
224
+ value: "action:empty",
225
+ label: "Empty list",
226
+ description: "Set an explicit empty list",
227
+ group: "Actions",
228
+ },
229
+ {
230
+ value: "action:unset",
231
+ label: "Unset (use default policy)",
232
+ description: "Remove the explicit list",
233
+ group: "Actions",
234
+ },
235
+ {
236
+ value: "action:cancel",
237
+ label: "Cancel",
238
+ description: "Discard tool list changes",
239
+ group: "Actions",
240
+ },
241
+ ];
242
+ const list = new SelectList(
243
+ this.currentItems,
244
+ Math.min(this.currentItems.length, 10),
245
+ getSelectListTheme(),
246
+ LAYOUT,
247
+ );
248
+ const preferred = focusResult
249
+ ? this.currentItems.findIndex((row) => row.group === "Session tools · A–Z")
250
+ : this.currentItems.findIndex((row) => row.value === selectedValue);
251
+ list.setSelectedIndex(
252
+ preferred >= 0
253
+ ? preferred
254
+ : focusResult
255
+ ? 0
256
+ : Math.max(0, Math.min(previousIndex, this.currentItems.length - 1)),
257
+ );
258
+ list.onSelect = (item) => {
259
+ if (item.value === "action:done") this.finish();
260
+ else if (item.value === "action:cancel") this.options.onCancel();
261
+ else {
262
+ if (item.value === "action:unset") this.draft = undefined;
263
+ else if (item.value === "action:empty") this.draft = [];
264
+ else {
265
+ const name = item.value.slice("tool:".length);
266
+ this.draft ??= [];
267
+ const index = this.draft.indexOf(name);
268
+ if (index >= 0) this.draft.splice(index, 1);
269
+ else this.draft.push(name);
270
+ }
271
+ this.refresh(item.value);
272
+ this.options.tui.requestRender();
273
+ }
274
+ };
275
+ list.onCancel = () => this.options.onCancel();
276
+ list.onSelectionChange = () => this.options.tui.requestRender();
277
+ this.selectList = list;
278
+ if (this.children[1]) this.children[1] = list;
279
+ else this.addChild(list);
280
+ }
281
+ }
282
+
283
+ export async function editToolSelection(
284
+ ctx: ExtensionCommandContext,
285
+ field: "allow" | "block",
286
+ current: readonly string[] | undefined,
287
+ options: ToolEditorOptions,
288
+ ): Promise<readonly string[] | undefined | typeof TOOL_EDITOR_CANCEL> {
289
+ if (ctx.mode !== "tui") {
290
+ if (ctx.hasUI)
291
+ ctx.ui.notify("Tool selection requires interactive TUI mode; draft unchanged.", "warning");
292
+ return TOOL_EDITOR_CANCEL;
293
+ }
294
+ return ctx.ui.custom<readonly string[] | undefined | typeof TOOL_EDITOR_CANCEL>(
295
+ (tui, theme, _keys, done) =>
296
+ new ToolPickerComponent({
297
+ tui,
298
+ theme,
299
+ tools: options.getAllTools(),
300
+ field,
301
+ toolFiltering: options.toolFiltering,
302
+ initialTools: current,
303
+ onDone: (tools) => done(tools),
304
+ onCancel: () => done(TOOL_EDITOR_CANCEL),
305
+ }),
306
+ DIALOG_OPTIONS,
307
+ );
308
+ }