pi-subagent-manager 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/index.ts +10 -10
- package/src/{manager.ts → orch/manager.ts} +2 -2
- package/src/{prompt.ts → orch/prompt.ts} +1 -1
- package/src/{runtime.ts → orch/runtime.ts} +3 -3
- package/src/{tools.ts → orch/tools.ts} +2 -2
- package/src/{agent-import.ts → prefs/agent-import.ts} +2 -2
- package/src/{config.ts → prefs/config.ts} +2 -2
- package/src/{dialog.ts → ui/dialog.ts} +7 -5
- package/src/ui/model-picker.ts +451 -0
- package/src/{settings-ui.ts → ui/settings-ui.ts} +15 -17
- package/src/{status-ui.ts → ui/status-ui.ts} +1 -1
- package/src/{thread-tree.ts → ui/thread-tree.ts} +1 -1
- package/src/{ui.ts → ui/ui.ts} +3 -3
- package/src/model-picker.ts +0 -687
- /package/src/{mailbox.ts → orch/mailbox.ts} +0 -0
- /package/src/{paths.ts → orch/paths.ts} +0 -0
- /package/src/{import-discovery.ts → prefs/import-discovery.ts} +0 -0
- /package/src/{import-instructions.ts → prefs/import-instructions.ts} +0 -0
- /package/src/{models.ts → prefs/models.ts} +0 -0
- /package/src/{settings.ts → prefs/settings.ts} +0 -0
- /package/src/{import-picker.ts → ui/import-picker.ts} +0 -0
package/README.md
CHANGED
|
@@ -141,7 +141,7 @@ Automatic project discovery requires project trust. Only agent definitions are o
|
|
|
141
141
|
|
|
142
142
|
### Configuration and thread UI
|
|
143
143
|
|
|
144
|
-
- `/agents types`: open the bordered agent-definition browser and two-column editor: **field names** on the left, **current values** on the right. **↑↓/Tab** selects fields, **Enter** edits, **Ctrl+S** saves, and **Esc** discards the draft. Multiline field dialogs use **Enter** for a newline and **Ctrl+S** to apply to the draft. Edit the system prompt, models, thinking, tools, color and save scope. Model preferences use an ordered picker:
|
|
144
|
+
- `/agents types`: open the bordered agent-definition browser and two-column editor: **field names** on the left, **current values** on the right. **↑↓/Tab** selects fields, **Enter** edits, **Ctrl+S** saves, and **Esc** discards the draft. Multiline field dialogs use **Enter** for a newline and **Ctrl+S** to apply to the draft. Edit the system prompt, models, thinking, tools, color and save scope. Model preferences use an ordered picker: selected models appear first in fallback order, followed by available models (scoped entries are marked). **Enter** toggles a model, **Ctrl+↑/↓** reorders a selected model without unselecting it, **Ctrl+S** applies preferences, and **Esc** discards changes. Below the selected models, [fuzzysort](https://github.com/farzher/fuzzysort) fuzzy-matches the draft's `modelSuggestions` against provider/id and display name: scoped matches first, other matches next (ranked by best match score), then remaining models alphabetically without duplicates. Typing filters these groups while keeping selected models visible; without suggestions the available models are alphabetical. Suggestions only aid selection and never change runtime model resolution. The YAML editor edits the header together; **External editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
|
|
145
145
|
- `/agents import`: select individual external definitions for model-driven migration.
|
|
146
146
|
- `/agents reload`: reload definitions and show diagnostics.
|
|
147
147
|
- `/agents` or `/agents settings`: open a bordered settings dialog. Choose **Subagent Mode** (**Off**, **Opportunistic**, or **Orchestration**), edit level, concurrency and retained-thread limits, toggle **Scoped model filtering**, choose global or trusted-project scope, and save with **Ctrl+S**. The mode field and chooser explain each option. Settings apply immediately without interrupting existing work. **Agent definitions** opens the type editor.
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -2,16 +2,16 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { buildSessionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { fuzzyFilter } from "@earendil-works/pi-tui";
|
|
5
|
-
import { ConfigStore } from "./config.ts";
|
|
6
|
-
import { IMPORT_REQUEST_PREFIX, markImportOffered, offerAgentImport } from "./agent-import.ts";
|
|
7
|
-
import { ThreadManager } from "./manager.ts";
|
|
8
|
-
import { loadManagerSettings } from "./settings.ts";
|
|
9
|
-
import { configureAgents } from "./settings-ui.ts";
|
|
10
|
-
import { showAgentStatus, showAgentTree } from "./status-ui.ts";
|
|
11
|
-
import { createDriverFactory } from "./runtime.ts";
|
|
12
|
-
import { subagentPrompt } from "./prompt.ts";
|
|
13
|
-
import { agentTools } from "./tools.ts";
|
|
14
|
-
import { editAgentTypes, updateWidget } from "./ui.ts";
|
|
5
|
+
import { ConfigStore } from "./prefs/config.ts";
|
|
6
|
+
import { IMPORT_REQUEST_PREFIX, markImportOffered, offerAgentImport } from "./prefs/agent-import.ts";
|
|
7
|
+
import { ThreadManager } from "./orch/manager.ts";
|
|
8
|
+
import { loadManagerSettings } from "./prefs/settings.ts";
|
|
9
|
+
import { configureAgents } from "./ui/settings-ui.ts";
|
|
10
|
+
import { showAgentStatus, showAgentTree } from "./ui/status-ui.ts";
|
|
11
|
+
import { createDriverFactory } from "./orch/runtime.ts";
|
|
12
|
+
import { subagentPrompt } from "./orch/prompt.ts";
|
|
13
|
+
import { agentTools } from "./orch/tools.ts";
|
|
14
|
+
import { editAgentTypes, updateWidget } from "./ui/ui.ts";
|
|
15
15
|
import type { SavedThread, ThreadEvent } from "./types.ts";
|
|
16
16
|
|
|
17
17
|
const REGISTRY_ENTRY = "pi-subagent:registry:v1";
|
|
@@ -8,9 +8,9 @@ import type {
|
|
|
8
8
|
SavedThreadView,
|
|
9
9
|
ThreadService,
|
|
10
10
|
ThreadView,
|
|
11
|
-
} from "
|
|
11
|
+
} from "../types.ts";
|
|
12
12
|
import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.ts";
|
|
13
|
-
import { DEFAULT_MANAGER_SETTINGS, type ManagerSettings } from "
|
|
13
|
+
import { DEFAULT_MANAGER_SETTINGS, type ManagerSettings } from "../prefs/settings.ts";
|
|
14
14
|
|
|
15
15
|
interface Record {
|
|
16
16
|
view: ThreadView;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ManagerSettings } from "
|
|
1
|
+
import type { ManagerSettings } from "../prefs/settings.ts";
|
|
2
2
|
|
|
3
3
|
/** Root-only guidance: child SDK sessions use their own worker prompt. */
|
|
4
4
|
export function subagentPrompt(settings: ManagerSettings): string | undefined {
|
|
@@ -18,14 +18,14 @@ import {
|
|
|
18
18
|
buildUpdateDetails,
|
|
19
19
|
DurableMailbox,
|
|
20
20
|
} from "./mailbox.ts";
|
|
21
|
-
import { selectTools } from "
|
|
22
|
-
import { modelIdentity, getModelPreferences, selectPreferredModel } from "
|
|
21
|
+
import { selectTools } from "../prefs/config.ts";
|
|
22
|
+
import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.ts";
|
|
23
23
|
import {
|
|
24
24
|
THINKING_LEVELS,
|
|
25
25
|
type DriverFactory,
|
|
26
26
|
type DriverOptions,
|
|
27
27
|
type ThinkingLevel,
|
|
28
|
-
} from "
|
|
28
|
+
} from "../types.ts";
|
|
29
29
|
|
|
30
30
|
const BUILTINS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
|
|
31
31
|
/** Persisted before transcript messages so older-leaf restores still carry ownership. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { getModelPreferences } from "
|
|
3
|
+
import { getModelPreferences } from "../prefs/models.ts";
|
|
4
4
|
import type { ThreadManager } from "./manager.ts";
|
|
5
|
-
import type { AgentType, ThreadView } from "
|
|
5
|
+
import type { AgentType, ThreadView } from "../types.ts";
|
|
6
6
|
|
|
7
7
|
const path = Type.String({ description: "Absolute agent path, or name relative to the caller" });
|
|
8
8
|
const text = Type.String({ minLength: 1 });
|
|
@@ -4,9 +4,9 @@ import { fileURLToPath } from "node:url";
|
|
|
4
4
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { AGENT_COLORS, type ConfigStore } from "./config.ts";
|
|
6
6
|
import { discoverImportCandidates, type ImportCandidate } from "./import-discovery.ts";
|
|
7
|
-
import { selectImportAgents } from "
|
|
7
|
+
import { selectImportAgents } from "../ui/import-picker.ts";
|
|
8
8
|
import { MIGRATION_INSTRUCTIONS } from "./import-instructions.ts";
|
|
9
|
-
import { dialogText } from "
|
|
9
|
+
import { dialogText } from "../ui/dialog.ts";
|
|
10
10
|
|
|
11
11
|
export const IMPORT_REQUEST_PREFIX =
|
|
12
12
|
"Import ONLY the agents I selected in the pi-subagent-manager migration picker.";
|
|
@@ -12,7 +12,7 @@ import { fileURLToPath } from "node:url";
|
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
13
|
import { isMap, isScalar, parseDocument, stringify } from "yaml";
|
|
14
14
|
import { getModelPreferences } from "./models.js";
|
|
15
|
-
import { THINKING_LEVELS, type AgentType } from "
|
|
15
|
+
import { THINKING_LEVELS, type AgentType } from "../types.js";
|
|
16
16
|
|
|
17
17
|
// Pi semantic color tokens, resolved as concrete colors for agent name backgrounds.
|
|
18
18
|
export const AGENT_COLORS = [
|
|
@@ -292,7 +292,7 @@ export class ConfigStore {
|
|
|
292
292
|
const layers: [string, NonNullable<AgentType["source"]>][] = [
|
|
293
293
|
[
|
|
294
294
|
this.options.bundledDir ??
|
|
295
|
-
fileURLToPath(new URL("
|
|
295
|
+
fileURLToPath(new URL("../../agents/", import.meta.url)),
|
|
296
296
|
"bundled",
|
|
297
297
|
],
|
|
298
298
|
...this.scopeDirectories("user").map(
|
|
@@ -224,10 +224,10 @@ export class DialogMenu {
|
|
|
224
224
|
render(width: number): string[] {
|
|
225
225
|
const height = dialogHeight(this.host);
|
|
226
226
|
const inner = Math.max(0, width - 4);
|
|
227
|
-
const help =
|
|
228
|
-
|
|
229
|
-
Math.max(1, inner - 1)
|
|
230
|
-
|
|
227
|
+
const help = (this.rows[this.selected]?.help ?? "")
|
|
228
|
+
.split(/\r\n?|\n/)
|
|
229
|
+
.flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, inner - 1)))
|
|
230
|
+
.slice(0, Math.max(1, height - 7));
|
|
231
231
|
this.viewport = Math.max(1, height - 6 - help.length);
|
|
232
232
|
const start = Math.max(
|
|
233
233
|
0,
|
|
@@ -337,7 +337,9 @@ export async function dialogInput(
|
|
|
337
337
|
"",
|
|
338
338
|
...input.render(Math.max(1, width - 4)).map((line) => ` ${line}`),
|
|
339
339
|
"",
|
|
340
|
-
...
|
|
340
|
+
...help
|
|
341
|
+
.split(/\r\n?|\n/)
|
|
342
|
+
.flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, width - 5)))
|
|
341
343
|
.map((line) => theme.fg("muted", ` ${line}`)),
|
|
342
344
|
],
|
|
343
345
|
"Enter apply · Esc cancel",
|
|
@@ -0,0 +1,451 @@
|
|
|
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 currentItems: ModelSelectItem[] = [];
|
|
106
|
+
private selectList = new SelectList([], 1, getSelectListTheme(), MODEL_EDITOR_LAYOUT);
|
|
107
|
+
private _focused = false;
|
|
108
|
+
|
|
109
|
+
constructor(options: OrderedModelEditorComponentOptions) {
|
|
110
|
+
super();
|
|
111
|
+
this.tui = options.tui;
|
|
112
|
+
this.theme = options.theme;
|
|
113
|
+
this.allModels = sortModels(options.availableModels);
|
|
114
|
+
// The registry is fixed for this dialog; prepare searchable fields once.
|
|
115
|
+
// Scope annotations deliberately aren't searchable model metadata.
|
|
116
|
+
this.modelSearch = fuzzysort.snapshot(this.allModels, {
|
|
117
|
+
keys: [
|
|
118
|
+
(model) => modelSearchText(modelIdentity(model)),
|
|
119
|
+
(model) => modelSearchText(model.name),
|
|
120
|
+
],
|
|
121
|
+
});
|
|
122
|
+
this.suggestedScores = this.searchScores(options.modelSuggestions ?? []);
|
|
123
|
+
this.onDone = options.onDone;
|
|
124
|
+
this.onCancel = options.onCancel;
|
|
125
|
+
for (const model of this.allModels) this.modelsByIdentity.set(modelIdentity(model), model);
|
|
126
|
+
this.scopedIdentities = new Set(
|
|
127
|
+
options.scopedModels.map((entry) => modelIdentity(entry.model)),
|
|
128
|
+
);
|
|
129
|
+
this.draft = [...new Set(options.initialModels ?? [])];
|
|
130
|
+
this.titleText.setText(this.theme.fg("accent", PICKER_TITLE));
|
|
131
|
+
this.subtitleText.setText(
|
|
132
|
+
this.theme.fg(
|
|
133
|
+
"muted",
|
|
134
|
+
this.withScopeWarning(
|
|
135
|
+
this.suggestedScores.size
|
|
136
|
+
? "Selected first; suggested matches scoped first, then other models; the rest A–Z. Type to search."
|
|
137
|
+
: "Selected first. Search by provider/id or model name; other models A–Z.",
|
|
138
|
+
),
|
|
139
|
+
),
|
|
140
|
+
);
|
|
141
|
+
this.footerText.setText(
|
|
142
|
+
this.theme.fg("dim", "↑↓ select · Enter toggle · Ctrl+↑↓ reorder · Ctrl+S done · Esc cancel"),
|
|
143
|
+
);
|
|
144
|
+
this.addChild(this.searchInput);
|
|
145
|
+
this.refreshPickerList();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
get focused(): boolean {
|
|
149
|
+
return this._focused;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
set focused(value: boolean) {
|
|
153
|
+
this._focused = value;
|
|
154
|
+
this.searchInput.focused = value;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
getMode(): "picker" {
|
|
158
|
+
return "picker";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
getDraftModels(): readonly string[] {
|
|
162
|
+
return this.draft;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
getCurrentItems(): readonly SelectItem[] {
|
|
166
|
+
return this.currentItems;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
getSelectList(): SelectList {
|
|
170
|
+
return this.selectList;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
getSearchInput(): Input {
|
|
174
|
+
return this.searchInput;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
render(width: number): string[] {
|
|
178
|
+
const height = dialogHeight(this.tui);
|
|
179
|
+
const inner = Math.max(1, width - 4);
|
|
180
|
+
const header = [
|
|
181
|
+
truncateToWidth(
|
|
182
|
+
this.subtitleText
|
|
183
|
+
.render(1000)
|
|
184
|
+
.map((line) => line.trim())
|
|
185
|
+
.filter(Boolean)
|
|
186
|
+
.join(" "),
|
|
187
|
+
inner,
|
|
188
|
+
"",
|
|
189
|
+
),
|
|
190
|
+
...this.searchInput.render(inner),
|
|
191
|
+
];
|
|
192
|
+
const budget = Math.max(1, height - 4 - header.length);
|
|
193
|
+
const selected = this.selectList.getSelectedItem()?.value;
|
|
194
|
+
// Headings are visual rows only: keyboard navigation selects models, not groups.
|
|
195
|
+
const displayRows: (ModelSelectItem | string)[] = [];
|
|
196
|
+
let previousGroup: string | undefined;
|
|
197
|
+
const hasResults = this.currentItems.some(
|
|
198
|
+
(item) => item.group !== SELECTED_GROUP && item.group !== ACTIONS_GROUP,
|
|
199
|
+
);
|
|
200
|
+
for (const item of this.currentItems) {
|
|
201
|
+
if (item.group !== previousGroup) {
|
|
202
|
+
if (item.group === ACTIONS_GROUP && !hasResults) displayRows.push("No matching models");
|
|
203
|
+
displayRows.push(item.group);
|
|
204
|
+
}
|
|
205
|
+
previousGroup = item.group;
|
|
206
|
+
displayRows.push(item);
|
|
207
|
+
}
|
|
208
|
+
const index = Math.max(
|
|
209
|
+
0,
|
|
210
|
+
displayRows.findIndex((row) => typeof row !== "string" && row.value === selected),
|
|
211
|
+
);
|
|
212
|
+
const start = Math.max(0, Math.min(index - budget + 1, displayRows.length - budget));
|
|
213
|
+
// Only format visible rows; a registry can contain thousands of models.
|
|
214
|
+
const rows = displayRows.slice(start, start + budget).map((row) => {
|
|
215
|
+
if (typeof row === "string") return this.theme.fg("muted", row);
|
|
216
|
+
const text = `${row.value === selected ? "›" : " "} ${row.label} ${this.theme.fg("muted", row.description ?? "")}`;
|
|
217
|
+
return row.value === selected ? this.theme.fg("accent", text) : text;
|
|
218
|
+
});
|
|
219
|
+
return frameDialog(
|
|
220
|
+
this.theme,
|
|
221
|
+
width,
|
|
222
|
+
height,
|
|
223
|
+
this.titleText.render(1000).join(" ").trim(),
|
|
224
|
+
[...header, ...rows].map((line) => ` ${line}`),
|
|
225
|
+
this.footerText
|
|
226
|
+
.render(1000)
|
|
227
|
+
.map((line) => line.trim())
|
|
228
|
+
.filter(Boolean)
|
|
229
|
+
.join(" "),
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
handleInput(keyData: string): void {
|
|
234
|
+
if (matchesKey(keyData, Key.ctrl("s"))) {
|
|
235
|
+
this.onDone([...this.draft]);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const earlier = matchesKey(keyData, Key.ctrl("up"));
|
|
239
|
+
const later = matchesKey(keyData, Key.ctrl("down"));
|
|
240
|
+
if (earlier || later) {
|
|
241
|
+
const selected = this.selectList.getSelectedItem()?.value;
|
|
242
|
+
const index = selected === undefined ? -1 : this.draft.indexOf(selected);
|
|
243
|
+
const next = index + (earlier ? -1 : 1);
|
|
244
|
+
// Consume reorder keys even on unselected models or at a list boundary.
|
|
245
|
+
if (index >= 0 && next >= 0 && next < this.draft.length) {
|
|
246
|
+
[this.draft[index], this.draft[next]] = [this.draft[next], this.draft[index]];
|
|
247
|
+
this.refreshPickerList(selected);
|
|
248
|
+
this.tui.requestRender();
|
|
249
|
+
}
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const kb = getKeybindings();
|
|
253
|
+
const isNav =
|
|
254
|
+
kb.matches(keyData, "tui.select.up") ||
|
|
255
|
+
kb.matches(keyData, "tui.select.down") ||
|
|
256
|
+
kb.matches(keyData, "tui.select.confirm") ||
|
|
257
|
+
kb.matches(keyData, "tui.select.cancel");
|
|
258
|
+
if (isNav) {
|
|
259
|
+
this.selectList.handleInput(keyData);
|
|
260
|
+
} else {
|
|
261
|
+
this.searchInput.handleInput(keyData);
|
|
262
|
+
const nextQuery = this.searchInput.getValue();
|
|
263
|
+
if (nextQuery !== this.pickerQuery) {
|
|
264
|
+
this.pickerQuery = nextQuery;
|
|
265
|
+
// Keep selected preferences visible, but focus the first search result
|
|
266
|
+
// so typing a query and pressing Enter still adds the matching model.
|
|
267
|
+
this.refreshPickerList(undefined, true);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
this.tui.requestRender();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private refreshPickerList(selectedValue?: string, focusSearchResult = false): void {
|
|
274
|
+
const previousIndex = this.currentItems.findIndex(
|
|
275
|
+
(item) => item.value === this.selectList.getSelectedItem()?.value,
|
|
276
|
+
);
|
|
277
|
+
this.currentItems = [
|
|
278
|
+
...this.draft.map((identity, index) => ({
|
|
279
|
+
value: identity,
|
|
280
|
+
label: `[x] ${index + 1}. ${renderModelIdentity(identity)}`,
|
|
281
|
+
description: this.describeDraftIdentity(identity),
|
|
282
|
+
group: SELECTED_GROUP,
|
|
283
|
+
})),
|
|
284
|
+
...this.getPickerItems(),
|
|
285
|
+
{
|
|
286
|
+
value: "action:done",
|
|
287
|
+
label: "Done",
|
|
288
|
+
description: "Commit this ordered model preference list",
|
|
289
|
+
group: ACTIONS_GROUP,
|
|
290
|
+
},
|
|
291
|
+
{
|
|
292
|
+
value: "action:clear",
|
|
293
|
+
label: "Use inherited default",
|
|
294
|
+
description: "Clear explicit preferences and inherit the default model",
|
|
295
|
+
group: ACTIONS_GROUP,
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
value: "action:cancel",
|
|
299
|
+
label: "Cancel",
|
|
300
|
+
description: "Discard unsaved model preference changes",
|
|
301
|
+
group: ACTIONS_GROUP,
|
|
302
|
+
},
|
|
303
|
+
];
|
|
304
|
+
const list = new SelectList(
|
|
305
|
+
this.currentItems,
|
|
306
|
+
Math.min(this.currentItems.length, 10),
|
|
307
|
+
getSelectListTheme(),
|
|
308
|
+
MODEL_EDITOR_LAYOUT,
|
|
309
|
+
);
|
|
310
|
+
const preferredIndex = focusSearchResult
|
|
311
|
+
? this.currentItems.findIndex(
|
|
312
|
+
(item) => item.group !== SELECTED_GROUP && item.group !== ACTIONS_GROUP,
|
|
313
|
+
)
|
|
314
|
+
: this.currentItems.findIndex((item) => item.value === selectedValue);
|
|
315
|
+
list.setSelectedIndex(
|
|
316
|
+
preferredIndex >= 0
|
|
317
|
+
? preferredIndex
|
|
318
|
+
: focusSearchResult
|
|
319
|
+
? 0
|
|
320
|
+
: Math.max(0, Math.min(previousIndex, this.currentItems.length - 1)),
|
|
321
|
+
);
|
|
322
|
+
list.onSelect = (item) => {
|
|
323
|
+
if (this.currentItems.find((row) => row.value === item.value)?.group === ACTIONS_GROUP) {
|
|
324
|
+
if (item.value === "action:done") this.onDone([...this.draft]);
|
|
325
|
+
else if (item.value === "action:cancel") this.onCancel();
|
|
326
|
+
else {
|
|
327
|
+
this.draft = [];
|
|
328
|
+
this.refreshPickerList("action:done");
|
|
329
|
+
this.tui.requestRender();
|
|
330
|
+
}
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const index = this.draft.indexOf(item.value);
|
|
334
|
+
if (index >= 0) this.draft.splice(index, 1);
|
|
335
|
+
else this.draft.push(item.value);
|
|
336
|
+
this.refreshPickerList(item.value);
|
|
337
|
+
this.tui.requestRender();
|
|
338
|
+
};
|
|
339
|
+
list.onSelectionChange = () => this.tui.requestRender();
|
|
340
|
+
list.onCancel = () => this.onCancel();
|
|
341
|
+
this.selectList = list;
|
|
342
|
+
if (this.children[1]) this.children[1] = list;
|
|
343
|
+
else this.addChild(list);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private searchScores(queries: readonly string[]): Map<string, number> {
|
|
347
|
+
const scores = new Map<string, number>();
|
|
348
|
+
const uniqueQueries = new Set(
|
|
349
|
+
queries.map((query) => modelSearchText(query).trim()).filter(Boolean),
|
|
350
|
+
);
|
|
351
|
+
for (const query of uniqueQueries) {
|
|
352
|
+
// Both defaults are restrictive (10 results, score >= .5); collect every
|
|
353
|
+
// fuzzy match so suggestions aren't silently capped or omitted.
|
|
354
|
+
for (const result of fuzzysort.go(query, this.modelSearch, {
|
|
355
|
+
limit: 0,
|
|
356
|
+
threshold: 0,
|
|
357
|
+
})) {
|
|
358
|
+
const identity = modelIdentity(result.obj);
|
|
359
|
+
scores.set(identity, Math.max(scores.get(identity) ?? 0, result.score));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return scores;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
private getPickerItems(): ModelSelectItem[] {
|
|
366
|
+
const excluded = new Set(this.draft);
|
|
367
|
+
const query = this.pickerQuery.trim();
|
|
368
|
+
const queryScores = query ? this.searchScores([query]) : undefined;
|
|
369
|
+
const scoped: AvailableModel[] = [];
|
|
370
|
+
const other: AvailableModel[] = [];
|
|
371
|
+
const remaining: AvailableModel[] = [];
|
|
372
|
+
for (const model of this.allModels) {
|
|
373
|
+
const identity = modelIdentity(model);
|
|
374
|
+
if (excluded.has(identity) || (queryScores && !queryScores.has(identity))) continue;
|
|
375
|
+
if (this.suggestedScores.has(identity)) {
|
|
376
|
+
(this.scopedIdentities.has(identity) ? scoped : other).push(model);
|
|
377
|
+
} else {
|
|
378
|
+
remaining.push(model);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const bySuggestionScore = (a: AvailableModel, b: AvailableModel) =>
|
|
382
|
+
this.suggestedScores.get(modelIdentity(b))! - this.suggestedScores.get(modelIdentity(a))!;
|
|
383
|
+
// Stable score sorting preserves alphabetical order for ties. The last
|
|
384
|
+
// tier retains the registry's alphabetical order, irrespective of scope.
|
|
385
|
+
scoped.sort(bySuggestionScore);
|
|
386
|
+
other.sort(bySuggestionScore);
|
|
387
|
+
const items = (models: AvailableModel[], group: string): ModelSelectItem[] =>
|
|
388
|
+
models.map((model) => ({
|
|
389
|
+
value: modelIdentity(model),
|
|
390
|
+
label: `[ ] ${renderModelIdentity(modelIdentity(model))}`,
|
|
391
|
+
description: describeModel(model, this.scopedIdentities),
|
|
392
|
+
group,
|
|
393
|
+
}));
|
|
394
|
+
return [
|
|
395
|
+
...items(scoped, "Suggested matches · scoped models"),
|
|
396
|
+
...items(other, "Suggested matches · other models"),
|
|
397
|
+
...items(
|
|
398
|
+
remaining,
|
|
399
|
+
scoped.length || other.length ? "All other models · A–Z" : "All models · A–Z",
|
|
400
|
+
),
|
|
401
|
+
];
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private describeDraftIdentity(identity: string): string {
|
|
405
|
+
const model = this.modelsByIdentity.get(identity);
|
|
406
|
+
if (!model) return "unavailable in current model registry";
|
|
407
|
+
return describeModel(model, this.scopedIdentities);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
private withScopeWarning(text: string): string {
|
|
411
|
+
if (this.scopedIdentities.size === 0) {
|
|
412
|
+
return `No scoped models: explicit preferences cannot run. Configure /scoped-models. ${text}`;
|
|
413
|
+
}
|
|
414
|
+
return text;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
export async function editModelPreferences(
|
|
419
|
+
ctx: ExtensionCommandContext,
|
|
420
|
+
currentModels?: readonly string[],
|
|
421
|
+
modelSuggestions?: readonly string[],
|
|
422
|
+
): Promise<readonly string[] | typeof MODEL_EDITOR_CANCEL> {
|
|
423
|
+
if (ctx.mode !== "tui") {
|
|
424
|
+
if (ctx.hasUI) {
|
|
425
|
+
ctx.ui.notify(
|
|
426
|
+
"Ordered model preferences require interactive TUI mode; draft unchanged.",
|
|
427
|
+
"warning",
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
return MODEL_EDITOR_CANCEL;
|
|
431
|
+
}
|
|
432
|
+
const availableModels = ctx.modelRegistry.getAvailable().map((model) => ({
|
|
433
|
+
provider: model.provider,
|
|
434
|
+
id: model.id,
|
|
435
|
+
name: model.name,
|
|
436
|
+
}));
|
|
437
|
+
return ctx.ui.custom<readonly string[] | typeof MODEL_EDITOR_CANCEL>(
|
|
438
|
+
(tui, theme, _keys, done) =>
|
|
439
|
+
new OrderedModelEditorComponent({
|
|
440
|
+
tui,
|
|
441
|
+
theme,
|
|
442
|
+
availableModels,
|
|
443
|
+
scopedModels: ctx.scopedModels,
|
|
444
|
+
initialModels: currentModels,
|
|
445
|
+
modelSuggestions,
|
|
446
|
+
onDone: (models) => done(models),
|
|
447
|
+
onCancel: () => done(MODEL_EDITOR_CANCEL),
|
|
448
|
+
}),
|
|
449
|
+
DIALOG_OPTIONS,
|
|
450
|
+
);
|
|
451
|
+
}
|