pi-subagent-manager 1.10.0 → 1.11.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 (186) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +836 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/orch/checklist-integration.d.ts +48 -0
  6. package/dist/orch/checklist-integration.d.ts.map +1 -0
  7. package/dist/orch/checklist-integration.js +204 -0
  8. package/dist/orch/checklist-integration.js.map +1 -0
  9. package/dist/orch/context-entries.d.ts +8 -0
  10. package/dist/orch/context-entries.d.ts.map +1 -0
  11. package/dist/orch/context-entries.js +8 -0
  12. package/dist/orch/context-entries.js.map +1 -0
  13. package/dist/orch/cost-ledger.d.ts +16 -0
  14. package/dist/orch/cost-ledger.d.ts.map +1 -0
  15. package/dist/orch/cost-ledger.js +43 -0
  16. package/dist/orch/cost-ledger.js.map +1 -0
  17. package/dist/orch/diagnostics.d.ts +13 -0
  18. package/dist/orch/diagnostics.d.ts.map +1 -0
  19. package/dist/orch/diagnostics.js +95 -0
  20. package/dist/orch/diagnostics.js.map +1 -0
  21. package/dist/orch/extensions.d.ts +15 -0
  22. package/dist/orch/extensions.d.ts.map +1 -0
  23. package/dist/orch/extensions.js +80 -0
  24. package/dist/orch/extensions.js.map +1 -0
  25. package/dist/orch/housekeeping-usage.d.ts +14 -0
  26. package/dist/orch/housekeeping-usage.d.ts.map +1 -0
  27. package/dist/orch/housekeeping-usage.js +27 -0
  28. package/dist/orch/housekeeping-usage.js.map +1 -0
  29. package/dist/orch/housekeeping.d.ts +89 -0
  30. package/dist/orch/housekeeping.d.ts.map +1 -0
  31. package/dist/orch/housekeeping.js +281 -0
  32. package/dist/orch/housekeeping.js.map +1 -0
  33. package/dist/orch/inherited-tools.d.ts +18 -0
  34. package/dist/orch/inherited-tools.d.ts.map +1 -0
  35. package/dist/orch/inherited-tools.js +71 -0
  36. package/dist/orch/inherited-tools.js.map +1 -0
  37. package/dist/orch/mailbox.d.ts +59 -0
  38. package/dist/orch/mailbox.d.ts.map +1 -0
  39. package/dist/orch/mailbox.js +196 -0
  40. package/dist/orch/mailbox.js.map +1 -0
  41. package/dist/orch/manager.d.ts +82 -0
  42. package/dist/orch/manager.d.ts.map +1 -0
  43. package/dist/orch/manager.js +1010 -0
  44. package/dist/orch/manager.js.map +1 -0
  45. package/dist/orch/paths.d.ts +7 -0
  46. package/dist/orch/paths.d.ts.map +1 -0
  47. package/dist/orch/paths.js +73 -0
  48. package/dist/orch/paths.js.map +1 -0
  49. package/dist/orch/prompt.d.ts +7 -0
  50. package/dist/orch/prompt.d.ts.map +1 -0
  51. package/dist/orch/prompt.js +34 -0
  52. package/dist/orch/prompt.js.map +1 -0
  53. package/dist/orch/registry.d.ts +49 -0
  54. package/dist/orch/registry.d.ts.map +1 -0
  55. package/dist/orch/registry.js +134 -0
  56. package/dist/orch/registry.js.map +1 -0
  57. package/dist/orch/runtime.d.ts +11 -0
  58. package/dist/orch/runtime.d.ts.map +1 -0
  59. package/dist/orch/runtime.js +882 -0
  60. package/dist/orch/runtime.js.map +1 -0
  61. package/dist/orch/tools.d.ts +6 -0
  62. package/dist/orch/tools.d.ts.map +1 -0
  63. package/dist/orch/tools.js +114 -0
  64. package/dist/orch/tools.js.map +1 -0
  65. package/dist/orch/transcript.d.ts +28 -0
  66. package/dist/orch/transcript.d.ts.map +1 -0
  67. package/dist/orch/transcript.js +176 -0
  68. package/dist/orch/transcript.js.map +1 -0
  69. package/dist/prefs/agent-import.d.ts +37 -0
  70. package/dist/prefs/agent-import.d.ts.map +1 -0
  71. package/dist/prefs/agent-import.js +196 -0
  72. package/dist/prefs/agent-import.js.map +1 -0
  73. package/dist/prefs/config.d.ts +108 -0
  74. package/dist/prefs/config.d.ts.map +1 -0
  75. package/dist/prefs/config.js +926 -0
  76. package/dist/prefs/config.js.map +1 -0
  77. package/dist/prefs/import-discovery.d.ts +28 -0
  78. package/dist/prefs/import-discovery.d.ts.map +1 -0
  79. package/dist/prefs/import-discovery.js +562 -0
  80. package/dist/prefs/import-discovery.js.map +1 -0
  81. package/dist/prefs/import-instructions.d.ts +3 -0
  82. package/dist/prefs/import-instructions.d.ts.map +1 -0
  83. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +1 -0
  84. package/dist/prefs/import-instructions.js.map +1 -0
  85. package/dist/prefs/models.d.ts +24 -0
  86. package/dist/prefs/models.d.ts.map +1 -0
  87. package/dist/prefs/models.js +57 -0
  88. package/dist/prefs/models.js.map +1 -0
  89. package/dist/prefs/settings.d.ts +89 -0
  90. package/dist/prefs/settings.d.ts.map +1 -0
  91. package/dist/prefs/settings.js +505 -0
  92. package/dist/prefs/settings.js.map +1 -0
  93. package/dist/types.d.ts +293 -0
  94. package/dist/types.d.ts.map +1 -0
  95. package/dist/types.js +2 -0
  96. package/dist/types.js.map +1 -0
  97. package/dist/ui/agent-loader.d.ts +21 -0
  98. package/dist/ui/agent-loader.d.ts.map +1 -0
  99. package/dist/ui/agent-loader.js +73 -0
  100. package/dist/ui/agent-loader.js.map +1 -0
  101. package/dist/ui/agent-navigation-editor.d.ts +46 -0
  102. package/dist/ui/agent-navigation-editor.d.ts.map +1 -0
  103. package/dist/ui/agent-navigation-editor.js +189 -0
  104. package/dist/ui/agent-navigation-editor.js.map +1 -0
  105. package/dist/ui/cost-footer.d.ts +37 -0
  106. package/dist/ui/cost-footer.d.ts.map +1 -0
  107. package/dist/ui/cost-footer.js +215 -0
  108. package/dist/ui/cost-footer.js.map +1 -0
  109. package/dist/ui/dialog.d.ts +135 -0
  110. package/dist/ui/dialog.d.ts.map +1 -0
  111. package/dist/ui/dialog.js +533 -0
  112. package/dist/ui/dialog.js.map +1 -0
  113. package/dist/ui/import-picker.d.ts +38 -0
  114. package/dist/ui/import-picker.d.ts.map +1 -0
  115. package/dist/ui/import-picker.js +211 -0
  116. package/dist/ui/import-picker.js.map +1 -0
  117. package/dist/ui/live-agent-view.d.ts +82 -0
  118. package/dist/ui/live-agent-view.d.ts.map +1 -0
  119. package/dist/ui/live-agent-view.js +546 -0
  120. package/dist/ui/live-agent-view.js.map +1 -0
  121. package/dist/ui/model-picker.d.ts +109 -0
  122. package/dist/ui/model-picker.d.ts.map +1 -0
  123. package/dist/ui/model-picker.js +549 -0
  124. package/dist/ui/model-picker.js.map +1 -0
  125. package/dist/ui/settings-ui.d.ts +17 -0
  126. package/dist/ui/settings-ui.d.ts.map +1 -0
  127. package/dist/ui/settings-ui.js +679 -0
  128. package/dist/ui/settings-ui.js.map +1 -0
  129. package/dist/ui/status-ui.d.ts +67 -0
  130. package/dist/ui/status-ui.d.ts.map +1 -0
  131. package/dist/ui/status-ui.js +487 -0
  132. package/dist/ui/status-ui.js.map +1 -0
  133. package/dist/ui/thread-tree.d.ts +22 -0
  134. package/dist/ui/thread-tree.d.ts.map +1 -0
  135. package/dist/ui/thread-tree.js +153 -0
  136. package/dist/ui/thread-tree.js.map +1 -0
  137. package/dist/ui/tool-picker.d.ts +46 -0
  138. package/dist/ui/tool-picker.d.ts.map +1 -0
  139. package/dist/ui/tool-picker.js +334 -0
  140. package/dist/ui/tool-picker.js.map +1 -0
  141. package/dist/ui/transcript-tool.d.ts +2 -0
  142. package/dist/ui/transcript-tool.d.ts.map +1 -0
  143. package/dist/ui/transcript-tool.js +100 -0
  144. package/dist/ui/transcript-tool.js.map +1 -0
  145. package/dist/ui/ui.d.ts +41 -0
  146. package/dist/ui/ui.d.ts.map +1 -0
  147. package/dist/ui/ui.js +1047 -0
  148. package/dist/ui/ui.js.map +1 -0
  149. package/docs/development.md +2 -1
  150. package/package.json +16 -4
  151. package/src/index.ts +0 -920
  152. package/src/orch/checklist-integration.ts +0 -230
  153. package/src/orch/context-entries.ts +0 -15
  154. package/src/orch/cost-ledger.ts +0 -56
  155. package/src/orch/diagnostics.ts +0 -95
  156. package/src/orch/extensions.ts +0 -83
  157. package/src/orch/housekeeping-usage.ts +0 -47
  158. package/src/orch/housekeeping.ts +0 -348
  159. package/src/orch/inherited-tools.ts +0 -84
  160. package/src/orch/mailbox.ts +0 -261
  161. package/src/orch/manager.ts +0 -1084
  162. package/src/orch/paths.ts +0 -73
  163. package/src/orch/prompt.ts +0 -39
  164. package/src/orch/registry.ts +0 -168
  165. package/src/orch/runtime.ts +0 -1041
  166. package/src/orch/tools.ts +0 -190
  167. package/src/orch/transcript.ts +0 -186
  168. package/src/prefs/agent-import.ts +0 -245
  169. package/src/prefs/config.ts +0 -1017
  170. package/src/prefs/import-discovery.ts +0 -643
  171. package/src/prefs/models.ts +0 -74
  172. package/src/prefs/settings.ts +0 -614
  173. package/src/types.ts +0 -271
  174. package/src/ui/agent-loader.ts +0 -98
  175. package/src/ui/agent-navigation-editor.ts +0 -233
  176. package/src/ui/cost-footer.ts +0 -230
  177. package/src/ui/dialog.ts +0 -678
  178. package/src/ui/import-picker.ts +0 -231
  179. package/src/ui/live-agent-view.ts +0 -600
  180. package/src/ui/model-picker.ts +0 -701
  181. package/src/ui/settings-ui.ts +0 -830
  182. package/src/ui/status-ui.ts +0 -628
  183. package/src/ui/thread-tree.ts +0 -173
  184. package/src/ui/tool-picker.ts +0 -398
  185. package/src/ui/transcript-tool.ts +0 -142
  186. package/src/ui/ui.ts +0 -1407
