pi-subagent-manager 0.1.1 → 0.3.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,611 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import {
3
+ getSelectListTheme,
4
+ type ExtensionCommandContext,
5
+ type ScopedModel,
6
+ type Theme,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import {
9
+ Container,
10
+ fuzzyFilter,
11
+ getKeybindings,
12
+ Input,
13
+ SelectList,
14
+ Spacer,
15
+ stripTerminalSequences,
16
+ truncateToWidth,
17
+ Text,
18
+ type SelectItem,
19
+ } from "@earendil-works/pi-tui";
20
+ import { modelIdentity } from "./models.ts";
21
+ import { dialogHeight, frameDialog, DIALOG_OPTIONS } from "./dialog.ts";
22
+
23
+ const MODEL_EDITOR_LAYOUT = {
24
+ minPrimaryColumnWidth: 24,
25
+ maxPrimaryColumnWidth: 52,
26
+ } as const;
27
+
28
+ const PICKER_TITLE = "Preferred models";
29
+
30
+ export const MODEL_EDITOR_CANCEL = Symbol("model-editor-cancel");
31
+
32
+ type AvailableModel = Pick<Model<Api>, "provider" | "id" | "name">;
33
+
34
+ type ModelEditorMode =
35
+ | { kind: "menu" }
36
+ | { kind: "actions"; index: number }
37
+ | {
38
+ kind: "picker";
39
+ replaceIndex: number | undefined;
40
+ returnTo: "menu" | "actions";
41
+ };
42
+
43
+ interface OrderedModelEditorComponentOptions {
44
+ tui: { requestRender(force?: boolean): void; terminal?: { rows: number } };
45
+ theme: Theme;
46
+ availableModels: readonly AvailableModel[];
47
+ scopedModels: readonly ScopedModel[];
48
+ initialModels?: readonly string[];
49
+ onDone(models: string[]): void;
50
+ onCancel(): void;
51
+ }
52
+
53
+ function sanitizeModelText(text: string): string {
54
+ return stripTerminalSequences(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
55
+ }
56
+
57
+ function renderModelIdentity(identity: string): string {
58
+ return sanitizeModelText(identity);
59
+ }
60
+
61
+ function sortModels(models: readonly AvailableModel[]): AvailableModel[] {
62
+ const unique = new Map<string, AvailableModel>();
63
+ for (const model of models) unique.set(modelIdentity(model), model);
64
+ return [...unique.values()].sort(
65
+ (a, b) =>
66
+ a.provider.localeCompare(b.provider) ||
67
+ a.id.localeCompare(b.id) ||
68
+ sanitizeModelText(a.name).localeCompare(sanitizeModelText(b.name)),
69
+ );
70
+ }
71
+
72
+ function describeModel(
73
+ model: AvailableModel,
74
+ scopedIdentities: ReadonlySet<string>,
75
+ ): string {
76
+ const annotation = scopedIdentities.has(modelIdentity(model))
77
+ ? "scoped in this session"
78
+ : "portable preference · not scoped in this session";
79
+ const name = sanitizeModelText(model.name);
80
+ return [name, annotation].filter(Boolean).join(" · ");
81
+ }
82
+
83
+ function buildSearchText(
84
+ model: AvailableModel,
85
+ scopedIdentities: ReadonlySet<string>,
86
+ ): string {
87
+ return [
88
+ renderModelIdentity(modelIdentity(model)),
89
+ sanitizeModelText(model.name),
90
+ describeModel(model, scopedIdentities),
91
+ ]
92
+ .filter(Boolean)
93
+ .join(" ");
94
+ }
95
+
96
+ export class OrderedModelEditorComponent extends Container {
97
+ private readonly tui: {
98
+ requestRender(force?: boolean): void;
99
+ terminal?: { rows: number };
100
+ };
101
+ private readonly theme: Theme;
102
+ private readonly allModels: readonly AvailableModel[];
103
+ private readonly modelsByIdentity = new Map<string, AvailableModel>();
104
+ private readonly scopedIdentities: ReadonlySet<string>;
105
+ private readonly onDone: (models: string[]) => void;
106
+ private readonly onCancel: () => void;
107
+ private readonly body = new Container();
108
+ private readonly titleText = new Text();
109
+ private readonly subtitleText = new Text();
110
+ private readonly footerText = new Text();
111
+ private draft: string[];
112
+ private mode: ModelEditorMode;
113
+ private pickerQuery = "";
114
+ private pickerSelectedValue: string | undefined;
115
+ private currentItems: SelectItem[] = [];
116
+ private selectList = new SelectList(
117
+ [],
118
+ 1,
119
+ getSelectListTheme(),
120
+ MODEL_EDITOR_LAYOUT,
121
+ );
122
+ private searchInput: Input | undefined;
123
+ private pickerListChildIndex = -1;
124
+ private menuSelectedValue: string | undefined;
125
+ private actionSelectedValue: string | undefined;
126
+ private _focused = false;
127
+
128
+ constructor(options: OrderedModelEditorComponentOptions) {
129
+ super();
130
+ this.tui = options.tui;
131
+ this.theme = options.theme;
132
+ this.allModels = sortModels(options.availableModels);
133
+ this.onDone = options.onDone;
134
+ this.onCancel = options.onCancel;
135
+ for (const model of this.allModels)
136
+ this.modelsByIdentity.set(modelIdentity(model), model);
137
+ this.scopedIdentities = new Set(
138
+ options.scopedModels.map((entry) => modelIdentity(entry.model)),
139
+ );
140
+ this.draft = [...(options.initialModels ?? [])];
141
+ this.mode =
142
+ this.draft.length === 0
143
+ ? { kind: "picker", replaceIndex: undefined, returnTo: "menu" }
144
+ : { kind: "menu" };
145
+
146
+ this.rebuild();
147
+ }
148
+
149
+ get focused(): boolean {
150
+ return this._focused;
151
+ }
152
+
153
+ set focused(value: boolean) {
154
+ this._focused = value;
155
+ if (this.searchInput) this.searchInput.focused = value;
156
+ }
157
+
158
+ getMode(): ModelEditorMode["kind"] {
159
+ return this.mode.kind;
160
+ }
161
+
162
+ getDraftModels(): readonly string[] {
163
+ return this.draft;
164
+ }
165
+
166
+ getCurrentItems(): readonly SelectItem[] {
167
+ return this.currentItems;
168
+ }
169
+
170
+ getSelectList(): SelectList {
171
+ return this.selectList;
172
+ }
173
+
174
+ getSearchInput(): Input | undefined {
175
+ return this.searchInput;
176
+ }
177
+
178
+ render(width: number): string[] {
179
+ const height = dialogHeight(this.tui);
180
+ const inner = Math.max(1, width - 4);
181
+ const header = [
182
+ truncateToWidth(
183
+ this.subtitleText
184
+ .render(1000)
185
+ .map((line) => line.trim())
186
+ .filter(Boolean)
187
+ .join(" "),
188
+ inner,
189
+ "",
190
+ ),
191
+ ];
192
+ if (this.searchInput) header.push(...this.searchInput.render(inner));
193
+ const budget = Math.max(1, height - 4 - header.length);
194
+ const selected = this.selectList.getSelectedItem()?.value;
195
+ const index = Math.max(
196
+ 0,
197
+ this.currentItems.findIndex((item) => item.value === selected),
198
+ );
199
+ const start = Math.max(
200
+ 0,
201
+ Math.min(index - budget + 1, this.currentItems.length - budget),
202
+ );
203
+ const rows = this.currentItems.slice(start, start + budget).map((item) => {
204
+ const text = `${item.value === selected ? "›" : " "} ${item.label} ${this.theme.fg("muted", item.description ?? "")}`;
205
+ return item.value === selected ? this.theme.fg("accent", text) : text;
206
+ });
207
+ if (!rows.length) rows.push(this.theme.fg("muted", "No matching models"));
208
+ return frameDialog(
209
+ this.theme,
210
+ width,
211
+ height,
212
+ this.titleText.render(1000).join(" ").trim(),
213
+ [...header, ...rows].map((line) => ` ${line}`),
214
+ this.footerText
215
+ .render(1000)
216
+ .map((line) => line.trim())
217
+ .filter(Boolean)
218
+ .join(" "),
219
+ );
220
+ }
221
+
222
+ handleInput(keyData: string): void {
223
+ if (this.mode.kind === "picker" && this.searchInput) {
224
+ const kb = getKeybindings();
225
+ const isNav =
226
+ kb.matches(keyData, "tui.select.up") ||
227
+ kb.matches(keyData, "tui.select.down") ||
228
+ kb.matches(keyData, "tui.select.confirm") ||
229
+ kb.matches(keyData, "tui.select.cancel");
230
+ if (isNav) {
231
+ this.selectList.handleInput(keyData);
232
+ } else {
233
+ this.searchInput.handleInput(keyData);
234
+ const nextQuery = this.searchInput.getValue();
235
+ if (nextQuery !== this.pickerQuery) {
236
+ this.pickerQuery = nextQuery;
237
+ this.pickerSelectedValue = undefined;
238
+ this.refreshPickerList(this.mode.replaceIndex, this.mode.returnTo);
239
+ this.tui.requestRender();
240
+ return;
241
+ }
242
+ }
243
+ this.tui.requestRender();
244
+ return;
245
+ }
246
+ this.selectList.handleInput(keyData);
247
+ this.tui.requestRender();
248
+ }
249
+
250
+ private rebuild(): void {
251
+ this.body.clear();
252
+ this.searchInput = undefined;
253
+ this.pickerListChildIndex = -1;
254
+ if (this.mode.kind === "menu") {
255
+ this.buildMenu();
256
+ } else if (this.mode.kind === "actions") {
257
+ this.buildActions(this.mode.index);
258
+ } else {
259
+ this.buildPicker(this.mode.replaceIndex);
260
+ }
261
+ }
262
+
263
+ private buildMenu(): void {
264
+ this.titleText.setText(this.theme.fg("accent", PICKER_TITLE));
265
+ this.subtitleText.setText(
266
+ this.theme.fg(
267
+ "muted",
268
+ this.withScopeWarning(
269
+ this.draft.length
270
+ ? "Ordered fallback preferences. Select a numbered entry for actions."
271
+ : "No explicit preferences. Add models or done to inherit the default.",
272
+ ),
273
+ ),
274
+ );
275
+ const items: SelectItem[] = [
276
+ ...this.draft.map((identity, index) => ({
277
+ value: `entry:${index}`,
278
+ label: `${index + 1}. ${renderModelIdentity(identity)}`,
279
+ description: this.describeDraftIdentity(identity),
280
+ })),
281
+ {
282
+ value: "action:add",
283
+ label: "Add model",
284
+ description: "Append another preferred model to the ordered list",
285
+ },
286
+ {
287
+ value: "action:clear",
288
+ label: "Use inherited default",
289
+ description: "Clear explicit preferences and inherit the default model",
290
+ },
291
+ {
292
+ value: "action:done",
293
+ label: "Done",
294
+ description: "Commit this ordered model preference list",
295
+ },
296
+ {
297
+ value: "action:cancel",
298
+ label: "Cancel",
299
+ description: "Discard unsaved model preference changes",
300
+ },
301
+ ];
302
+ this.currentItems = items;
303
+ this.selectList = this.buildSelectList(
304
+ items,
305
+ this.menuSelectedValue,
306
+ (value) => {
307
+ if (value.startsWith("entry:")) {
308
+ const index = Number(value.slice("entry:".length));
309
+ if (!Number.isNaN(index) && this.draft[index] !== undefined) {
310
+ this.mode = { kind: "actions", index };
311
+ this.actionSelectedValue = "action:replace";
312
+ this.rebuildAndRender();
313
+ }
314
+ return;
315
+ }
316
+ if (value === "action:add") {
317
+ this.openPicker(undefined, "menu");
318
+ } else if (value === "action:clear") {
319
+ this.draft = [];
320
+ this.menuSelectedValue = "action:done";
321
+ this.rebuildAndRender();
322
+ } else if (value === "action:done") {
323
+ this.onDone([...this.draft]);
324
+ } else if (value === "action:cancel") {
325
+ this.onCancel();
326
+ }
327
+ },
328
+ () => this.onCancel(),
329
+ );
330
+ this.body.addChild(this.selectList);
331
+ this.footerText.setText(
332
+ this.theme.fg(
333
+ "dim",
334
+ "↑↓ select · Enter edit · Esc cancel · Done applies preferences",
335
+ ),
336
+ );
337
+ }
338
+
339
+ private buildActions(index: number): void {
340
+ const identity = this.draft[index] ?? "";
341
+ this.titleText.setText(this.theme.fg("accent", `Model ${index + 1}`));
342
+ this.subtitleText.setText(
343
+ this.theme.fg(
344
+ "muted",
345
+ `${index + 1}. ${renderModelIdentity(identity)} · ${this.describeDraftIdentity(identity)}`,
346
+ ),
347
+ );
348
+ const items: SelectItem[] = [
349
+ {
350
+ value: "action:replace",
351
+ label: "Replace",
352
+ description: "Choose a different available model for this position",
353
+ },
354
+ {
355
+ value: "action:remove",
356
+ label: "Remove",
357
+ description: "Delete this preference from the ordered list",
358
+ },
359
+ ...(index > 0
360
+ ? [
361
+ {
362
+ value: "action:earlier",
363
+ label: "Move earlier",
364
+ description: "Swap with the previous preference",
365
+ },
366
+ ]
367
+ : []),
368
+ ...(index < this.draft.length - 1
369
+ ? [
370
+ {
371
+ value: "action:later",
372
+ label: "Move later",
373
+ description: "Swap with the next preference",
374
+ },
375
+ ]
376
+ : []),
377
+ {
378
+ value: "action:back",
379
+ label: "Back",
380
+ description: "Return to the ordered preference list",
381
+ },
382
+ ];
383
+ this.currentItems = items;
384
+ this.selectList = this.buildSelectList(
385
+ items,
386
+ this.actionSelectedValue,
387
+ (value) => {
388
+ if (value === "action:replace") {
389
+ this.openPicker(index, "actions");
390
+ } else if (value === "action:remove") {
391
+ this.draft.splice(index, 1);
392
+ this.mode = { kind: "menu" };
393
+ this.menuSelectedValue = this.draft[index]
394
+ ? `entry:${index}`
395
+ : "action:add";
396
+ this.rebuildAndRender();
397
+ } else if (value === "action:earlier" && index > 0) {
398
+ [this.draft[index - 1], this.draft[index]] = [
399
+ this.draft[index],
400
+ this.draft[index - 1],
401
+ ];
402
+ this.mode = { kind: "menu" };
403
+ this.menuSelectedValue = `entry:${index - 1}`;
404
+ this.rebuildAndRender();
405
+ } else if (value === "action:later" && index < this.draft.length - 1) {
406
+ [this.draft[index], this.draft[index + 1]] = [
407
+ this.draft[index + 1],
408
+ this.draft[index],
409
+ ];
410
+ this.mode = { kind: "menu" };
411
+ this.menuSelectedValue = `entry:${index + 1}`;
412
+ this.rebuildAndRender();
413
+ } else if (value === "action:back") {
414
+ this.mode = { kind: "menu" };
415
+ this.menuSelectedValue = `entry:${index}`;
416
+ this.rebuildAndRender();
417
+ }
418
+ },
419
+ () => {
420
+ this.mode = { kind: "menu" };
421
+ this.menuSelectedValue = `entry:${index}`;
422
+ this.rebuildAndRender();
423
+ },
424
+ );
425
+ this.body.addChild(this.selectList);
426
+ this.footerText.setText(
427
+ this.theme.fg("dim", "↑↓ select · Enter choose · Esc back"),
428
+ );
429
+ }
430
+
431
+ private buildPicker(replaceIndex: number | undefined): void {
432
+ const isReplace = replaceIndex !== undefined;
433
+ this.titleText.setText(
434
+ this.theme.fg(
435
+ "accent",
436
+ isReplace ? `Replace model ${replaceIndex + 1}` : "Add model",
437
+ ),
438
+ );
439
+ this.subtitleText.setText(
440
+ this.theme.fg(
441
+ "muted",
442
+ this.withScopeWarning(
443
+ "Search by provider/id or model name. Already-selected duplicates are hidden.",
444
+ ),
445
+ ),
446
+ );
447
+ this.searchInput = new Input({ placeholder: "Search models" });
448
+ this.searchInput.setValue(this.pickerQuery);
449
+ this.searchInput.focused = this._focused;
450
+ this.searchInput.onSubmit = () => {
451
+ this.selectList.handleInput("\r");
452
+ this.tui.requestRender();
453
+ };
454
+ this.body.addChild(this.searchInput);
455
+ this.body.addChild(new Spacer(1));
456
+ const returnTo = this.mode.kind === "picker" ? this.mode.returnTo : "menu";
457
+ this.pickerListChildIndex = this.body.children.length;
458
+ this.refreshPickerList(replaceIndex, returnTo);
459
+ this.footerText.setText(
460
+ this.theme.fg("dim", "Type filter · ↑↓ select · Enter choose · Esc back"),
461
+ );
462
+ }
463
+
464
+ private rebuildAndRender(): void {
465
+ this.rebuild();
466
+ this.tui.requestRender();
467
+ }
468
+
469
+ private openPicker(
470
+ replaceIndex: number | undefined,
471
+ returnTo: "menu" | "actions",
472
+ ): void {
473
+ this.mode = { kind: "picker", replaceIndex, returnTo };
474
+ this.pickerQuery = "";
475
+ this.pickerSelectedValue = undefined;
476
+ this.rebuildAndRender();
477
+ }
478
+
479
+ private refreshPickerList(
480
+ replaceIndex: number | undefined,
481
+ returnTo: "menu" | "actions",
482
+ ): void {
483
+ const items = this.getPickerItems(replaceIndex);
484
+ this.currentItems = items;
485
+ const list = this.buildSelectList(
486
+ items,
487
+ this.pickerSelectedValue,
488
+ (value) => {
489
+ if (replaceIndex === undefined) this.draft.push(value);
490
+ else this.draft[replaceIndex] = value;
491
+ this.mode = { kind: "menu" };
492
+ this.menuSelectedValue = `entry:${replaceIndex === undefined ? this.draft.length - 1 : replaceIndex}`;
493
+ this.pickerQuery = "";
494
+ this.pickerSelectedValue = undefined;
495
+ this.rebuildAndRender();
496
+ },
497
+ () => {
498
+ this.mode =
499
+ returnTo === "actions" && replaceIndex !== undefined
500
+ ? { kind: "actions", index: replaceIndex }
501
+ : { kind: "menu" };
502
+ this.pickerQuery = "";
503
+ this.pickerSelectedValue = undefined;
504
+ this.rebuildAndRender();
505
+ },
506
+ );
507
+ this.selectList = list;
508
+ if (this.body.children[this.pickerListChildIndex])
509
+ this.body.children[this.pickerListChildIndex] = list;
510
+ else this.body.addChild(list);
511
+ }
512
+
513
+ private buildSelectList(
514
+ items: SelectItem[],
515
+ selectedValue: string | undefined,
516
+ onSelect: (value: string) => void,
517
+ onCancel: () => void,
518
+ ): SelectList {
519
+ const list = new SelectList(
520
+ items,
521
+ Math.min(Math.max(items.length, 1), 10),
522
+ getSelectListTheme(),
523
+ MODEL_EDITOR_LAYOUT,
524
+ );
525
+ const selectedIndex = selectedValue
526
+ ? items.findIndex((item) => item.value === selectedValue)
527
+ : 0;
528
+ if (selectedIndex >= 0) list.setSelectedIndex(selectedIndex);
529
+ list.onSelect = (item) => {
530
+ if (this.mode.kind === "menu") this.menuSelectedValue = item.value;
531
+ else if (this.mode.kind === "actions")
532
+ this.actionSelectedValue = item.value;
533
+ else this.pickerSelectedValue = item.value;
534
+ onSelect(item.value);
535
+ };
536
+ list.onSelectionChange = (item) => {
537
+ if (this.mode.kind === "menu") this.menuSelectedValue = item.value;
538
+ else if (this.mode.kind === "actions")
539
+ this.actionSelectedValue = item.value;
540
+ else this.pickerSelectedValue = item.value;
541
+ this.tui.requestRender();
542
+ };
543
+ list.onCancel = onCancel;
544
+ return list;
545
+ }
546
+
547
+ private getPickerItems(replaceIndex: number | undefined): SelectItem[] {
548
+ const excluded = new Set(
549
+ this.draft.filter((_, index) => index !== replaceIndex),
550
+ );
551
+ const available = this.allModels.filter(
552
+ (model) => !excluded.has(modelIdentity(model)),
553
+ );
554
+ const filtered = this.pickerQuery
555
+ ? fuzzyFilter(available, this.pickerQuery, (model) =>
556
+ buildSearchText(model, this.scopedIdentities),
557
+ )
558
+ : available;
559
+ return filtered.map((model) => ({
560
+ value: modelIdentity(model),
561
+ label: renderModelIdentity(modelIdentity(model)),
562
+ description: describeModel(model, this.scopedIdentities),
563
+ }));
564
+ }
565
+
566
+ private describeDraftIdentity(identity: string): string {
567
+ const model = this.modelsByIdentity.get(identity);
568
+ if (!model) return "unavailable in current model registry";
569
+ return describeModel(model, this.scopedIdentities);
570
+ }
571
+
572
+ private withScopeWarning(text: string): string {
573
+ if (this.scopedIdentities.size === 0) {
574
+ return `No scoped models: explicit preferences cannot run. Configure /scoped-models. ${text}`;
575
+ }
576
+ return text;
577
+ }
578
+ }
579
+
580
+ export async function editModelPreferences(
581
+ ctx: ExtensionCommandContext,
582
+ currentModels?: readonly string[],
583
+ ): Promise<readonly string[] | typeof MODEL_EDITOR_CANCEL> {
584
+ if (ctx.mode !== "tui") {
585
+ if (ctx.hasUI) {
586
+ ctx.ui.notify(
587
+ "Ordered model preferences require interactive TUI mode; draft unchanged.",
588
+ "warning",
589
+ );
590
+ }
591
+ return MODEL_EDITOR_CANCEL;
592
+ }
593
+ const availableModels = ctx.modelRegistry.getAvailable().map((model) => ({
594
+ provider: model.provider,
595
+ id: model.id,
596
+ name: model.name,
597
+ }));
598
+ return ctx.ui.custom<readonly string[] | typeof MODEL_EDITOR_CANCEL>(
599
+ (tui, theme, _keys, done) =>
600
+ new OrderedModelEditorComponent({
601
+ tui,
602
+ theme,
603
+ availableModels,
604
+ scopedModels: ctx.scopedModels,
605
+ initialModels: currentModels,
606
+ onDone: (models) => done(models),
607
+ onCancel: () => done(MODEL_EDITOR_CANCEL),
608
+ }),
609
+ DIALOG_OPTIONS,
610
+ );
611
+ }
package/src/models.ts ADDED
@@ -0,0 +1,60 @@
1
+ const MODEL_IDENTITY = /^[^\s/]+\/[^\s]+$/;
2
+
3
+ function validateModelPreference(value: unknown, label: string): string {
4
+ if (typeof value !== "string" || !MODEL_IDENTITY.test(value))
5
+ throw new Error(`${label} must be provider/model-id`);
6
+ return value;
7
+ }
8
+
9
+ export function getModelPreferences(type: {
10
+ models?: unknown;
11
+ model?: unknown;
12
+ }): string[] | undefined {
13
+ const hasModels = type.models !== undefined;
14
+ const hasModel = type.model !== undefined;
15
+ if (hasModels && hasModel)
16
+ throw new Error("Specify either models or model, not both");
17
+ if (hasModels) {
18
+ if (!Array.isArray(type.models))
19
+ throw new Error("models must be an array of provider/model-id strings");
20
+ if (type.models.length === 0)
21
+ throw new Error(
22
+ "models must not be empty; omit models to inherit the parent/default model",
23
+ );
24
+ const models = type.models.map((value, index) =>
25
+ validateModelPreference(value, `models[${index}]`),
26
+ );
27
+ if (new Set(models).size !== models.length)
28
+ throw new Error("models contains duplicate entries");
29
+ return [...models];
30
+ }
31
+ if (hasModel) return [validateModelPreference(type.model, "model")];
32
+ return undefined;
33
+ }
34
+
35
+ export function modelIdentity(model: { provider: string; id: string }): string {
36
+ return `${model.provider}/${model.id}`;
37
+ }
38
+
39
+ export function selectPreferredModel(
40
+ type: { name: string; models?: unknown; model?: unknown },
41
+ eligibleModels: readonly { model: { provider: string; id: string } }[],
42
+ scopedModelFiltering = true,
43
+ ): string | undefined {
44
+ const preferences = getModelPreferences(type);
45
+ if (preferences === undefined) return undefined;
46
+ const available = eligibleModels.map(({ model }) => modelIdentity(model));
47
+ for (const preference of preferences) {
48
+ if (available.includes(preference)) return preference;
49
+ }
50
+ const preferenceList = `[${preferences.join(", ")}]`;
51
+ const availableList = available.length === 0 ? "(none)" : `[${available.join(", ")}]`;
52
+ if (!scopedModelFiltering) {
53
+ throw new Error(
54
+ `Agent type ${JSON.stringify(type.name)} prefers models ${preferenceList}, but none are available. Available models: ${availableList}. Update this agent type's models list.`,
55
+ );
56
+ }
57
+ throw new Error(
58
+ `Agent type ${JSON.stringify(type.name)} prefers scoped models ${preferenceList}, but none are available in /scoped-models. Available scoped models: ${availableList}. Update /scoped-models or this agent type's models list.`,
59
+ );
60
+ }