@restranger/repi-model-fallback 0.0.0-stage → 0.0.1-sha.2ba2721

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/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
+ }