@@ -1,701 +0,0 @@
1
- import fuzzysort, { type SnapshotKeys } from "fuzzysort";
2
- import type { Api, Model } from "@earendil-works/pi-ai";
3
- import {
4
- getSelectListTheme,
5
- type ExtensionCommandContext,
6
- type ScopedModel,
7
- type Theme,
8
- } from "@earendil-works/pi-coding-agent";
9
- import {
10
- Container,
11
- getKeybindings,
12
- Input,
13
- Key,
14
- matchesKey,
15
- SelectList,
16
- stripTerminalSequences,
17
- truncateToWidth,
18
- Text,
19
- type SelectItem,
20
- } from "@earendil-works/pi-tui";
21
- import { modelIdentity } from "../prefs/models.ts";
22
- import { dialogHeight, frameDialog, DIALOG_OPTIONS } from "./dialog.ts";
23
-
24
- const MODEL_EDITOR_LAYOUT = {
25
- minPrimaryColumnWidth: 24,
26
- maxPrimaryColumnWidth: 52,
27
- } as const;
28
-
29
- const PICKER_TITLE = "Preferred models";
30
- const SELECTED_GROUP = "Selected models · ordered fallback";
31
- const ACTIONS_GROUP = "Actions";
32
-
33
- export const MODEL_EDITOR_CANCEL = Symbol("model-editor-cancel");
34
-
35
- type AvailableModel = Pick<Model<Api>, "provider" | "id" | "name">;
36
-
37
- interface ModelSelectItem extends SelectItem {
38
- group: string;
39
- }
40
-
41
- interface OrderedModelEditorComponentOptions {
42
- tui: { requestRender(force?: boolean): void; terminal?: { rows: number } };
43
- theme: Theme;
44
- availableModels: readonly AvailableModel[];
45
- scopedModels: readonly ScopedModel[];
46
- initialModels?: readonly string[];
47
- modelSuggestions?: readonly string[];
48
- onDone(models: string[]): void;
49
- onCancel(): void;
50
- }
51
-
52
- function sanitizeModelText(text: string): string {
53
- return stripTerminalSequences(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
54
- }
55
-
56
- function renderModelIdentity(identity: string): string {
57
- return sanitizeModelText(identity);
58
- }
59
-
60
- function modelSearchText(text: string): string {
61
- // Providers spell the same version differently (sonnet-5.5 vs sonnet-5-5).
62
- // Strip separators rather than splitting them into repeated numeric terms;
63
- // raw identities and labels remain untouched.
64
- return sanitizeModelText(text).replace(/[._:/-]+/g, "");
65
- }
66
-
67
- function sortModels(models: readonly AvailableModel[]): AvailableModel[] {
68
- const unique = new Map<string, AvailableModel>();
69
- for (const model of models) unique.set(modelIdentity(model), model);
70
- return [...unique.values()].sort(
71
- (a, b) =>
72
- a.provider.localeCompare(b.provider) ||
73
- a.id.localeCompare(b.id) ||
74
- sanitizeModelText(a.name).localeCompare(sanitizeModelText(b.name)),
75
- );
76
- }
77
-
78
- function describeModel(model: AvailableModel, scopedIdentities: ReadonlySet<string>): string {
79
- const annotation = scopedIdentities.has(modelIdentity(model))
80
- ? "scoped in this session"
81
- : "portable preference · not scoped in this session";
82
- const name = sanitizeModelText(model.name);
83
- return [name, annotation].filter(Boolean).join(" · ");
84
- }
85
-
86
- export class OrderedModelEditorComponent extends Container {
87
- private readonly tui: {
88
- requestRender(force?: boolean): void;
89
- terminal?: { rows: number };
90
- };
91
- private readonly theme: Theme;
92
- private readonly allModels: readonly AvailableModel[];
93
- private readonly modelSearch: SnapshotKeys<AvailableModel>;
94
- private readonly suggestedScores: ReadonlyMap<string, number>;
95
- private readonly modelsByIdentity = new Map<string, AvailableModel>();
96
- private readonly scopedIdentities: ReadonlySet<string>;
97
- private readonly onDone: (models: string[]) => void;
98
- private readonly onCancel: () => void;
99
- private readonly titleText = new Text();
100
- private readonly subtitleText = new Text();
101
- private readonly footerText = new Text();
102
- private readonly searchInput = new Input({ placeholder: "Search models" });
103
- private draft: string[];
104
- private pickerQuery = "";
105
- private searching = false;
106
- private currentItems: ModelSelectItem[] = [];
107
- private selectList = new SelectList([], 1, getSelectListTheme(), MODEL_EDITOR_LAYOUT);
108
- private _focused = false;
109
-
110
- constructor(options: OrderedModelEditorComponentOptions) {
111
- super();
112
- this.tui = options.tui;
113
- this.theme = options.theme;
114
- this.allModels = sortModels(options.availableModels);
115
- // The registry is fixed for this dialog; prepare searchable fields once.
116
- // Scope annotations deliberately aren't searchable model metadata.
117
- this.modelSearch = fuzzysort.snapshot(this.allModels, {
118
- keys: [
119
- (model) => modelSearchText(modelIdentity(model)),
120
- (model) => modelSearchText(model.name),
121
- ],
122
- });
123
- this.suggestedScores = this.searchScores(options.modelSuggestions ?? []);
124
- this.onDone = options.onDone;
125
- this.onCancel = options.onCancel;
126
- for (const model of this.allModels) this.modelsByIdentity.set(modelIdentity(model), model);
127
- this.scopedIdentities = new Set(
128
- options.scopedModels.map((entry) => modelIdentity(entry.model)),
129
- );
130
- this.draft = [...new Set(options.initialModels ?? [])];
131
- this.titleText.setText(this.theme.fg("accent", PICKER_TITLE));
132
- this.subtitleText.setText(
133
- this.theme.fg(
134
- "muted",
135
- this.withScopeWarning(
136
- this.suggestedScores.size
137
- ? "Selected first; suggested matches scoped first, then other models; the rest A–Z. / to search."
138
- : "Selected first. / to search by provider/id or model name; other models A–Z.",
139
- ),
140
- ),
141
- );
142
- this.updateFooter();
143
- this.addChild(this.searchInput);
144
- this.refreshPickerList();
145
- }
146
-
147
- get focused(): boolean {
148
- return this._focused;
149
- }
150
-
151
- set focused(value: boolean) {
152
- this._focused = value;
153
- this.searchInput.focused = value && this.searching;
154
- }
155
-
156
- getMode(): "picker" {
157
- return "picker";
158
- }
159
-
160
- getDraftModels(): readonly string[] {
161
- return this.draft;
162
- }
163
-
164
- getCurrentItems(): readonly SelectItem[] {
165
- return this.currentItems;
166
- }
167
-
168
- getSelectList(): SelectList {
169
- return this.selectList;
170
- }
171
-
172
- getSearchInput(): Input {
173
- return this.searchInput;
174
- }
175
-
176
- render(width: number): string[] {
177
- const height = dialogHeight(this.tui);
178
- const inner = Math.max(1, width - 4);
179
- const header = [
180
- truncateToWidth(
181
- this.subtitleText
182
- .render(1000)
183
- .map((line) => line.trim())
184
- .filter(Boolean)
185
- .join(" "),
186
- inner,
187
- "",
188
- ),
189
- ...this.searchInput.render(inner),
190
- ];
191
- const budget = Math.max(1, height - 4 - header.length);
192
- const selected = this.selectList.getSelectedItem()?.value;
193
- // Headings are visual rows only: keyboard navigation selects models, not groups.
194
- const displayRows: (ModelSelectItem | string)[] = [];
195
- let previousGroup: string | undefined;
196
- const hasResults = this.currentItems.some(
197
- (item) => item.group !== SELECTED_GROUP && item.group !== ACTIONS_GROUP,
198
- );
199
- for (const item of this.currentItems) {
200
- if (item.group !== previousGroup) {
201
- if (item.group === ACTIONS_GROUP && !hasResults) displayRows.push("No matching models");
202
- displayRows.push(item.group);
203
- }
204
- previousGroup = item.group;
205
- displayRows.push(item);
206
- }
207
- const index = Math.max(
208
- 0,
209
- displayRows.findIndex((row) => typeof row !== "string" && row.value === selected),
210
- );
211
- const start = Math.max(0, Math.min(index - budget + 1, displayRows.length - budget));
212
- // Only format visible rows; a registry can contain thousands of models.
213
- const rows = displayRows.slice(start, start + budget).map((row) => {
214
- if (typeof row === "string") return this.theme.fg("muted", row);
215
- const text = `${row.value === selected ? "›" : " "} ${row.label} ${this.theme.fg("muted", row.description ?? "")}`;
216
- return row.value === selected ? this.theme.fg("accent", text) : text;
217
- });
218
- return frameDialog(
219
- this.theme,
220
- width,
221
- height,
222
- this.titleText.render(1000).join(" ").trim(),
223
- [...header, ...rows].map((line) => ` ${line}`),
224
- this.footerText
225
- .render(1000)
226
- .map((line) => line.trim())
227
- .filter(Boolean)
228
- .join(" "),
229
- );
230
- }
231
-
232
- handleInput(keyData: string): void {
233
- if (matchesKey(keyData, Key.ctrl("s"))) {
234
- this.onDone([...this.draft]);
235
- return;
236
- }
237
- if (matchesKey(keyData, Key.tab) || (!this.searching && keyData === "/")) {
238
- this.setSearching(!this.searching);
239
- this.tui.requestRender();
240
- return;
241
- }
242
- const earlier = !this.searching && (keyData === "w" || matchesKey(keyData, Key.ctrl("up")));
243
- const later = !this.searching && (keyData === "s" || matchesKey(keyData, Key.ctrl("down")));
244
- if (earlier || later) {
245
- const selected = this.selectList.getSelectedItem()?.value;
246
- const index = selected === undefined ? -1 : this.draft.indexOf(selected);
247
- const next = index + (earlier ? -1 : 1);
248
- // Consume reorder keys even on unselected models or at a list boundary.
249
- if (index >= 0 && next >= 0 && next < this.draft.length) {
250
- [this.draft[index], this.draft[next]] = [this.draft[next], this.draft[index]];
251
- this.refreshPickerList(selected);
252
- this.tui.requestRender();
253
- }
254
- return;
255
- }
256
- const kb = getKeybindings();
257
- const isNav =
258
- kb.matches(keyData, "tui.select.up") ||
259
- kb.matches(keyData, "tui.select.down") ||
260
- kb.matches(keyData, "tui.select.confirm") ||
261
- kb.matches(keyData, "tui.select.cancel");
262
- if (isNav) {
263
- this.selectList.handleInput(keyData);
264
- } else {
265
- this.searchInput.handleInput(keyData);
266
- const nextQuery = this.searchInput.getValue();
267
- if (nextQuery !== this.pickerQuery) {
268
- this.setSearching(true);
269
- this.pickerQuery = nextQuery;
270
- // Keep selected preferences visible, but focus the first search result
271
- // so typing a query and pressing Enter still adds the matching model.
272
- this.refreshPickerList(undefined, true);
273
- }
274
- }
275
- this.tui.requestRender();
276
- }
277
-
278
- private setSearching(value: boolean): void {
279
- this.searching = value;
280
- this.searchInput.focused = this._focused && value;
281
- this.updateFooter();
282
- }
283
-
284
- private updateFooter(): void {
285
- this.footerText.setText(
286
- this.theme.fg(
287
- "dim",
288
- this.searching
289
- ? "↑↓ select · Enter toggle · Tab browse · Ctrl+S done · Esc cancel"
290
- : "↑↓ · Enter toggle · w/s | Ctrlꜛꜜ reorder · / search · Ctrl+S done · Esc cancel",
291
- ),
292
- );
293
- }
294
-
295
- private refreshPickerList(selectedValue?: string, focusSearchResult = false): void {
296
- const previousIndex = this.currentItems.findIndex(
297
- (item) => item.value === this.selectList.getSelectedItem()?.value,
298
- );
299
- this.currentItems = [
300
- ...this.draft.map((identity, index) => ({
301
- value: identity,
302
- label: `[x] ${index + 1}. ${renderModelIdentity(identity)}`,
303
- description: this.describeDraftIdentity(identity),
304
- group: SELECTED_GROUP,
305
- })),
306
- ...this.getPickerItems(),
307
- {
308
- value: "action:done",
309
- label: "Done",
310
- description: "Commit this ordered model preference list",
311
- group: ACTIONS_GROUP,
312
- },
313
- {
314
- value: "action:clear",
315
- label: "Use inherited default",
316
- description: "Clear explicit preferences and inherit the default model",
317
- group: ACTIONS_GROUP,
318
- },
319
- {
320
- value: "action:cancel",
321
- label: "Cancel",
322
- description: "Discard unsaved model preference changes",
323
- group: ACTIONS_GROUP,
324
- },
325
- ];
326
- const list = new SelectList(
327
- this.currentItems,
328
- Math.min(this.currentItems.length, 10),
329
- getSelectListTheme(),
330
- MODEL_EDITOR_LAYOUT,
331
- );
332
- const preferredIndex = focusSearchResult
333
- ? this.currentItems.findIndex(
334
- (item) => item.group !== SELECTED_GROUP && item.group !== ACTIONS_GROUP,
335
- )
336
- : this.currentItems.findIndex((item) => item.value === selectedValue);
337
- list.setSelectedIndex(
338
- preferredIndex >= 0
339
- ? preferredIndex
340
- : focusSearchResult
341
- ? 0
342
- : Math.max(0, Math.min(previousIndex, this.currentItems.length - 1)),
343
- );
344
- list.onSelect = (item) => {
345
- if (this.currentItems.find((row) => row.value === item.value)?.group === ACTIONS_GROUP) {
346
- if (item.value === "action:done") this.onDone([...this.draft]);
347
- else if (item.value === "action:cancel") this.onCancel();
348
- else {
349
- this.draft = [];
350
- this.refreshPickerList("action:done");
351
- this.tui.requestRender();
352
- }
353
- return;
354
- }
355
- const index = this.draft.indexOf(item.value);
356
- if (index >= 0) this.draft.splice(index, 1);
357
- else this.draft.push(item.value);
358
- this.refreshPickerList(item.value);
359
- this.tui.requestRender();
360
- };
361
- list.onSelectionChange = () => this.tui.requestRender();
362
- list.onCancel = () => this.onCancel();
363
- this.selectList = list;
364
- if (this.children[1]) this.children[1] = list;
365
- else this.addChild(list);
366
- }
367
-
368
- private searchScores(queries: readonly string[]): Map<string, number> {
369
- const scores = new Map<string, number>();
370
- const uniqueQueries = new Set(
371
- queries.map((query) => modelSearchText(query).trim()).filter(Boolean),
372
- );
373
- for (const query of uniqueQueries) {
374
- // Both defaults are restrictive (10 results, score >= .5); collect every
375
- // fuzzy match so suggestions aren't silently capped or omitted.
376
- for (const result of fuzzysort.go(query, this.modelSearch, {
377
- limit: 0,
378
- threshold: 0,
379
- })) {
380
- const identity = modelIdentity(result.obj);
381
- scores.set(identity, Math.max(scores.get(identity) ?? 0, result.score));
382
- }
383
- }
384
- return scores;
385
- }
386
-
387
- private getPickerItems(): ModelSelectItem[] {
388
- const excluded = new Set(this.draft);
389
- const query = this.pickerQuery.trim();
390
- const queryScores = query ? this.searchScores([query]) : undefined;
391
- const scoped: AvailableModel[] = [];
392
- const other: AvailableModel[] = [];
393
- const remaining: AvailableModel[] = [];
394
- for (const model of this.allModels) {
395
- const identity = modelIdentity(model);
396
- if (excluded.has(identity) || (queryScores && !queryScores.has(identity))) continue;
397
- if (this.suggestedScores.has(identity)) {
398
- (this.scopedIdentities.has(identity) ? scoped : other).push(model);
399
- } else {
400
- remaining.push(model);
401
- }
402
- }
403
- const bySuggestionScore = (a: AvailableModel, b: AvailableModel) =>
404
- this.suggestedScores.get(modelIdentity(b))! - this.suggestedScores.get(modelIdentity(a))!;
405
- // Stable score sorting preserves alphabetical order for ties. The last
406
- // tier retains the registry's alphabetical order, irrespective of scope.
407
- scoped.sort(bySuggestionScore);
408
- other.sort(bySuggestionScore);
409
- const items = (models: AvailableModel[], group: string): ModelSelectItem[] =>
410
- models.map((model) => ({
411
- value: modelIdentity(model),
412
- label: `[ ] ${renderModelIdentity(modelIdentity(model))}`,
413
- description: describeModel(model, this.scopedIdentities),
414
- group,
415
- }));
416
- return [
417
- ...items(scoped, "Suggested matches · scoped models"),
418
- ...items(other, "Suggested matches · other models"),
419
- ...items(
420
- remaining,
421
- scoped.length || other.length ? "All other models · A–Z" : "All models · A–Z",
422
- ),
423
- ];
424
- }
425
-
426
- private describeDraftIdentity(identity: string): string {
427
- const model = this.modelsByIdentity.get(identity);
428
- if (!model) return "unavailable in current model registry";
429
- return describeModel(model, this.scopedIdentities);
430
- }
431
-
432
- private withScopeWarning(text: string): string {
433
- if (this.scopedIdentities.size === 0) {
434
- return `No scope restriction: Pick First (scoped) uses all available models. ${text}`;
435
- }
436
- return text;
437
- }
438
- }
439
-
440
- export async function editModelPreferences(
441
- ctx: ExtensionCommandContext,
442
- currentModels?: readonly string[],
443
- modelSuggestions?: readonly string[],
444
- ): Promise<readonly string[] | typeof MODEL_EDITOR_CANCEL> {
445
- if (ctx.mode !== "tui") {
446
- if (ctx.hasUI) {
447
- ctx.ui.notify(
448
- "Ordered model preferences require interactive TUI mode; draft unchanged.",
449
- "warning",
450
- );
451
- }
452
- return MODEL_EDITOR_CANCEL;
453
- }
454
- const availableModels = ctx.modelRegistry.getAvailable().map((model) => ({
455
- provider: model.provider,
456
- id: model.id,
457
- name: model.name,
458
- }));
459
- return ctx.ui.custom<readonly string[] | typeof MODEL_EDITOR_CANCEL>(
460
- (tui, theme, _keys, done) =>
461
- new OrderedModelEditorComponent({
462
- tui,
463
- theme,
464
- availableModels,
465
- scopedModels: ctx.scopedModels,
466
- initialModels: currentModels,
467
- modelSuggestions,
468
- onDone: (models) => done(models),
469
- onCancel: () => done(MODEL_EDITOR_CANCEL),
470
- }),
471
- DIALOG_OPTIONS,
472
- );
473
- }
474
-
475
- export const HOUSEKEEPING_PICKER_CANCEL = Symbol("housekeeping-picker-cancel");
476
-
477
- interface HousekeepingRow {
478
- /** `provider/model-id`; empty string clears the selection. */
479
- value: string;
480
- label: string;
481
- description: string;
482
- group: string;
483
- }
484
-
485
- const HOUSEKEEPING_TITLE = "[lab] Housekeeping model";
486
- const CLEAR_GROUP = "Selection";
487
- const SCOPED_GROUP = "Scoped models";
488
- const OTHER_GROUP = "Other available models";
489
-
490
- /**
491
- * Single-select picker over available models, scoped models listed first.
492
- * Typing searches; Enter selects; Esc cancels. "No model" clears the selection.
493
- */
494
- export class HousekeepingModelPickerComponent extends Container {
495
- private readonly tui: { requestRender(force?: boolean): void; terminal?: { rows: number } };
496
- private readonly theme: Theme;
497
- private readonly allModels: readonly AvailableModel[];
498
- private readonly modelSearch: SnapshotKeys<AvailableModel>;
499
- private readonly scopedIdentities: ReadonlySet<string>;
500
- private readonly current: string;
501
- private readonly onDone: (identity: string) => void;
502
- private readonly onCancel: () => void;
503
- private readonly searchInput = new Input({ placeholder: "Search models" });
504
- private rows: HousekeepingRow[] = [];
505
- private selected = 0;
506
- private _focused = false;
507
-
508
- constructor(options: {
509
- tui: { requestRender(force?: boolean): void; terminal?: { rows: number } };
510
- theme: Theme;
511
- availableModels: readonly AvailableModel[];
512
- scopedModels: readonly ScopedModel[];
513
- current?: string;
514
- onDone(identity: string): void;
515
- onCancel(): void;
516
- }) {
517
- super();
518
- this.tui = options.tui;
519
- this.theme = options.theme;
520
- this.allModels = sortModels(options.availableModels);
521
- this.modelSearch = fuzzysort.snapshot(this.allModels, {
522
- keys: [
523
- (model) => modelSearchText(modelIdentity(model)),
524
- (model) => modelSearchText(model.name),
525
- ],
526
- });
527
- this.scopedIdentities = new Set(
528
- options.scopedModels.map((entry) => modelIdentity(entry.model)),
529
- );
530
- this.current = options.current ?? "";
531
- this.onDone = options.onDone;
532
- this.onCancel = options.onCancel;
533
- this.refresh();
534
- }
535
-
536
- get focused(): boolean {
537
- return this._focused;
538
- }
539
-
540
- set focused(value: boolean) {
541
- this._focused = value;
542
- this.searchInput.focused = value;
543
- }
544
-
545
- getRows(): readonly HousekeepingRow[] {
546
- return this.rows;
547
- }
548
-
549
- getSelectedValue(): string | undefined {
550
- return this.rows[this.selected]?.value;
551
- }
552
-
553
- render(width: number): string[] {
554
- const height = dialogHeight(this.tui);
555
- const inner = Math.max(1, width - 4);
556
- const hint = this.scopedIdentities.size
557
- ? "Scoped models first, then every other available model. Type to search."
558
- : "No scoped models in this session; all available models are listed. Type to search.";
559
- const header = [
560
- truncateToWidth(this.theme.fg("muted", hint), inner, ""),
561
- ...this.searchInput.render(inner),
562
- ];
563
- const budget = Math.max(1, height - 4 - header.length);
564
- const display: (HousekeepingRow | string)[] = [];
565
- let previous: string | undefined;
566
- for (const row of this.rows) {
567
- if (row.group !== previous) display.push(row.group);
568
- previous = row.group;
569
- display.push(row);
570
- }
571
- const selectedRow = this.rows[this.selected];
572
- const index = Math.max(
573
- 0,
574
- display.findIndex((row) => row === selectedRow),
575
- );
576
- const start = Math.max(0, Math.min(index - budget + 1, display.length - budget));
577
- const lines = display.slice(start, start + budget).map((row) => {
578
- if (typeof row === "string") return this.theme.fg("muted", row);
579
- const text = `${row === selectedRow ? "›" : " "} ${row.label} ${this.theme.fg("muted", row.description)}`;
580
- return row === selectedRow ? this.theme.fg("accent", text) : text;
581
- });
582
- return frameDialog(
583
- this.theme,
584
- width,
585
- height,
586
- this.theme.fg("accent", HOUSEKEEPING_TITLE),
587
- [...header, ...lines].map((line) => ` ${line}`),
588
- this.theme.fg("dim", "↑↓ select · Enter choose · Esc cancel"),
589
- );
590
- }
591
-
592
- handleInput(keyData: string): void {
593
- const kb = getKeybindings();
594
- if (kb.matches(keyData, "tui.select.cancel")) return this.onCancel();
595
- if (kb.matches(keyData, "tui.select.confirm")) {
596
- const row = this.rows[this.selected];
597
- if (row) this.onDone(row.value);
598
- return;
599
- }
600
- if (kb.matches(keyData, "tui.select.up")) this.selected = Math.max(0, this.selected - 1);
601
- else if (kb.matches(keyData, "tui.select.down"))
602
- this.selected = Math.min(this.rows.length - 1, this.selected + 1);
603
- else if (matchesKey(keyData, Key.pageUp)) this.selected = Math.max(0, this.selected - 10);
604
- else if (matchesKey(keyData, Key.pageDown))
605
- this.selected = Math.min(this.rows.length - 1, this.selected + 10);
606
- else {
607
- const before = this.searchInput.getValue();
608
- this.searchInput.handleInput(keyData);
609
- if (this.searchInput.getValue() !== before) this.refresh(true);
610
- }
611
- this.tui.requestRender();
612
- }
613
-
614
- private refresh(resetSelection = false): void {
615
- const query = modelSearchText(this.searchInput.getValue()).trim();
616
- let matches: AvailableModel[] = [...this.allModels];
617
- if (query) {
618
- const scores = new Map<string, number>();
619
- for (const result of fuzzysort.go(query, this.modelSearch, { limit: 0, threshold: 0 }))
620
- scores.set(modelIdentity(result.obj), result.score);
621
- matches = matches
622
- .filter((model) => scores.has(modelIdentity(model)))
623
- .sort((a, b) => scores.get(modelIdentity(b))! - scores.get(modelIdentity(a))!);
624
- }
625
- const describe = (model: AvailableModel) =>
626
- [sanitizeModelText(model.name), modelIdentity(model) === this.current ? "current" : ""]
627
- .filter(Boolean)
628
- .join(" · ");
629
- const row = (model: AvailableModel, group: string): HousekeepingRow => ({
630
- value: modelIdentity(model),
631
- label: renderModelIdentity(modelIdentity(model)),
632
- description: describe(model),
633
- group,
634
- });
635
- const known = this.allModels.some((model) => modelIdentity(model) === this.current);
636
- const rows: HousekeepingRow[] = [
637
- {
638
- value: "",
639
- label: "No model",
640
- description: "Leave housekeeping without a model (summaries stay inactive)",
641
- group: CLEAR_GROUP,
642
- },
643
- ...(this.current && !known
644
- ? [
645
- {
646
- value: this.current,
647
- label: renderModelIdentity(this.current),
648
- description: "current · unavailable in current model registry",
649
- group: CLEAR_GROUP,
650
- },
651
- ]
652
- : []),
653
- ...matches
654
- .filter((m) => this.scopedIdentities.has(modelIdentity(m)))
655
- .map((m) => row(m, SCOPED_GROUP)),
656
- ...matches
657
- .filter((m) => !this.scopedIdentities.has(modelIdentity(m)))
658
- .map((m) => row(m, OTHER_GROUP)),
659
- ];
660
- const previous = this.rows[this.selected]?.value;
661
- this.rows = rows;
662
- if (resetSelection) {
663
- // Land on the best matching available model, never the clear row or an unavailable saved one.
664
- const first = query ? rows.findIndex((r) => r.group !== CLEAR_GROUP) : -1;
665
- this.selected = Math.max(0, first);
666
- } else {
667
- const kept = rows.findIndex((r) => r.value === previous);
668
- const initial = rows.findIndex((r) => r.value === this.current && this.current !== "");
669
- this.selected = kept >= 0 ? kept : Math.max(0, initial);
670
- }
671
- }
672
- }
673
-
674
- export async function pickHousekeepingModel(
675
- ctx: ExtensionCommandContext,
676
- current: string,
677
- ): Promise<string | typeof HOUSEKEEPING_PICKER_CANCEL> {
678
- if (ctx.mode !== "tui") {
679
- if (ctx.hasUI)
680
- ctx.ui.notify("The housekeeping model picker requires interactive TUI mode.", "warning");
681
- return HOUSEKEEPING_PICKER_CANCEL;
682
- }
683
- const availableModels = ctx.modelRegistry.getAvailable().map((model) => ({
684
- provider: model.provider,
685
- id: model.id,
686
- name: model.name,
687
- }));
688
- return ctx.ui.custom<string | typeof HOUSEKEEPING_PICKER_CANCEL>(
689
- (tui, theme, _keys, done) =>
690
- new HousekeepingModelPickerComponent({
691
- tui,
692
- theme,
693
- availableModels,
694
- scopedModels: ctx.scopedModels,
695
- current,
696
- onDone: (identity) => done(identity),
697
- onCancel: () => done(HOUSEKEEPING_PICKER_CANCEL),
698
- }),
699
- DIALOG_OPTIONS,
700
- );
701
- }