@restranger/repi-model-fallback 0.0.0-stage → 0.0.1-sha.9fd9ba8

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 CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @restranger/repi-model-fallback
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Automatic model fallback and retry for the primary Pi agent. When a model request fails (rate limit, quota exceeded, 403/5xx errors, network failure), this extension automatically switches the active session to the next configured fallback model and transparently resumes execution.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pi install npm:@restranger/repi-model-fallback
9
+ # or from this monorepo
10
+ pi --extension ./packages/model-fallback/src/index.ts
11
+ ```
12
+
13
+ ## How it works
14
+
15
+ 1. Pi executes a turn. If the provider fails (e.g. 403 Forbidden, 429 Rate Limit, 500 Server Error), the turn ends with an error.
16
+ 2. Before the session settles, `@restranger/repi-model-fallback` intercepts `agent_before_settle`:
17
+ - Selects the next viable candidate from your `fallbacks` list.
18
+ - Activates the fallback model via `pi.setModel(nextModel)`.
19
+ - Omits the failed assistant message via `context_edit` so the context is clean.
20
+ - Shows a notification in the UI (`Model "..." failed: ... Falling back to "..."`).
21
+ - Returns `{ continue: true }` to immediately prompt the new model.
22
+ 3. The fallback model produces the final answer without requiring user intervention.
23
+
24
+ ## Configuration
25
+
26
+ Configurations are loaded with project priority:
27
+ 1. `$XDG_CONFIG_HOME/repi/model-fallback.json` (or `~/.config/repi/model-fallback.json`)
28
+ 2. `<project>/.repi/model-fallback.json` (wins over user config)
29
+
30
+ ```json
31
+ {
32
+ "version": 1,
33
+ "enabled": true,
34
+ "fallbacks": [
35
+ "gemini-3.8-flash",
36
+ "anthropic/claude-3-5-sonnet",
37
+ "openai/gpt-4o"
38
+ ],
39
+ "maxRetriesPerTurn": 3,
40
+ "notify": true
41
+ }
42
+ ```
43
+
44
+ ### Options
45
+
46
+ | Field | Description | Default |
47
+ |---|---|---|
48
+ | `enabled` | Whether automatic model fallback is active. | `true` |
49
+ | `fallbacks` | Ordered list of models to try if the current model fails. Exact `provider/id` or fuzzy model name. | `[]` |
50
+ | `maxRetriesPerTurn` | Maximum number of consecutive fallback attempts per user prompt before stopping. | `3` |
51
+ | `notify` | Whether to show an informative UI notification on fallback. | `true` |
52
+
53
+ Accepted aliases for compatibility: `fallback_models`, `fallbackModels`, `max_retries_per_turn`.
54
+
55
+ ## Slash command & TUI Menu
56
+
57
+ - `/fallback` — Open the interactive TUI menu (styled after `/subagents fleet`) to view and manage fallbacks for all agents:
58
+ - Lists the `[main]` primary agent and all declared subagents (`Explore`, `Plan`, `general-purpose`, etc.).
59
+ - Shows primary model and configured fallback chains for each agent.
60
+ - Press `a` or `Enter` to open the model picker and add any available model from the registry.
61
+ - Press `d` to remove a fallback model.
62
+ - Press `s` to save changes to `.repi/model-fallback.json` and `.repi/subagents.json`.
63
+ - Press `q` or `Esc` to close.
64
+ - `/fallback status` — Print status overview in text mode.
65
+ - `/fallback list` — List configured fallbacks and all available models in the registry.
66
+ - `/fallback on` — Enable fallback for the current session.
67
+ - `/fallback off` — Temporarily disable fallback.
68
+ - `/fallback reload` — Reload configuration files from disk.
69
+
70
+ Typing `/fallback ` and pressing `Tab` completes these subcommands; nothing is offered after a
71
+ subcommand because the rest of the argument is not a fixed slot.
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
- "name": "@restranger/repi-model-fallback",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@restranger/repi-model-fallback",
3
+ "version": "0.0.1-sha.9fd9ba8",
4
+ "description": "Automatic model fallback and retry for pi-coding-agent",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "!src/**/__tests__"
15
+ ],
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-coding-agent",
19
+ "model-fallback",
20
+ "retry",
21
+ "tui"
22
+ ],
23
+ "author": "ReStranger <restranger@disroot.org>",
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/ReStranger/repi-mono.git",
28
+ "directory": "packages/model-fallback"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/ReStranger/repi-mono/issues"
32
+ },
33
+ "homepage": "https://github.com/ReStranger/repi-mono#readme",
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "pi": {
38
+ "extensions": [
39
+ "./src/index.ts"
40
+ ]
41
+ },
42
+ "dependencies": {
43
+ "@restranger/repi-lib": "0.0.1-sha.9fd9ba8"
44
+ },
45
+ "peerDependencies": {
46
+ "@earendil-works/pi-coding-agent": ">=0.79.0"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "@earendil-works/pi-coding-agent": {
50
+ "optional": true
51
+ }
52
+ },
53
+ "devDependencies": {
54
+ "@restranger/repi-test-utils": "0.0.1-sha.9fd9ba8"
55
+ }
56
+ }
package/src/config.ts ADDED
@@ -0,0 +1,216 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { type PluginConfigLayer, type PluginDiagnostic, resolveConfigLayers } from "@restranger/repi-lib";
4
+ import type { FallbackConfig, LoadedFallbackConfig, ModelFallbackConfigContext } from "./types.js";
5
+
6
+ const CONFIG_NAME = "model-fallback.json";
7
+
8
+ /** Layers are resolved by `@restranger/repi-lib` so every plugin applies the same trust rule. */
9
+ export function resolveConfigPaths(context: ModelFallbackConfigContext): PluginConfigLayer[] {
10
+ return resolveConfigLayers({
11
+ cwd: context.cwd,
12
+ ...(context.homeDir !== undefined ? { homeDir: context.homeDir } : {}),
13
+ ...(context.env !== undefined ? { env: context.env } : {}),
14
+ ...(context.workspaceTrusted !== undefined ? { workspaceTrusted: context.workspaceTrusted } : {}),
15
+ filename: CONFIG_NAME,
16
+ });
17
+ }
18
+
19
+ export function loadFallbackConfig(context: ModelFallbackConfigContext): LoadedFallbackConfig {
20
+ const diagnostics: PluginDiagnostic[] = [];
21
+ const configFiles: string[] = [];
22
+ let merged: FallbackConfig = {
23
+ enabled: true,
24
+ fallbacks: [],
25
+ maxRetriesPerTurn: 3,
26
+ notify: true,
27
+ };
28
+
29
+ for (const layer of resolveConfigPaths(context)) {
30
+ if (!safeExists(layer.path)) {
31
+ continue;
32
+ }
33
+ configFiles.push(layer.path);
34
+ const parsed = readConfigFile(layer, diagnostics);
35
+ if (!parsed) {
36
+ continue;
37
+ }
38
+
39
+ merged = mergeLayer(merged, parsed);
40
+ }
41
+
42
+ return {
43
+ config: merged,
44
+ configFiles,
45
+ diagnostics,
46
+ };
47
+ }
48
+
49
+ function readConfigFile(
50
+ layer: PluginConfigLayer,
51
+ diagnostics: PluginDiagnostic[],
52
+ ): Record<string, unknown> | undefined {
53
+ let raw: string;
54
+ try {
55
+ raw = readFileSync(layer.path, "utf8");
56
+ } catch (err) {
57
+ diagnostics.push({
58
+ level: "error",
59
+ path: layer.path,
60
+ message: `Cannot read ${layer.source} config: ${errorMessage(err)}`,
61
+ });
62
+ return undefined;
63
+ }
64
+
65
+ try {
66
+ const parsed = JSON.parse(raw.replace(/^\uFEFF/, "")) as unknown;
67
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
68
+ diagnostics.push({
69
+ level: "error",
70
+ path: layer.path,
71
+ message: `Invalid ${layer.source} config: expected a JSON object.`,
72
+ });
73
+ return undefined;
74
+ }
75
+ return parsed as Record<string, unknown>;
76
+ } catch (err) {
77
+ diagnostics.push({
78
+ level: "error",
79
+ path: layer.path,
80
+ message: `JSON syntax error in ${layer.source} config: ${errorMessage(err)}`,
81
+ });
82
+ return undefined;
83
+ }
84
+ }
85
+
86
+ function mergeLayer(base: FallbackConfig, patch: Record<string, unknown>): FallbackConfig {
87
+ let enabled = base.enabled;
88
+ if (typeof patch.enabled === "boolean") {
89
+ enabled = patch.enabled;
90
+ }
91
+
92
+ let notify = base.notify;
93
+ if (typeof patch.notify === "boolean") {
94
+ notify = patch.notify;
95
+ }
96
+
97
+ let maxRetriesPerTurn = base.maxRetriesPerTurn;
98
+ const maxRetriesRaw = patch.maxRetriesPerTurn ?? patch.max_retries_per_turn;
99
+ if (typeof maxRetriesRaw === "number" && Number.isInteger(maxRetriesRaw) && maxRetriesRaw >= 1) {
100
+ maxRetriesPerTurn = maxRetriesRaw;
101
+ }
102
+
103
+ let fallbacks = base.fallbacks;
104
+ const rawFallbacks = patch.fallbacks ?? patch.fallback_models ?? patch.fallbackModels;
105
+ if (Array.isArray(rawFallbacks)) {
106
+ const parsed = rawFallbacks
107
+ .filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0)
108
+ .map((entry) => entry.trim());
109
+ fallbacks = parsed;
110
+ } else if (typeof rawFallbacks === "string") {
111
+ const parsed = rawFallbacks
112
+ .split(",")
113
+ .map((entry) => entry.trim())
114
+ .filter(Boolean);
115
+ fallbacks = parsed;
116
+ }
117
+
118
+ return {
119
+ ...base,
120
+ ...(enabled !== undefined ? { enabled } : {}),
121
+ ...(notify !== undefined ? { notify } : {}),
122
+ ...(maxRetriesPerTurn !== undefined ? { maxRetriesPerTurn } : {}),
123
+ ...(fallbacks ? { fallbacks } : {}),
124
+ };
125
+ }
126
+
127
+ function safeExists(path: string): boolean {
128
+ try {
129
+ return existsSync(path);
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
134
+
135
+ function errorMessage(error: unknown): string {
136
+ return error instanceof Error ? error.message : String(error);
137
+ }
138
+
139
+ export interface SaveConfigOptions {
140
+ /** `false` refuses to write into the project; the caller reports the error to the user. */
141
+ readonly workspaceTrusted?: boolean;
142
+ }
143
+
144
+ /**
145
+ * Persist the main model's fallback list.
146
+ *
147
+ * The write is atomic (temp file + rename) and never silently discards an unreadable existing
148
+ * file: a corrupt config must surface as an error, not as settings that vanish on the next save.
149
+ * `enabled` is preserved so saving from the menu does not undo `/fallback off`.
150
+ */
151
+ export function saveMainFallbackConfig(
152
+ cwd: string,
153
+ fallbacks: readonly string[],
154
+ options: SaveConfigOptions = {},
155
+ ): string {
156
+ assertProjectWritable(options);
157
+ const filePath = join(resolve(cwd), ".repi", CONFIG_NAME);
158
+ const existing = readExistingObject(filePath);
159
+ const updated = {
160
+ ...existing,
161
+ version: 1,
162
+ enabled: typeof existing.enabled === "boolean" ? existing.enabled : true,
163
+ fallbacks: [...fallbacks],
164
+ };
165
+ writeJsonAtomic(filePath, updated);
166
+ return filePath;
167
+ }
168
+
169
+ function assertProjectWritable(options: SaveConfigOptions): void {
170
+ if (options.workspaceTrusted === false) {
171
+ throw new Error("Refusing to write project fallback config: the workspace is not trusted.");
172
+ }
173
+ }
174
+
175
+ function readExistingObject(filePath: string): Record<string, unknown> {
176
+ let raw: string;
177
+ try {
178
+ raw = readFileSync(filePath, "utf8");
179
+ } catch (err) {
180
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
181
+ return {};
182
+ }
183
+ throw new Error(`Cannot read ${filePath}: ${errorMessage(err)}`);
184
+ }
185
+
186
+ let parsed: unknown;
187
+ try {
188
+ parsed = JSON.parse(raw.replace(/^\uFEFF/, ""));
189
+ } catch (err) {
190
+ throw new Error(`Cannot parse ${filePath}: ${errorMessage(err)}. Fix or delete the file, then save again.`);
191
+ }
192
+ if (!isRecord(parsed)) {
193
+ throw new Error(`Cannot use ${filePath}: expected a JSON object.`);
194
+ }
195
+ return parsed;
196
+ }
197
+
198
+ function writeJsonAtomic(filePath: string, value: unknown): void {
199
+ mkdirSync(dirname(filePath), { recursive: true });
200
+ const temp = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
201
+ try {
202
+ writeFileSync(temp, `${JSON.stringify(value, null, "\t")}\n`, { encoding: "utf8", mode: 0o600 });
203
+ renameSync(temp, filePath);
204
+ } catch (err) {
205
+ try {
206
+ rmSync(temp, { force: true });
207
+ } catch {
208
+ // Best effort: the temp file may never have been created.
209
+ }
210
+ throw err;
211
+ }
212
+ }
213
+
214
+ function isRecord(value: unknown): value is Record<string, unknown> {
215
+ return typeof value === "object" && value !== null && !Array.isArray(value);
216
+ }
package/src/format.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { alignRight, boldText, displayWidth, fitWidth, sanitize, truncate, wrapDisplay } from "@restranger/repi-lib";
2
+
3
+ /**
4
+ * Display primitives for the fallback menu, re-exported from `@restranger/repi-lib`.
5
+ *
6
+ * The menu used to carry its own width/truncation implementation, which disagreed with the
7
+ * subagent widget about emoji and CJK width (and with it about SGR carry-over across wraps).
8
+ * Keeping this module as a re-export preserves the menu's import surface.
9
+ */
10
+ export { alignRight, boldText, displayWidth, fitWidth, sanitize, truncate, wrapDisplay };
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./types.js";
2
+ export * from "./config.js";
3
+ export * from "./resolver.js";
4
+ export * from "./plugin.js";
5
+ export { default } from "./plugin.js";
package/src/menu-ui.ts ADDED
@@ -0,0 +1,584 @@
1
+ import { ListOverlay, type PiModel, type SubagentSummary, mouseWheelDirection } from "@restranger/repi-lib";
2
+ import { alignRight, boldText, fitWidth, sanitize, truncate, wrapDisplay } from "./format.js";
3
+
4
+ export interface FallbackAgentEntry {
5
+ readonly id: string;
6
+ readonly name: string;
7
+ readonly isMain: boolean;
8
+ readonly primaryModel: string;
9
+ fallbackModels: string[];
10
+ }
11
+
12
+ export interface FallbackMenuViewOptions {
13
+ readonly mainModel?: PiModel;
14
+ readonly mainFallbacks: readonly string[];
15
+ readonly subagents: readonly SubagentSummary[];
16
+ readonly availableModels: readonly PiModel[];
17
+ readonly onSave: (entries: readonly FallbackAgentEntry[]) => void;
18
+ readonly onDone?: () => void;
19
+ readonly maxRows?: number;
20
+ }
21
+
22
+ const MIN_WIDTH = 36;
23
+ const MIN_ROWS = 8;
24
+ const SEARCH_CHAR_PATTERN = /^[a-zA-Z0-9\-_./:]+$/;
25
+
26
+ export class FallbackMenuView extends ListOverlay {
27
+ private rosterScroll = 0;
28
+ private selectedPickerIndex = 0;
29
+ private pickerScroll = 0;
30
+ private lastOutputBodyHeight = 0;
31
+ private mode: "roster" | "pick_model" = "roster";
32
+ private searchQuery = "";
33
+ private notice?: string;
34
+
35
+ private readonly agents: FallbackAgentEntry[];
36
+ private readonly availableModelNames: readonly string[];
37
+
38
+ constructor(private readonly options: FallbackMenuViewOptions) {
39
+ super({ maxRows: options.maxRows });
40
+ const mainModelName = options.mainModel
41
+ ? `${options.mainModel.provider}/${options.mainModel.id}`
42
+ : "default parent model";
43
+
44
+ const mainEntry: FallbackAgentEntry = {
45
+ id: "main",
46
+ name: "[main] (Main Agent)",
47
+ isMain: true,
48
+ primaryModel: mainModelName,
49
+ fallbackModels: [...options.mainFallbacks],
50
+ };
51
+
52
+ const subagentEntries: FallbackAgentEntry[] = options.subagents.map((sub) => ({
53
+ id: sub.name,
54
+ name: sub.name,
55
+ isMain: false,
56
+ primaryModel: sub.model ?? "inherit",
57
+ fallbackModels: [...(sub.fallbackModels ?? [])],
58
+ }));
59
+
60
+ this.agents = [mainEntry, ...subagentEntries];
61
+
62
+ const modelNames = options.availableModels.map((m) => `${m.provider}/${m.id}`);
63
+ this.availableModelNames = [...new Set(modelNames)].sort();
64
+ }
65
+
66
+ /** Number of rows the base class moves through with ↑/↓. */
67
+ protected itemCount(): number {
68
+ return this.agents.length;
69
+ }
70
+
71
+ /** Selecting another agent clears the transient notice, as before. */
72
+ protected onSelectionChanged(): void {
73
+ this.notice = undefined;
74
+ }
75
+
76
+ protected onClose(): void {
77
+ this.options.onDone?.();
78
+ }
79
+
80
+ refresh(): void {
81
+ super.refresh();
82
+ this.clampPickerSelection();
83
+ }
84
+
85
+ handleInput(data: string): void {
86
+ if (this.mode === "pick_model") {
87
+ this.handlePickerInput(data);
88
+ return;
89
+ }
90
+
91
+ if (data === "q" || this.matches(data, "tui.select.cancel")) {
92
+ this.close();
93
+ return;
94
+ }
95
+
96
+ if (this.matches(data, "tui.select.up") || data === "\x1b[A" || data === "\x1bOA" || data === "k") {
97
+ this.move(-1);
98
+ return;
99
+ }
100
+
101
+ if (this.matches(data, "tui.select.down") || data === "\x1b[B" || data === "\x1bOB" || data === "j") {
102
+ this.move(1);
103
+ return;
104
+ }
105
+
106
+ if (data === "\x1b[H" || data === "g") {
107
+ this.select(0);
108
+ return;
109
+ }
110
+
111
+ if (data === "\x1b[F" || data === "G") {
112
+ this.select(this.agents.length - 1);
113
+ return;
114
+ }
115
+
116
+ if (data === "K" || this.isScrollUp(data)) {
117
+ this.scrollDetail(-1);
118
+ return;
119
+ }
120
+
121
+ if (data === "J" || this.isScrollDown(data)) {
122
+ this.scrollDetail(1);
123
+ return;
124
+ }
125
+
126
+ if (data === "\x1b[5~" || this.matches(data, "tui.select.pageUp")) {
127
+ this.scrollDetail(-Math.max(1, this.lastOutputBodyHeight || 5));
128
+ return;
129
+ }
130
+
131
+ if (data === "\x1b[6~" || this.matches(data, "tui.select.pageDown")) {
132
+ this.scrollDetail(Math.max(1, this.lastOutputBodyHeight || 5));
133
+ return;
134
+ }
135
+
136
+ if (data === "a" || data === "A" || data === "\r" || data === "\n" || this.matches(data, "tui.select.confirm")) {
137
+ this.mode = "pick_model";
138
+ this.searchQuery = "";
139
+ this.selectedPickerIndex = 0;
140
+ this.pickerScroll = 0;
141
+ this.notice = undefined;
142
+ this.tui?.requestRender();
143
+ return;
144
+ }
145
+
146
+ if (data === "d" || data === "D" || data === "\x7f") {
147
+ this.removeSelectedFallback();
148
+ return;
149
+ }
150
+
151
+ if (data === "s" || data === "S") {
152
+ this.save();
153
+ return;
154
+ }
155
+ }
156
+
157
+ private handlePickerInput(data: string): void {
158
+ if (data === "\x1b" || (!SEARCH_CHAR_PATTERN.test(data) && this.matches(data, "tui.select.cancel"))) {
159
+ if (this.searchQuery.length > 0) {
160
+ this.searchQuery = "";
161
+ this.clampPickerSelection();
162
+ } else {
163
+ this.mode = "roster";
164
+ this.pickerScroll = 0;
165
+ this.notice = undefined;
166
+ }
167
+ this.tui?.requestRender();
168
+ return;
169
+ }
170
+
171
+ if (data === "\x7f" || data === "\b") {
172
+ if (this.searchQuery.length > 0) {
173
+ this.searchQuery = this.searchQuery.slice(0, -1);
174
+ this.clampPickerSelection();
175
+ }
176
+ this.tui?.requestRender();
177
+ return;
178
+ }
179
+
180
+ if (this.isScrollUp(data)) {
181
+ this.movePicker(-1, false);
182
+ return;
183
+ }
184
+
185
+ if (this.isScrollDown(data)) {
186
+ this.movePicker(1, false);
187
+ return;
188
+ }
189
+
190
+ if (
191
+ data === "\x1b[A" ||
192
+ data === "\x1bOA" ||
193
+ (this.searchQuery.length === 0 && (data === "k" || data === "K")) ||
194
+ (!SEARCH_CHAR_PATTERN.test(data) && this.matches(data, "tui.select.up"))
195
+ ) {
196
+ this.movePicker(-1, true);
197
+ return;
198
+ }
199
+
200
+ if (
201
+ data === "\x1b[B" ||
202
+ data === "\x1bOB" ||
203
+ (this.searchQuery.length === 0 && (data === "j" || data === "J")) ||
204
+ (!SEARCH_CHAR_PATTERN.test(data) && this.matches(data, "tui.select.down"))
205
+ ) {
206
+ this.movePicker(1, true);
207
+ return;
208
+ }
209
+
210
+ if (data === "\x1b[5~" || (!SEARCH_CHAR_PATTERN.test(data) && this.matches(data, "tui.select.pageUp"))) {
211
+ const step = Math.max(1, (this.lastOutputBodyHeight || 5) - 1);
212
+ this.movePicker(-step, false);
213
+ return;
214
+ }
215
+
216
+ if (data === "\x1b[6~" || (!SEARCH_CHAR_PATTERN.test(data) && this.matches(data, "tui.select.pageDown"))) {
217
+ const step = Math.max(1, (this.lastOutputBodyHeight || 5) - 1);
218
+ this.movePicker(step, false);
219
+ return;
220
+ }
221
+
222
+ if (data === "\x1b[H" || (this.searchQuery.length === 0 && data === "g")) {
223
+ this.selectPicker(0);
224
+ return;
225
+ }
226
+
227
+ if (data === "\x1b[F" || (this.searchQuery.length === 0 && data === "G")) {
228
+ const count = this.pickerCandidates().length;
229
+ this.selectPicker(Math.max(0, count - 1));
230
+ return;
231
+ }
232
+
233
+ if (
234
+ data === "\r" ||
235
+ data === "\n" ||
236
+ (!SEARCH_CHAR_PATTERN.test(data) && this.matches(data, "tui.select.confirm"))
237
+ ) {
238
+ const candidates = this.pickerCandidates();
239
+ const picked = candidates[this.selectedPickerIndex];
240
+ if (picked) {
241
+ const current = this.agents[this.selected];
242
+ if (current) {
243
+ if (!current.fallbackModels.includes(picked)) {
244
+ current.fallbackModels.push(picked);
245
+ this.notice = `Added "${picked}" to ${current.isMain ? "main agent" : current.name}`;
246
+ } else {
247
+ this.notice = `Model "${picked}" is already in fallback chain`;
248
+ }
249
+ }
250
+ this.mode = "roster";
251
+ this.pickerScroll = 0;
252
+ this.searchQuery = "";
253
+ }
254
+ this.tui?.requestRender();
255
+ return;
256
+ }
257
+
258
+ if (SEARCH_CHAR_PATTERN.test(data)) {
259
+ this.searchQuery += data;
260
+ this.clampPickerSelection();
261
+ this.tui?.requestRender();
262
+ return;
263
+ }
264
+ }
265
+
266
+ private pickerCandidates(): string[] {
267
+ const current = this.agents[this.selected];
268
+ const candidates = [...this.availableModelNames];
269
+ if (current && !current.isMain) {
270
+ candidates.unshift("inherit");
271
+ }
272
+ if (!this.searchQuery) {
273
+ return candidates;
274
+ }
275
+ const query = this.searchQuery.toLowerCase();
276
+ return candidates.filter((name) => name.toLowerCase().includes(query));
277
+ }
278
+
279
+ private clampPickerSelection(): void {
280
+ const count = this.pickerCandidates().length;
281
+ if (count <= 0) {
282
+ this.selectedPickerIndex = 0;
283
+ } else {
284
+ this.selectedPickerIndex = Math.max(0, Math.min(this.selectedPickerIndex, count - 1));
285
+ }
286
+ this.ensurePickerVisible();
287
+ }
288
+
289
+ private movePicker(delta: number, wrap: boolean): void {
290
+ const candidates = this.pickerCandidates();
291
+ if (candidates.length === 0) {
292
+ return;
293
+ }
294
+ if (wrap) {
295
+ this.selectedPickerIndex = (this.selectedPickerIndex + delta + candidates.length) % candidates.length;
296
+ } else {
297
+ this.selectedPickerIndex = Math.max(0, Math.min(this.selectedPickerIndex + delta, candidates.length - 1));
298
+ }
299
+ this.ensurePickerVisible();
300
+ this.tui?.requestRender();
301
+ }
302
+
303
+ private selectPicker(index: number): void {
304
+ const candidates = this.pickerCandidates();
305
+ if (candidates.length === 0) {
306
+ return;
307
+ }
308
+ this.selectedPickerIndex = Math.max(0, Math.min(index, candidates.length - 1));
309
+ this.ensurePickerVisible();
310
+ this.tui?.requestRender();
311
+ }
312
+
313
+ private ensurePickerVisible(outputBodyHeight?: number): void {
314
+ const height = outputBodyHeight ?? this.lastOutputBodyHeight;
315
+ if (height <= 0) {
316
+ return;
317
+ }
318
+ const count = this.pickerCandidates().length;
319
+ const maxScroll = Math.max(0, count - height);
320
+ if (this.selectedPickerIndex >= this.pickerScroll + height) {
321
+ this.pickerScroll = this.selectedPickerIndex - height + 1;
322
+ }
323
+ if (this.selectedPickerIndex < this.pickerScroll) {
324
+ this.pickerScroll = this.selectedPickerIndex;
325
+ }
326
+ this.pickerScroll = Math.max(0, Math.min(this.pickerScroll, maxScroll));
327
+ }
328
+
329
+ private removeSelectedFallback(): void {
330
+ const current = this.agents[this.selected];
331
+ if (!current || current.fallbackModels.length === 0) {
332
+ return;
333
+ }
334
+ const removed = current.fallbackModels.pop();
335
+ this.notice = removed ? `Removed "${removed}"` : undefined;
336
+ this.tui?.requestRender();
337
+ }
338
+
339
+ private save(): void {
340
+ try {
341
+ this.options.onSave(this.agents);
342
+ this.notice = "Saved fallback configuration!";
343
+ } catch (err) {
344
+ this.notice = `Save failed: ${err instanceof Error ? err.message : String(err)}`;
345
+ }
346
+ this.tui?.requestRender();
347
+ }
348
+
349
+ invalidate(): void {
350
+ super.invalidate();
351
+ this.clampPickerSelection();
352
+ }
353
+
354
+ render(width: number): string[] {
355
+ const terminalWidth = Math.max(1, Math.floor(width));
356
+ if (terminalWidth < MIN_WIDTH) {
357
+ return [truncate("Model fallback manager needs at least 36 columns. Esc closes.", terminalWidth)];
358
+ }
359
+
360
+ const rows = this.rowsBudget();
361
+ if (rows < MIN_ROWS) {
362
+ return [truncate(`Model fallback manager needs at least ${MIN_ROWS} terminal rows. Esc closes.`, terminalWidth)];
363
+ }
364
+
365
+ const bodyHeight = this.bodyHeightFor(rows);
366
+ const innerWidth = terminalWidth - 2;
367
+ const rosterWidth = Math.max(22, Math.min(46, Math.floor((terminalWidth - 3) * 0.38)));
368
+ const detailWidth = Math.max(1, terminalWidth - rosterWidth - 3);
369
+
370
+ const selected = this.agents[this.selected];
371
+ const detail = this.detailSections(selected, detailWidth, bodyHeight);
372
+ const header = detail.header.slice(0, Math.max(0, bodyHeight - 1));
373
+ const outputBodyHeight = Math.max(0, bodyHeight - header.length);
374
+ this.lastOutputBodyHeight = outputBodyHeight;
375
+
376
+ const wrappedPerItem = detail.body.map((line) => wrapDisplay(line, Math.max(1, detailWidth)));
377
+ const wrapped = wrappedPerItem.flat();
378
+
379
+ let targetLine: number | undefined;
380
+ let targetEndLine: number | undefined;
381
+ if (this.mode === "pick_model") {
382
+ let currentLine = 0;
383
+ for (let i = 0; i < detail.body.length; i++) {
384
+ const count = wrappedPerItem[i]?.length ?? 1;
385
+ if (i === this.selectedPickerIndex) {
386
+ targetLine = currentLine;
387
+ targetEndLine = currentLine + count - 1;
388
+ break;
389
+ }
390
+ currentLine += count;
391
+ }
392
+ }
393
+
394
+ const visible = [...header, ...this.windowBody(wrapped, outputBodyHeight, targetLine, targetEndLine)];
395
+
396
+ const frame: string[] = [
397
+ this.border(`╭${"─".repeat(innerWidth)}╮`),
398
+ `${this.border("│")}${alignRight(this.title(), this.titleRight(selected), innerWidth)}${this.border("│")}`,
399
+ this.border(`├${"─".repeat(rosterWidth)}┬${"─".repeat(detailWidth)}┤`),
400
+ ];
401
+
402
+ const roster = this.rosterLines(this.agents, rosterWidth, bodyHeight);
403
+ for (let index = 0; index < bodyHeight; index++) {
404
+ frame.push(
405
+ `${this.border("│")}${fitWidth(roster[index] ?? "", rosterWidth)}${this.border("│")}${fitWidth(visible[index] ?? "", detailWidth)}${this.border("│")}`,
406
+ );
407
+ }
408
+
409
+ frame.push(
410
+ this.border(`├${"─".repeat(rosterWidth)}┴${"─".repeat(detailWidth)}┤`),
411
+ `${this.border("│")}${fitWidth(this.footer(), innerWidth)}${this.border("│")}`,
412
+ this.border(`╰${"─".repeat(innerWidth)}╯`),
413
+ );
414
+
415
+ return frame.map((line) => truncate(line, terminalWidth));
416
+ }
417
+
418
+ private title(): string {
419
+ return ` ${boldText(this.theme, "Model fallback manager")} ${this.paint("dim", "· live controls")}`;
420
+ }
421
+
422
+ private titleRight(entry: FallbackAgentEntry | undefined): string {
423
+ if (!entry) {
424
+ return this.paint("dim", "no agents ");
425
+ }
426
+ const glyph = entry.isMain ? this.paint("accent", "★") : this.paint("dim", "●");
427
+ return `${glyph} ${this.paint("dim", entry.name)} · active `;
428
+ }
429
+
430
+ private rosterLines(entries: readonly FallbackAgentEntry[], width: number, bodyHeight: number): string[] {
431
+ if (entries.length === 0) {
432
+ return [this.paint("dim", "No configured agents")];
433
+ }
434
+ const maxScroll = Math.max(0, entries.length - bodyHeight);
435
+ if (this.selected < this.rosterScroll) {
436
+ this.rosterScroll = this.selected;
437
+ } else if (this.selected >= this.rosterScroll + bodyHeight) {
438
+ this.rosterScroll = this.selected - bodyHeight + 1;
439
+ }
440
+ this.rosterScroll = Math.max(0, Math.min(this.rosterScroll, maxScroll));
441
+ const start = this.rosterScroll;
442
+ const lines: string[] = [];
443
+ for (let offset = 0; offset < bodyHeight; offset++) {
444
+ const index = start + offset;
445
+ const entry = entries[index];
446
+ if (!entry) {
447
+ lines.push("");
448
+ continue;
449
+ }
450
+ const isSelected = index === this.selected;
451
+ const marker = isSelected ? this.paint("accent", "›") : " ";
452
+ const glyph = entry.isMain ? this.paint("accent", "★") : this.paint("dim", "●");
453
+ const name = isSelected ? boldText(this.theme, sanitize(entry.name)) : sanitize(entry.name);
454
+ const count = entry.fallbackModels.length;
455
+ const countLabel = count > 0 ? `${count} model${count === 1 ? "" : "s"}` : "none";
456
+ const left = `${marker} ${glyph} ${name}`;
457
+ lines.push(alignRight(left, this.paint("dim", `· ${countLabel}`), width));
458
+ }
459
+ return lines;
460
+ }
461
+
462
+ private detailSections(
463
+ entry: FallbackAgentEntry | undefined,
464
+ width: number,
465
+ _height: number,
466
+ ): { header: string[]; body: string[] } {
467
+ if (this.mode === "pick_model") {
468
+ return this.pickerSections(width);
469
+ }
470
+
471
+ if (!entry) {
472
+ return {
473
+ header: [],
474
+ body: ["No agent selected."],
475
+ };
476
+ }
477
+
478
+ const glyph = entry.isMain ? this.paint("accent", "★") : this.paint("dim", "●");
479
+ const header = [
480
+ alignRight(` ${glyph} ${boldText(this.theme, entry.name)}`, this.paint("dim", "active"), width),
481
+ ` ${this.paint("dim", `${entry.isMain ? "primary session" : "subagent"} · ${sanitize(entry.primaryModel)}`)}`,
482
+ ` ${this.paint("muted", `${entry.fallbackModels.length} fallback${entry.fallbackModels.length === 1 ? "" : "s"} configured`)}`,
483
+ `${this.paint("accent", "Fallback Chain")} ${this.paint("dim", "· priority order")}`,
484
+ ].map((line) => truncate(line, width));
485
+
486
+ const body: string[] = [];
487
+ if (this.notice) {
488
+ body.push(this.paint("warning", ` Notice: ${this.notice}`), "");
489
+ }
490
+
491
+ if (entry.fallbackModels.length === 0) {
492
+ body.push(this.paint("dim", " No fallback models configured."));
493
+ body.push(this.paint("dim", " Press [a] or [Enter] to add a fallback model."));
494
+ } else {
495
+ entry.fallbackModels.forEach((model, index) => {
496
+ const num = this.paint("accent", `${index + 1}.`);
497
+ body.push(` ${num} ${model}`);
498
+ });
499
+ }
500
+
501
+ body.push("");
502
+ body.push(this.paint("dim", " Controls:"));
503
+ body.push(` ${this.paint("accent", "[a/Enter]")} Add fallback model to chain`);
504
+ body.push(` ${this.paint("accent", "[d]")} Remove last fallback model`);
505
+ body.push(` ${this.paint("accent", "[s]")} Save changes to configuration files`);
506
+
507
+ return { header, body };
508
+ }
509
+
510
+ private pickerSections(width: number): { header: string[]; body: string[] } {
511
+ const candidates = this.pickerCandidates();
512
+ const matchLabel = `${candidates.length} match${candidates.length === 1 ? "" : "es"}`;
513
+ const header = [
514
+ alignRight(
515
+ ` ${this.paint("accent", "Select Model to Add to Fallback Chain")}`,
516
+ this.paint("dim", "picker"),
517
+ width,
518
+ ),
519
+ ` ${this.paint("dim", "Use ↑/↓ to navigate, Enter to select, Esc to return")}`,
520
+ ` ${this.paint("accent", "Search:")} [${this.searchQuery}] ${this.paint("dim", `(${matchLabel})`)}`,
521
+ ].map((line) => truncate(line, width));
522
+
523
+ const body: string[] = [];
524
+ if (candidates.length === 0) {
525
+ if (this.searchQuery) {
526
+ body.push(this.paint("dim", ` No models match "${this.searchQuery}"`));
527
+ } else {
528
+ body.push(this.paint("dim", " No available models to select"));
529
+ }
530
+ } else {
531
+ for (let i = 0; i < candidates.length; i++) {
532
+ const candidate = candidates[i] ?? "";
533
+ const isSelected = i === this.selectedPickerIndex;
534
+ const marker = isSelected ? this.paint("accent", " › ") : " ";
535
+ const text = isSelected ? boldText(this.theme, candidate) : candidate;
536
+ body.push(`${marker}${text}`);
537
+ }
538
+ }
539
+
540
+ return { header, body };
541
+ }
542
+
543
+ private footer(): string {
544
+ if (this.mode === "pick_model") {
545
+ const candidates = this.pickerCandidates();
546
+ const position = `${candidates.length === 0 ? 0 : this.selectedPickerIndex + 1}/${candidates.length}`;
547
+ return ` ${this.paint("dim", `↑/↓ move · enter select · esc cancel · ${position}`)}`;
548
+ }
549
+ const up = this.keyLabel("tui.select.up", "↑");
550
+ const down = this.keyLabel("tui.select.down", "↓");
551
+ const close = this.keyLabel("tui.select.cancel", "Esc");
552
+ const position = `${this.agents.length === 0 ? 0 : this.selected + 1}/${this.agents.length}`;
553
+ return ` ${this.paint("dim", `${up}/${down} agent · a add · d remove · s save · K/J scroll · ${close} close · ${position}`)} `;
554
+ }
555
+
556
+ protected windowBody(body: readonly string[], height: number, targetLine?: number, targetEndLine?: number): string[] {
557
+ if (this.mode !== "pick_model") {
558
+ return super.windowBody(body, height);
559
+ }
560
+ if (height <= 0) {
561
+ return [];
562
+ }
563
+ const maxScroll = Math.max(0, body.length - height);
564
+ const line = targetLine ?? this.selectedPickerIndex;
565
+ const endLine = targetEndLine ?? line;
566
+ if (endLine >= this.pickerScroll + height) {
567
+ this.pickerScroll = endLine - height + 1;
568
+ }
569
+ if (line < this.pickerScroll) {
570
+ this.pickerScroll = line;
571
+ }
572
+ this.pickerScroll = Math.max(0, Math.min(this.pickerScroll, maxScroll));
573
+ return body.slice(this.pickerScroll, this.pickerScroll + height);
574
+ }
575
+
576
+ /** Wheel event or the host's scroll keybinding, in either direction. */
577
+ private isScrollUp(data: string): boolean {
578
+ return mouseWheelDirection(data) === -1 || this.matches(data, "tui.select.scrollUp");
579
+ }
580
+
581
+ private isScrollDown(data: string): boolean {
582
+ return mouseWheelDirection(data) === 1 || this.matches(data, "tui.select.scrollDown");
583
+ }
584
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,375 @@
1
+ import {
2
+ type ArgumentChoice,
3
+ type PiContext,
4
+ type PiExtensionAPI,
5
+ type PiModel,
6
+ type PluginDiagnostic,
7
+ SUBAGENTS_CONTRACT_ID,
8
+ type SubagentsService,
9
+ completeArguments,
10
+ getService,
11
+ getSessionId,
12
+ } from "@restranger/repi-lib";
13
+ import { loadFallbackConfig, saveMainFallbackConfig } from "./config.js";
14
+ import { FallbackMenuView } from "./menu-ui.js";
15
+ import { resolveFallbackModel } from "./resolver.js";
16
+ import type { FallbackConfig, ModelFallbackPluginOptions } from "./types.js";
17
+
18
+ /** `/fallback` arguments; the handler treats anything else as `status`. */
19
+ const FALLBACK_ARGUMENTS: readonly ArgumentChoice[] = [
20
+ { name: "menu", description: "Open the interactive fallback editor (default)" },
21
+ { name: "status", description: "Show enabled state, current model and fallback chain" },
22
+ { name: "list", description: "List configured fallbacks and available models" },
23
+ { name: "on", description: "Enable fallback for this session" },
24
+ { name: "off", description: "Disable fallback for this session" },
25
+ { name: "reload", description: "Re-read fallback config files" },
26
+ ];
27
+
28
+ interface ContextEntryLike {
29
+ readonly sourceEntry?: {
30
+ readonly id: string;
31
+ };
32
+ }
33
+
34
+ interface MessageLike {
35
+ readonly role?: string;
36
+ readonly stopReason?: string;
37
+ readonly errorMessage?: string;
38
+ }
39
+
40
+ interface BoundaryContextLike {
41
+ readonly contextEntries?: readonly ContextEntryLike[];
42
+ readonly contextMessages?: readonly MessageLike[];
43
+ }
44
+
45
+ interface AgentBeforeSettleEventLike {
46
+ readonly type: string;
47
+ readonly outcome?: string;
48
+ readonly context?: BoundaryContextLike;
49
+ readonly entries?: readonly Record<string, unknown>[];
50
+ }
51
+
52
+ interface BoundaryResultLike {
53
+ readonly entries?: readonly Record<string, unknown>[];
54
+ readonly continue?: boolean;
55
+ }
56
+
57
+ interface RetryState {
58
+ /** Retries consumed by the current failing streak (not reset by our own continuation turns). */
59
+ retries: number;
60
+ /** Models already tried in this streak. */
61
+ readonly attempted: Set<string>;
62
+ /** The next `turn_start` is the host continuing after `{ continue: true }`, not a new turn. */
63
+ continuation: boolean;
64
+ }
65
+
66
+ export function createModelFallbackPlugin(options: ModelFallbackPluginOptions = {}): (pi: unknown) => void {
67
+ return (host) => {
68
+ const pi = host as PiExtensionAPI;
69
+ let runtimeConfig: FallbackConfig | undefined = options.config;
70
+ let configFiles: readonly string[] = [];
71
+ let diagnostics: readonly PluginDiagnostic[] = [];
72
+ /** Per-session retry state: a shared budget made two sessions throttle each other. */
73
+ const retryStates = new Map<string, RetryState>();
74
+
75
+ const stateFor = (sessionId: string): RetryState => {
76
+ let state = retryStates.get(sessionId);
77
+ if (!state) {
78
+ state = { retries: 0, attempted: new Set<string>(), continuation: false };
79
+ retryStates.set(sessionId, state);
80
+ }
81
+ return state;
82
+ };
83
+
84
+ const resetRetryState = (sessionId: string): void => {
85
+ const state = stateFor(sessionId);
86
+ state.retries = 0;
87
+ state.attempted.clear();
88
+ state.continuation = false;
89
+ };
90
+
91
+ const refreshConfig = (ctx: PiContext): FallbackConfig => {
92
+ if (options.config) {
93
+ runtimeConfig = options.config;
94
+ return runtimeConfig;
95
+ }
96
+ const loaded = loadFallbackConfig({
97
+ cwd: options.cwd ?? ctx.cwd,
98
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
99
+ ...(options.env ? { env: options.env } : {}),
100
+ // Same rule as @restranger/repi-subagents: only an explicit `true` may read project files.
101
+ workspaceTrusted: ctx.isProjectTrusted?.() === true,
102
+ });
103
+ runtimeConfig = loaded.config;
104
+ configFiles = loaded.configFiles;
105
+ diagnostics = loaded.diagnostics;
106
+ return runtimeConfig;
107
+ };
108
+
109
+ const getConfig = (ctx: PiContext): FallbackConfig => {
110
+ return runtimeConfig ?? refreshConfig(ctx);
111
+ };
112
+
113
+ pi.on("session_start", (_event, ctx) => {
114
+ refreshConfig(ctx);
115
+ resetRetryState(getSessionId(ctx, "default"));
116
+ });
117
+
118
+ pi.on("session_shutdown", (_event, ctx) => {
119
+ retryStates.delete(getSessionId(ctx, "default"));
120
+ });
121
+
122
+ pi.on("turn_start", (_event, ctx) => {
123
+ const state = stateFor(getSessionId(ctx, "default"));
124
+ // Pi answers `{ continue: true }` with `agent.continue()`, which starts a new turn in the
125
+ // same run. Resetting here would erase the retry budget right before it is enforced.
126
+ if (state.continuation) {
127
+ state.continuation = false;
128
+ return;
129
+ }
130
+ resetRetryState(getSessionId(ctx, "default"));
131
+ });
132
+
133
+ pi.on("agent_before_settle", async (rawEvent, ctx): Promise<BoundaryResultLike | undefined> => {
134
+ const event = rawEvent as AgentBeforeSettleEventLike;
135
+ const config = getConfig(ctx);
136
+ const sessionId = getSessionId(ctx, "default");
137
+ const retry = stateFor(sessionId);
138
+
139
+ if (config.enabled === false) {
140
+ return undefined;
141
+ }
142
+
143
+ const fallbacks = config.fallbacks ?? [];
144
+ if (fallbacks.length === 0) {
145
+ return undefined;
146
+ }
147
+
148
+ // Check if this run finished in an error state
149
+ const messages = event.context?.contextMessages ?? [];
150
+ const lastMessage = messages[messages.length - 1];
151
+ const isErrorMessage = lastMessage?.role === "assistant" && lastMessage?.stopReason === "error";
152
+ const isErrorOutcome = event.outcome === "error";
153
+
154
+ if (!isErrorMessage && !isErrorOutcome) {
155
+ // The turn finished successfully: the next turn starts from a clean budget.
156
+ resetRetryState(sessionId);
157
+ return undefined;
158
+ }
159
+
160
+ const maxRetries = Math.max(1, config.maxRetriesPerTurn ?? 3);
161
+ if (retry.retries >= maxRetries) {
162
+ ctx.ui.notify(`Model fallback: reached limit of ${maxRetries} consecutive retries. Stopping.`, "error");
163
+ return undefined;
164
+ }
165
+
166
+ const currentModel = ctx.model;
167
+ const currentModelKey = currentModel ? `${currentModel.provider}/${currentModel.id}`.toLowerCase() : "";
168
+ if (currentModelKey) {
169
+ retry.attempted.add(currentModelKey);
170
+ }
171
+
172
+ // Find next candidate from fallbacks list
173
+ let nextCandidateModel: PiModel | undefined;
174
+ for (const fallbackStr of fallbacks) {
175
+ const candidate = resolveFallbackModel(fallbackStr, ctx.modelRegistry);
176
+ if (!candidate) {
177
+ continue;
178
+ }
179
+ const key = `${candidate.provider}/${candidate.id}`.toLowerCase();
180
+ if (key !== currentModelKey && !retry.attempted.has(key)) {
181
+ nextCandidateModel = candidate;
182
+ break;
183
+ }
184
+ }
185
+
186
+ if (!nextCandidateModel) {
187
+ ctx.ui.notify(
188
+ `Model fallback: all configured fallback models (${fallbacks.join(", ")}) were exhausted.`,
189
+ "warning",
190
+ );
191
+ return undefined;
192
+ }
193
+
194
+ const targetEntry = event.context?.contextEntries?.at(-1);
195
+ const targetId = targetEntry?.sourceEntry?.id;
196
+
197
+ if (typeof pi.setModel === "function") {
198
+ const success = await pi.setModel(nextCandidateModel);
199
+ if (!success) {
200
+ ctx.ui.notify(
201
+ `Model fallback: could not activate model ${nextCandidateModel.provider}/${nextCandidateModel.id}.`,
202
+ "error",
203
+ );
204
+ return undefined;
205
+ }
206
+ }
207
+
208
+ retry.retries++;
209
+ retry.attempted.add(`${nextCandidateModel.provider}/${nextCandidateModel.id}`.toLowerCase());
210
+ // The scheduler starts a fresh turn to resume with the new model; keep the budget.
211
+ retry.continuation = true;
212
+
213
+ if (config.notify !== false) {
214
+ const errorSnippet = lastMessage?.errorMessage ? `: ${lastMessage.errorMessage}` : "";
215
+ const currentLabel = currentModelKey || "Current model";
216
+ const nextLabel = `${nextCandidateModel.provider}/${nextCandidateModel.id}`;
217
+ ctx.ui.notify(`Model "${currentLabel}" failed${errorSnippet}. Falling back to "${nextLabel}"...`, "warning");
218
+ }
219
+
220
+ const entries = [...(event.entries ?? [])];
221
+ if (targetId) {
222
+ entries.push({
223
+ type: "context_edit",
224
+ targetId,
225
+ replacement: null,
226
+ });
227
+ }
228
+
229
+ return {
230
+ entries,
231
+ continue: true,
232
+ };
233
+ });
234
+
235
+ pi.registerCommand("fallback", {
236
+ description: "Model fallback settings: /fallback [menu|status|list|on|off|reload] (Tab completes)",
237
+ getArgumentCompletions: (prefix) => completeArguments(prefix, FALLBACK_ARGUMENTS),
238
+ async handler(args, ctx) {
239
+ const trimmed = args.trim().toLowerCase();
240
+ const config = getConfig(ctx);
241
+ const sessionId = getSessionId(ctx, "default");
242
+
243
+ if (trimmed === "on") {
244
+ runtimeConfig = { ...config, enabled: true };
245
+ ctx.ui.notify("Model fallback enabled.", "info");
246
+ return;
247
+ }
248
+
249
+ if (trimmed === "off") {
250
+ runtimeConfig = { ...config, enabled: false };
251
+ ctx.ui.notify("Model fallback disabled.", "info");
252
+ return;
253
+ }
254
+
255
+ if (trimmed === "reload") {
256
+ runtimeConfig = undefined;
257
+ const reloaded = refreshConfig(ctx);
258
+ ctx.ui.notify(
259
+ `Model fallback reloaded: ${reloaded.enabled ? "enabled" : "disabled"}, ${reloaded.fallbacks?.length ?? 0} fallback models.`,
260
+ "info",
261
+ );
262
+ return;
263
+ }
264
+
265
+ if (trimmed === "list") {
266
+ const available = ctx.modelRegistry?.getAvailable?.();
267
+ const all = available && available.length > 0 ? available : (ctx.modelRegistry?.getAll() ?? []);
268
+ const listText = all.map((m) => ` ${m.provider}/${m.id}`).join("\n");
269
+ ctx.ui.notify(
270
+ `Configured fallbacks:\n${(config.fallbacks ?? []).map((f) => ` - ${f}`).join("\n") || " (none)"}\n\nAvailable models:\n${listText || " (none)"}`,
271
+ "info",
272
+ );
273
+ return;
274
+ }
275
+
276
+ if (trimmed === "" || trimmed === "menu" || trimmed === "ui") {
277
+ if (typeof ctx.ui.custom === "function") {
278
+ const subagentsService = getService<SubagentsService>(SUBAGENTS_CONTRACT_ID, sessionId);
279
+ // No service means no declared agents to edit. A hardcoded catalogue here drifted from
280
+ // `@restranger/repi-subagents` and wrote fallbacks for agents that do not exist.
281
+ const subagents = subagentsService?.listAgents() ?? [];
282
+
283
+ const available = ctx.modelRegistry?.getAvailable?.();
284
+ const availableModels = available && available.length > 0 ? available : (ctx.modelRegistry?.getAll() ?? []);
285
+ const view = new FallbackMenuView({
286
+ mainModel: ctx.model,
287
+ mainFallbacks: config.fallbacks ?? [],
288
+ subagents,
289
+ availableModels,
290
+ onSave: (entries) => {
291
+ const cwd = options.cwd ?? ctx.cwd;
292
+ const workspaceTrusted = ctx.isProjectTrusted?.() === true;
293
+ try {
294
+ const mainEntry = entries.find((e) => e.isMain);
295
+ if (mainEntry) {
296
+ saveMainFallbackConfig(cwd, mainEntry.fallbackModels, { workspaceTrusted });
297
+ runtimeConfig = {
298
+ ...config,
299
+ fallbacks: [...mainEntry.fallbackModels],
300
+ };
301
+ }
302
+
303
+ const subagentUpdates = entries
304
+ .filter((e) => !e.isMain)
305
+ .map((e) => ({
306
+ name: e.id,
307
+ fallbackModels: [...e.fallbackModels],
308
+ }));
309
+ if (subagentUpdates.length > 0) {
310
+ if (!subagentsService?.setAgentFallbackModels) {
311
+ ctx.ui.notify(
312
+ "Model fallback: @restranger/repi-subagents is not available, so agent fallbacks were not saved.",
313
+ "warning",
314
+ );
315
+ } else {
316
+ // @restranger/repi-subagents owns `.repi/subagents.json`; it applies the list and persists it.
317
+ for (const update of subagentUpdates) {
318
+ subagentsService.setAgentFallbackModels(update.name, update.fallbackModels);
319
+ }
320
+ }
321
+ }
322
+ } catch (err) {
323
+ ctx.ui.notify(
324
+ `Model fallback: could not save settings: ${err instanceof Error ? err.message : String(err)}`,
325
+ "error",
326
+ );
327
+ }
328
+ },
329
+ });
330
+
331
+ try {
332
+ await ctx.ui.custom(
333
+ (tui, theme, keybindings, done) => {
334
+ view.attach(tui, theme, keybindings, done);
335
+ return view;
336
+ },
337
+ {
338
+ overlay: true,
339
+ overlayOptions: {
340
+ anchor: "center",
341
+ width: "90%",
342
+ maxHeight: "85%",
343
+ },
344
+ },
345
+ );
346
+ } catch (err) {
347
+ ctx.ui.notify(`Fallback menu failed: ${err instanceof Error ? err.message : String(err)}`, "error");
348
+ }
349
+ return;
350
+ }
351
+ }
352
+
353
+ // Status overview when UI is not available
354
+ const statusText = [
355
+ `Model Fallback: ${config.enabled !== false ? "ENABLED" : "DISABLED"}`,
356
+ `Current Model: ${ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "none"}`,
357
+ `Configured Fallbacks (${config.fallbacks?.length ?? 0}):\n${(config.fallbacks ?? []).map((f) => ` - ${f}`).join("\n") || " (none)"}`,
358
+ `Max retries per turn: ${config.maxRetriesPerTurn ?? 3}`,
359
+ `Config files:\n${configFiles.map((f) => ` - ${f}`).join("\n") || " (none)"}`,
360
+ diagnostics.length > 0
361
+ ? `Diagnostics:\n${diagnostics.map((d) => ` ${d.level === "error" ? "!" : "?"} ${d.message}${d.path ? ` (${d.path})` : ""}`).join("\n")}`
362
+ : undefined,
363
+ ]
364
+ .filter(Boolean)
365
+ .join("\n\n");
366
+
367
+ ctx.ui.notify(statusText, "info");
368
+ },
369
+ });
370
+ };
371
+ }
372
+
373
+ export default function modelFallbackExtension(pi: unknown): void {
374
+ createModelFallbackPlugin()(pi);
375
+ }
@@ -0,0 +1,37 @@
1
+ import { type PiModel, type PiModelRegistry, isModelLike, scoreModel } from "@restranger/repi-lib";
2
+
3
+ export function resolveFallbackModel(input: string, registry: PiModelRegistry | undefined): PiModel | undefined {
4
+ if (!registry) {
5
+ return undefined;
6
+ }
7
+
8
+ const all = registry.getAvailable?.() ?? registry.getAll();
9
+ const models = all.filter(isModelLike);
10
+ const normalized = input.trim().toLowerCase();
11
+
12
+ const exact = models.find((m) => `${m.provider}/${m.id}`.toLowerCase() === normalized);
13
+ if (exact) {
14
+ return exact;
15
+ }
16
+
17
+ const slash = normalized.indexOf("/");
18
+ if (slash > 0) {
19
+ const provider = normalized.slice(0, slash);
20
+ const id = normalized.slice(slash + 1);
21
+ const found = registry.find(provider, id);
22
+ if (isModelLike(found)) {
23
+ return found;
24
+ }
25
+ }
26
+
27
+ const scored = models
28
+ .map((model) => ({ model, score: scoreModel(model, normalized) }))
29
+ .filter((entry) => entry.score >= 20)
30
+ .sort((left, right) => right.score - left.score);
31
+ const best = scored[0];
32
+ if (best && (!scored[1] || scored[1].score < best.score)) {
33
+ return best.model;
34
+ }
35
+
36
+ return undefined;
37
+ }
package/src/types.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { PluginDiagnostic } from "@restranger/repi-lib";
2
+
3
+ /** Public types for the @restranger/repi-model-fallback plugin. */
4
+
5
+ export interface FallbackConfig {
6
+ readonly version?: number;
7
+ readonly enabled?: boolean;
8
+ readonly fallbacks?: readonly string[];
9
+ readonly maxRetriesPerTurn?: number;
10
+ readonly notify?: boolean;
11
+ }
12
+
13
+ export interface ModelFallbackConfigContext {
14
+ readonly cwd: string;
15
+ readonly homeDir?: string;
16
+ readonly env?: Readonly<Record<string, string | undefined>>;
17
+ readonly workspaceTrusted?: boolean;
18
+ }
19
+
20
+ export interface LoadedFallbackConfig {
21
+ readonly config: FallbackConfig;
22
+ readonly configFiles: readonly string[];
23
+ readonly diagnostics: readonly PluginDiagnostic[];
24
+ }
25
+
26
+ export interface ModelFallbackPluginOptions {
27
+ readonly cwd?: string;
28
+ readonly homeDir?: string;
29
+ readonly env?: Readonly<Record<string, string | undefined>>;
30
+ readonly config?: FallbackConfig;
31
+ }