@restranger/repi-model-fallback 0.0.0-stage → 0.0.1-44677f3

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/src/menu-ui.ts ADDED
@@ -0,0 +1,762 @@
1
+ import type { PiModel, SubagentSummary } from "@restranger/repi-lib";
2
+ import {
3
+ NativeMenuView,
4
+ clamp,
5
+ fuzzyScore,
6
+ isPrintable,
7
+ mouseWheelDirection,
8
+ primaryColumnWidth,
9
+ } from "@restranger/repi-ui";
10
+ import { boldText, sanitize, truncate } from "./format.js";
11
+
12
+ export interface FallbackAgentEntry {
13
+ readonly id: string;
14
+ readonly name: string;
15
+ readonly isMain: boolean;
16
+ readonly primaryModel: string;
17
+ fallbackModels: string[];
18
+ }
19
+
20
+ export interface FallbackMenuViewOptions {
21
+ readonly mainModel?: PiModel;
22
+ readonly mainFallbacks: readonly string[];
23
+ readonly subagents: readonly SubagentSummary[];
24
+ readonly advisor?: {
25
+ readonly model?: string;
26
+ readonly fallbackModels?: readonly string[];
27
+ };
28
+ readonly availableModels: readonly PiModel[];
29
+ readonly onSave: (entries: readonly FallbackAgentEntry[]) => void;
30
+ readonly onDone?: () => void;
31
+ readonly maxRows?: number;
32
+ }
33
+
34
+ /** A model offered by the picker, already reduced to what a list row needs. */
35
+ interface ModelCandidate {
36
+ /** `provider/id`, or `inherit` for the subagent inheritance sentinel. */
37
+ readonly id: string;
38
+ readonly label: string;
39
+ readonly description: string;
40
+ /** Lowercased haystack for the search field. */
41
+ readonly search: string;
42
+ /** Provider used by the "toggle provider" action; undefined for `inherit`. */
43
+ readonly provider?: string;
44
+ /** The model is in the chain but is not currently available; it can only be removed. */
45
+ readonly unavailable?: boolean;
46
+ }
47
+
48
+ const MIN_WIDTH = 36;
49
+ const INHERIT_ID = "inherit";
50
+
51
+ const INHERIT_CANDIDATE: ModelCandidate = {
52
+ id: INHERIT_ID,
53
+ label: INHERIT_ID,
54
+ description: "parent session model",
55
+ search: INHERIT_ID,
56
+ };
57
+
58
+ /**
59
+ * `/fallback` menu, rendered the way Pi's own pickers (`/models`, `/scoped-models`, `ctx.ui.select`)
60
+ * render: a content-sized inline frame, no box, no second pane and no full-screen overlay.
61
+ *
62
+ * The roster picks an agent; the model screen is a multi-select editor modelled on Pi's
63
+ * `/scoped-models`: `Enter` toggles a model, `Ctrl+A`/`Ctrl+X` enable or clear the filtered list,
64
+ * `Ctrl+P` toggles the selected model's provider, `Alt+↑/↓` reorders the fallback chain and
65
+ * `Ctrl+S` persists. Enabled models are listed first, in chain order, with a `#n` rank.
66
+ *
67
+ * ```text
68
+ * ────────────────────────────────────────────────────────────────
69
+ * Model fallback
70
+ * 4 agents · google/gemini-3-pro
71
+ *
72
+ * → Main Agent google/gemini-3-pro · 2 fallbacks
73
+ * Explore inherit · 1 fallback
74
+ * Plan inherit · no fallbacks
75
+ *
76
+ * Fallback chain 1. anthropic/claude-sonnet-4.5 · 2. openai/gpt-5.1
77
+ *
78
+ * ↑↓ agent Enter models Ctrl+S save Esc close
79
+ * ────────────────────────────────────────────────────────────────
80
+ * ```
81
+ */
82
+ export class FallbackMenuView extends NativeMenuView {
83
+ private mode: "agents" | "models" = "agents";
84
+ private selectedModel = 0;
85
+ private query = "";
86
+ private notice?: string;
87
+ private dirty = false;
88
+
89
+ private readonly agents: FallbackAgentEntry[];
90
+ private readonly candidates: readonly ModelCandidate[];
91
+
92
+ constructor(private readonly options: FallbackMenuViewOptions) {
93
+ super({ maxRows: options.maxRows });
94
+ const mainModelName = options.mainModel ? `${options.mainModel.provider}/${options.mainModel.id}` : "parent model";
95
+
96
+ const mainEntry: FallbackAgentEntry = {
97
+ id: "main",
98
+ name: "Main Agent",
99
+ isMain: true,
100
+ primaryModel: mainModelName,
101
+ fallbackModels: [...options.mainFallbacks],
102
+ };
103
+
104
+ const advisorEntry: FallbackAgentEntry | undefined = options.advisor?.model
105
+ ? {
106
+ id: "advisor",
107
+ name: "Advisor",
108
+ isMain: false,
109
+ primaryModel: options.advisor.model,
110
+ fallbackModels: [...(options.advisor.fallbackModels ?? [])],
111
+ }
112
+ : undefined;
113
+
114
+ const subagentEntries: FallbackAgentEntry[] = options.subagents.map((sub) => ({
115
+ id: sub.name,
116
+ name: sub.name,
117
+ isMain: false,
118
+ primaryModel: sub.model ?? INHERIT_ID,
119
+ fallbackModels: [...(sub.fallbackModels ?? [])],
120
+ }));
121
+
122
+ this.agents = [mainEntry, ...(advisorEntry ? [advisorEntry] : []), ...subagentEntries];
123
+
124
+ const seen = new Set<string>();
125
+ const candidates: ModelCandidate[] = [];
126
+ for (const model of options.availableModels) {
127
+ const id = `${model.provider}/${model.id}`;
128
+ if (seen.has(id)) {
129
+ continue;
130
+ }
131
+ seen.add(id);
132
+ const provider = `[${model.provider}]`;
133
+ const name = model.name ? ` ${model.name}` : "";
134
+ candidates.push({
135
+ id,
136
+ label: model.id,
137
+ description: provider,
138
+ search: `${model.id} ${model.provider}${name}`,
139
+ provider: model.provider,
140
+ });
141
+ }
142
+ candidates.sort((left, right) => left.id.localeCompare(right.id));
143
+ this.candidates = candidates;
144
+ }
145
+
146
+ /** Number of rows the base class moves through with ↑/↓. */
147
+ protected itemCount(): number {
148
+ return this.agents.length;
149
+ }
150
+
151
+ /** A new agent clears the transient notice, like the previous roster did. */
152
+ protected onSelectionChanged(): void {
153
+ this.notice = undefined;
154
+ }
155
+
156
+ protected onClose(): void {
157
+ this.options.onDone?.();
158
+ }
159
+
160
+ refresh(): void {
161
+ super.refresh();
162
+ this.clampModelSelection();
163
+ }
164
+
165
+ handleInput(data: string): void {
166
+ if (this.mode === "models") {
167
+ this.handlePickerInput(data);
168
+ return;
169
+ }
170
+
171
+ if (data === "q" || this.matches(data, "tui.select.cancel")) {
172
+ this.close();
173
+ return;
174
+ }
175
+
176
+ if (this.isUp(data)) {
177
+ this.moveAgent(-1);
178
+ return;
179
+ }
180
+
181
+ if (this.isDown(data)) {
182
+ this.moveAgent(1);
183
+ return;
184
+ }
185
+
186
+ if (data === "\x1b[H") {
187
+ this.select(0);
188
+ return;
189
+ }
190
+
191
+ if (data === "\x1b[F") {
192
+ this.select(this.agents.length - 1);
193
+ return;
194
+ }
195
+
196
+ if (data === "\x1b[5~" || this.matches(data, "tui.select.pageUp")) {
197
+ this.moveAgent(-this.pageStep());
198
+ return;
199
+ }
200
+
201
+ if (data === "\x1b[6~" || this.matches(data, "tui.select.pageDown")) {
202
+ this.moveAgent(this.pageStep());
203
+ return;
204
+ }
205
+
206
+ if (this.isSave(data) || data === "s" || data === "S") {
207
+ this.save();
208
+ return;
209
+ }
210
+
211
+ if (data === "a" || data === "A" || data === "\r" || data === "\n" || this.matches(data, "tui.select.confirm")) {
212
+ this.openPicker();
213
+ }
214
+ }
215
+
216
+ render(width: number): string[] {
217
+ const terminalWidth = Math.max(1, Math.floor(width));
218
+ if (terminalWidth < MIN_WIDTH) {
219
+ return [truncate("Model fallback needs at least 36 columns. Esc closes.", terminalWidth)];
220
+ }
221
+ const lines = this.mode === "models" ? this.renderPicker(terminalWidth) : this.renderAgents(terminalWidth);
222
+ return lines.map((line) => truncate(line, terminalWidth));
223
+ }
224
+
225
+ // --- agents screen -------------------------------------------------------------------------
226
+
227
+ private renderAgents(width: number): string[] {
228
+ const selected = this.agents[this.selected];
229
+ const chain = this.agentChainLines(selected, width);
230
+ const hints = this.packHints(this.agentsHints(), width);
231
+ const frameRows = 9 + chain.length + hints.length + (this.notice ? 2 : 0);
232
+ const maxVisible = this.maxVisibleRows(frameRows);
233
+ const lines: string[] = [
234
+ this.rule(width),
235
+ "",
236
+ this.pad(this.paint("accent", boldText(this.theme, "Model fallback")), width),
237
+ this.pad(this.agentsSubtitle(), width),
238
+ "",
239
+ ...this.agentRows(width, maxVisible),
240
+ ];
241
+
242
+ if (this.notice) {
243
+ lines.push("", this.pad(this.paint("warning", this.notice), width));
244
+ }
245
+
246
+ lines.push("", ...chain, "", ...hints, "", this.rule(width));
247
+ return lines;
248
+ }
249
+
250
+ private agentsSubtitle(): string {
251
+ const count = this.agents.length;
252
+ const agents = `${count} agent${count === 1 ? "" : "s"}`;
253
+ const main = this.agents[0]?.primaryModel ?? "no parent model";
254
+ const base = this.paint("dim", `${agents} · ${main}`);
255
+ return this.dirty ? `${base}${this.paint("warning", " · unsaved")}` : base;
256
+ }
257
+
258
+ private agentRows(width: number, maxVisible: number): string[] {
259
+ const count = this.agents.length;
260
+ if (count === 0) {
261
+ return [this.pad(this.paint("warning", "No agents configured"), width)];
262
+ }
263
+ const primary = primaryColumnWidth(this.agents.map((agent) => agent.name));
264
+ const start = this.windowStart(this.selected, count, maxVisible);
265
+ const end = Math.min(start + maxVisible, count);
266
+ const lines: string[] = [];
267
+ for (let index = start; index < end; index++) {
268
+ const agent = this.agents[index];
269
+ if (!agent) {
270
+ continue;
271
+ }
272
+ lines.push(
273
+ this.row(width, {
274
+ selected: index === this.selected,
275
+ cursor: "→ ",
276
+ marker: false,
277
+ checked: false,
278
+ label: agent.name,
279
+ description: this.agentDescription(agent),
280
+ primary,
281
+ }),
282
+ );
283
+ }
284
+ if (start > 0 || end < count) {
285
+ lines.push(this.scrollInfo(this.selected + 1, count, width));
286
+ }
287
+ return lines;
288
+ }
289
+
290
+ private agentDescription(agent: FallbackAgentEntry): string {
291
+ const count = agent.fallbackModels.length;
292
+ const chain = count === 0 ? "no fallbacks" : `${count} fallback${count === 1 ? "" : "s"}`;
293
+ return `${agent.primaryModel} · ${chain}`;
294
+ }
295
+
296
+ /** Selected agent's chain, wrapped like `/models` shows the selected model's name. */
297
+ private agentChainLines(agent: FallbackAgentEntry | undefined, width: number): string[] {
298
+ return agent ? super.chainLines("Fallback chain", agent.fallbackModels, width) : [];
299
+ }
300
+
301
+ private agentsHints(): string[] {
302
+ return [
303
+ this.hint(this.navLabel(), "agent"),
304
+ this.hint(this.hintLabel("tui.select.confirm", "Enter"), "models"),
305
+ this.hint(this.hintLabel("app.models.save", "Ctrl+S"), "save"),
306
+ this.hint(this.hintLabel("tui.select.cancel", "Esc"), "close"),
307
+ ];
308
+ }
309
+
310
+ // --- model picker --------------------------------------------------------------------------
311
+
312
+ private renderPicker(width: number): string[] {
313
+ const agent = this.agents[this.selected];
314
+ const candidates = this.visibleCandidates(agent);
315
+ const hints = this.packHints(this.pickerHints(), width);
316
+ const frameRows = 10 + hints.length + (this.notice ? 2 : 0);
317
+ const maxVisible = this.maxVisibleRows(frameRows);
318
+ const lines: string[] = [
319
+ this.rule(width),
320
+ "",
321
+ this.pad(this.paint("accent", boldText(this.theme, "Model fallback")), width),
322
+ this.pad(this.pickerSubtitle(agent), width),
323
+ "",
324
+ this.pad(this.searchLine(), width, 0),
325
+ "",
326
+ ...this.candidateRows(width, maxVisible, candidates, agent),
327
+ ];
328
+
329
+ if (this.notice) {
330
+ lines.push("", this.pad(this.paint("warning", this.notice), width));
331
+ }
332
+
333
+ lines.push("", ...hints, "", this.rule(width));
334
+ return lines;
335
+ }
336
+
337
+ private pickerSubtitle(agent: FallbackAgentEntry | undefined): string {
338
+ if (!agent) {
339
+ return this.paint("dim", "no agent");
340
+ }
341
+ const stats = this.chainStats(agent);
342
+ const parts = [sanitize(agent.name), `${stats.enabled}/${stats.total} models`];
343
+ if (stats.unavailable > 0) {
344
+ parts.push(`${stats.unavailable} unavailable`);
345
+ }
346
+ let text = this.paint("dim", parts.join(" · "));
347
+ if (this.dirty) {
348
+ text += this.paint("warning", " · unsaved");
349
+ }
350
+ return text;
351
+ }
352
+
353
+ private chainStats(agent: FallbackAgentEntry): { enabled: number; total: number; unavailable: number } {
354
+ const known = new Set(this.candidates.map((candidate) => candidate.id));
355
+ const total = this.candidates.length + (agent.isMain ? 0 : 1);
356
+ let enabled = 0;
357
+ let unavailable = 0;
358
+ for (const id of agent.fallbackModels) {
359
+ if (id === INHERIT_ID && !agent.isMain) {
360
+ enabled++;
361
+ } else if (known.has(id)) {
362
+ enabled++;
363
+ } else {
364
+ unavailable++;
365
+ }
366
+ }
367
+ return { enabled, total, unavailable };
368
+ }
369
+
370
+ private searchLine(): string {
371
+ return `> ${sanitize(this.query)}${this.paint("accent", "▌")}`;
372
+ }
373
+
374
+ private candidateRows(
375
+ width: number,
376
+ maxVisible: number,
377
+ candidates: readonly ModelCandidate[],
378
+ agent: FallbackAgentEntry | undefined,
379
+ ): string[] {
380
+ if (candidates.length === 0) {
381
+ const message = this.query ? `No models match "${sanitize(this.query)}"` : "No models available";
382
+ return [this.pad(this.paint("warning", message), width)];
383
+ }
384
+ const primary = primaryColumnWidth(candidates.map((candidate) => candidate.label));
385
+ // On narrow frames the provider badge would squeeze the id into `[anthropi…`; drop it and keep
386
+ // the rank, which is what the fallback order is about. `[unavailable]` always stays.
387
+ const showProvider = width >= 52;
388
+ const start = this.windowStart(this.selectedModel, candidates.length, maxVisible);
389
+ const end = Math.min(start + maxVisible, candidates.length);
390
+ const chainIndex = new Map((agent?.fallbackModels ?? []).map((id, index) => [id, index]));
391
+ const lines: string[] = [];
392
+ for (let index = start; index < end; index++) {
393
+ const candidate = candidates[index];
394
+ if (!candidate) {
395
+ continue;
396
+ }
397
+ const rank = chainIndex.get(candidate.id);
398
+ lines.push(
399
+ this.row(width, {
400
+ selected: index === this.selectedModel,
401
+ cursor: "→ ",
402
+ marker: true,
403
+ checked: rank !== undefined,
404
+ label: candidate.label,
405
+ description: candidate.unavailable || showProvider ? candidate.description : "",
406
+ descriptionColor: candidate.unavailable ? "warning" : "muted",
407
+ unavailable: candidate.unavailable === true,
408
+ trailing: rank !== undefined ? ` #${rank + 1}` : "",
409
+ primary,
410
+ }),
411
+ );
412
+ }
413
+ if (start > 0 || end < candidates.length) {
414
+ lines.push(this.scrollInfo(this.selectedModel + 1, candidates.length, width));
415
+ }
416
+ return lines;
417
+ }
418
+
419
+ private pickerHints(): string[] {
420
+ return [
421
+ this.hint(this.navLabel(), "model"),
422
+ this.hint(this.hintLabel("tui.select.confirm", "Enter"), "toggle"),
423
+ this.hint(this.hintLabel("app.models.enableAll", "Ctrl+A"), "all"),
424
+ this.hint(this.hintLabel("app.models.clearAll", "Ctrl+X"), "clear"),
425
+ this.hint(this.hintLabel("app.models.toggleProvider", "Ctrl+P"), "provider"),
426
+ this.hint(this.reorderLabel(), "order"),
427
+ this.hint(this.hintLabel("app.models.save", "Ctrl+S"), "save"),
428
+ this.hint(this.hintLabel("tui.select.cancel", "Esc"), "back"),
429
+ ];
430
+ }
431
+
432
+ /**
433
+ * The visible list: enabled models first, in chain order, then the remaining models (and any
434
+ * chain entries that are no longer available). `inherit` is offered only to subagents.
435
+ */
436
+ private visibleCandidates(agent: FallbackAgentEntry | undefined): ModelCandidate[] {
437
+ if (!agent) {
438
+ return [];
439
+ }
440
+ const query = this.query.trim();
441
+ const chainIndex = new Map(agent.fallbackModels.map((id, index) => [id, index]));
442
+ const known = new Set(this.candidates.map((candidate) => candidate.id));
443
+ const items: ModelCandidate[] = agent.isMain ? [...this.candidates] : [INHERIT_CANDIDATE, ...this.candidates];
444
+ for (const id of agent.fallbackModels) {
445
+ if (id !== INHERIT_ID && !known.has(id)) {
446
+ items.push({ id, label: id, description: "[unavailable]", search: id, unavailable: true });
447
+ }
448
+ }
449
+
450
+ if (query.length === 0) {
451
+ return items.sort((left, right) => {
452
+ const leftRank = chainIndex.get(left.id);
453
+ const rightRank = chainIndex.get(right.id);
454
+ if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
455
+ if (leftRank !== undefined) return -1;
456
+ if (rightRank !== undefined) return 1;
457
+ return 0;
458
+ });
459
+ }
460
+
461
+ const scored: { candidate: ModelCandidate; score: number; order: number }[] = [];
462
+ items.forEach((candidate, order) => {
463
+ const score = fuzzyScore(candidate.search, query);
464
+ if (score !== undefined) {
465
+ scored.push({ candidate, score, order });
466
+ }
467
+ });
468
+ scored.sort((left, right) => {
469
+ const leftRank = chainIndex.get(left.candidate.id);
470
+ const rightRank = chainIndex.get(right.candidate.id);
471
+ if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
472
+ if (leftRank !== undefined) return -1;
473
+ if (rightRank !== undefined) return 1;
474
+ return right.score - left.score || left.order - right.order;
475
+ });
476
+ return scored.map((entry) => entry.candidate);
477
+ }
478
+
479
+ /** Every candidate that can be enabled, in display order, regardless of the search. */
480
+ private allCandidates(agent: FallbackAgentEntry): ModelCandidate[] {
481
+ return agent.isMain ? [...this.candidates] : [INHERIT_CANDIDATE, ...this.candidates];
482
+ }
483
+
484
+ private handlePickerInput(data: string): void {
485
+ if (data === "\x1b" || data === "\x03" || this.matches(data, "tui.select.cancel")) {
486
+ this.leavePickerStep();
487
+ return;
488
+ }
489
+
490
+ if (data === "\x7f" || data === "\b") {
491
+ if (this.query.length > 0) {
492
+ this.query = this.query.slice(0, -1);
493
+ this.clampModelSelection();
494
+ }
495
+ this.tui?.requestRender();
496
+ return;
497
+ }
498
+
499
+ if (this.isSave(data)) {
500
+ this.save();
501
+ return;
502
+ }
503
+
504
+ if (data === "\x01" || this.matches(data, "app.models.enableAll")) {
505
+ this.enableAll();
506
+ return;
507
+ }
508
+
509
+ if (data === "\x18" || this.matches(data, "app.models.clearAll")) {
510
+ this.clearAll();
511
+ return;
512
+ }
513
+
514
+ if (data === "\x10" || this.matches(data, "app.models.toggleProvider")) {
515
+ this.toggleProvider();
516
+ return;
517
+ }
518
+
519
+ if (this.isReorderUp(data)) {
520
+ this.reorder(-1);
521
+ return;
522
+ }
523
+
524
+ if (this.isReorderDown(data)) {
525
+ this.reorder(1);
526
+ return;
527
+ }
528
+
529
+ // Wheel moves the selection like a native SelectList; printable keys stay in the search field.
530
+ const wheel = mouseWheelDirection(data);
531
+ if (wheel !== undefined) {
532
+ this.moveModel(wheel);
533
+ return;
534
+ }
535
+
536
+ // Arrow keys (and any non-printable binding) drive the list; printable keys are the search field.
537
+ if (!isPrintable(data) && (this.matches(data, "tui.select.up") || this.isArrowUp(data))) {
538
+ this.moveModel(-1);
539
+ return;
540
+ }
541
+
542
+ if (!isPrintable(data) && (this.matches(data, "tui.select.down") || this.isArrowDown(data))) {
543
+ this.moveModel(1);
544
+ return;
545
+ }
546
+
547
+ if (data === "\x1b[H") {
548
+ this.selectedModel = 0;
549
+ this.tui?.requestRender();
550
+ return;
551
+ }
552
+
553
+ if (data === "\x1b[F") {
554
+ this.selectedModel = Math.max(0, this.visibleCandidates(this.agents[this.selected]).length - 1);
555
+ this.tui?.requestRender();
556
+ return;
557
+ }
558
+
559
+ if (data === "\x1b[5~" || (!isPrintable(data) && this.matches(data, "tui.select.pageUp"))) {
560
+ this.moveModel(-this.pageStep());
561
+ return;
562
+ }
563
+
564
+ if (data === "\x1b[6~" || (!isPrintable(data) && this.matches(data, "tui.select.pageDown"))) {
565
+ this.moveModel(this.pageStep());
566
+ return;
567
+ }
568
+
569
+ if (data === "\r" || data === "\n" || this.matches(data, "tui.select.confirm")) {
570
+ this.toggleSelected();
571
+ return;
572
+ }
573
+
574
+ if (isPrintable(data)) {
575
+ this.query += data;
576
+ this.selectedModel = 0;
577
+ this.tui?.requestRender();
578
+ }
579
+ }
580
+
581
+ private isReorderUp(data: string): boolean {
582
+ return data === "\x1b[1;3A" || this.matches(data, "app.models.reorderUp");
583
+ }
584
+
585
+ private isReorderDown(data: string): boolean {
586
+ return data === "\x1b[1;3B" || this.matches(data, "app.models.reorderDown");
587
+ }
588
+
589
+ private isSave(data: string): boolean {
590
+ return data === "\x13" || this.matches(data, "app.models.save");
591
+ }
592
+
593
+ private leavePickerStep(): void {
594
+ if (this.query.length > 0) {
595
+ this.query = "";
596
+ this.selectedModel = 0;
597
+ } else {
598
+ this.mode = "agents";
599
+ this.selectedModel = 0;
600
+ this.notice = undefined;
601
+ }
602
+ this.tui?.requestRender();
603
+ }
604
+
605
+ private moveModel(delta: number): void {
606
+ const count = this.visibleCandidates(this.agents[this.selected]).length;
607
+ if (count === 0) {
608
+ return;
609
+ }
610
+ this.selectedModel = (this.selectedModel + delta + count) % count;
611
+ this.tui?.requestRender();
612
+ }
613
+
614
+ private clampModelSelection(): void {
615
+ const count = this.visibleCandidates(this.agents[this.selected]).length;
616
+ this.selectedModel = count === 0 ? 0 : clamp(this.selectedModel, 0, count - 1);
617
+ }
618
+
619
+ /** Keep the cursor on the row that was just toggled or reordered, even after it moves. */
620
+ private keepSelectionOn(id: string | undefined): void {
621
+ const candidates = this.visibleCandidates(this.agents[this.selected]);
622
+ const index = id === undefined ? -1 : candidates.findIndex((candidate) => candidate.id === id);
623
+ this.selectedModel = index >= 0 ? index : Math.min(this.selectedModel, Math.max(0, candidates.length - 1));
624
+ this.tui?.requestRender();
625
+ }
626
+
627
+ private currentCandidate(): ModelCandidate | undefined {
628
+ return this.visibleCandidates(this.agents[this.selected])[this.selectedModel];
629
+ }
630
+
631
+ private toggleSelected(): void {
632
+ const agent = this.agents[this.selected];
633
+ const candidate = this.currentCandidate();
634
+ if (!agent || !candidate) {
635
+ return;
636
+ }
637
+ const at = agent.fallbackModels.indexOf(candidate.id);
638
+ if (at >= 0) {
639
+ agent.fallbackModels.splice(at, 1);
640
+ } else if (!candidate.unavailable) {
641
+ agent.fallbackModels.push(candidate.id);
642
+ }
643
+ this.dirty = true;
644
+ this.notice = undefined;
645
+ this.keepSelectionOn(candidate.id);
646
+ }
647
+
648
+ /** Enable every candidate in the filtered list, or every candidate when the search is empty. */
649
+ private enableAll(): void {
650
+ const agent = this.agents[this.selected];
651
+ if (!agent) {
652
+ return;
653
+ }
654
+ const current = this.currentCandidate()?.id;
655
+ const targets = this.query.trim() ? this.visibleCandidates(agent) : this.allCandidates(agent);
656
+ for (const candidate of targets) {
657
+ if (!candidate.unavailable && !agent.fallbackModels.includes(candidate.id)) {
658
+ agent.fallbackModels.push(candidate.id);
659
+ }
660
+ }
661
+ this.dirty = true;
662
+ this.notice = undefined;
663
+ this.keepSelectionOn(current);
664
+ }
665
+
666
+ /** Remove every candidate in the filtered list, or the whole chain when the search is empty. */
667
+ private clearAll(): void {
668
+ const agent = this.agents[this.selected];
669
+ if (!agent) {
670
+ return;
671
+ }
672
+ const current = this.currentCandidate()?.id;
673
+ if (this.query.trim()) {
674
+ const targets = new Set(this.visibleCandidates(agent).map((candidate) => candidate.id));
675
+ agent.fallbackModels = agent.fallbackModels.filter((id) => !targets.has(id));
676
+ } else {
677
+ agent.fallbackModels = [];
678
+ }
679
+ this.dirty = true;
680
+ this.notice = undefined;
681
+ this.keepSelectionOn(current);
682
+ }
683
+
684
+ private toggleProvider(): void {
685
+ const agent = this.agents[this.selected];
686
+ const candidate = this.currentCandidate();
687
+ if (!agent || !candidate?.provider || candidate.unavailable) {
688
+ return;
689
+ }
690
+ const provider = candidate.provider;
691
+ const ids = this.candidates.filter((entry) => entry.provider === provider).map((entry) => entry.id);
692
+ const allEnabled = ids.every((id) => agent.fallbackModels.includes(id));
693
+ if (allEnabled) {
694
+ const remove = new Set(ids);
695
+ agent.fallbackModels = agent.fallbackModels.filter((id) => !remove.has(id));
696
+ } else {
697
+ for (const id of ids) {
698
+ if (!agent.fallbackModels.includes(id)) {
699
+ agent.fallbackModels.push(id);
700
+ }
701
+ }
702
+ }
703
+ this.dirty = true;
704
+ this.notice = undefined;
705
+ this.keepSelectionOn(candidate.id);
706
+ }
707
+
708
+ private reorder(delta: number): void {
709
+ const agent = this.agents[this.selected];
710
+ const candidate = this.currentCandidate();
711
+ if (!agent || !candidate) {
712
+ return;
713
+ }
714
+ const at = agent.fallbackModels.indexOf(candidate.id);
715
+ if (at < 0) {
716
+ return;
717
+ }
718
+ const to = at + delta;
719
+ if (to < 0 || to >= agent.fallbackModels.length) {
720
+ return;
721
+ }
722
+ const [moved] = agent.fallbackModels.splice(at, 1);
723
+ if (moved !== undefined) {
724
+ agent.fallbackModels.splice(to, 0, moved);
725
+ }
726
+ this.dirty = true;
727
+ this.notice = undefined;
728
+ this.keepSelectionOn(candidate.id);
729
+ }
730
+
731
+ private openPicker(): void {
732
+ if (this.agents.length === 0) {
733
+ return;
734
+ }
735
+ this.mode = "models";
736
+ this.query = "";
737
+ this.selectedModel = 0;
738
+ this.notice = undefined;
739
+ this.tui?.requestRender();
740
+ }
741
+
742
+ // --- actions -------------------------------------------------------------------------------
743
+
744
+ private save(): void {
745
+ try {
746
+ this.options.onSave(this.agents);
747
+ this.dirty = false;
748
+ this.notice = "Saved fallback configuration";
749
+ } catch (err) {
750
+ this.notice = `Save failed: ${err instanceof Error ? err.message : String(err)}`;
751
+ }
752
+ this.tui?.requestRender();
753
+ }
754
+
755
+ private moveAgent(delta: number): void {
756
+ const count = this.agents.length;
757
+ if (count === 0) {
758
+ return;
759
+ }
760
+ this.select((this.selected + delta + count) % count);
761
+ }
762
+ }