pi-petrroll 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,6 +7,7 @@ Small, focused extensions for [Pi](https://pi.dev). MIT licensed.
7
7
  | [Change directory](#change-directory) | `/cd <path>` | `change_directory` |
8
8
  | [External costs](#external-costs) | — | `add_cost` |
9
9
  | [Scrollbar marks](#scrollbar-marks) | — | — |
10
+ | [Provider fallback](#provider-fallback) | `/provider-fallback [restore]` | — |
10
11
 
11
12
  Independent, focused extensions. No skills, shell wrappers, or replacement built-in tools.
12
13
 
@@ -142,6 +143,27 @@ Limitations:
142
143
  - Fullscreen TUI mode only (Pi's default `tuiMode`). In regular mode the terminal owns scrollback and the scrollbar, so the extension does nothing. Print, JSON, and RPC modes are unaffected.
143
144
  - Pi has no public scrollbar API yet. The extension wraps the transcript `ScrollView`'s scrollbar style callbacks and content render on that one instance, and wraps `UserMessageComponent.render` once per process to tell prompts from replies. It finds message starts from the OSC 133 zone markers Pi already renders. Disabling or reloading restores the original callbacks. Tested against Pi 1.4.0; future Pi versions may change these internals.
144
145
 
146
+ ## Provider fallback
147
+
148
+ When a request to a provider fails with a rate limit (HTTP 429, `rate_limit_error`), switches the session to the same model on a fallback provider. Pi's automatic retry then goes to the fallback, so the turn continues without your input.
149
+
150
+ Configure it in `~/.pi/agent/settings.json` (or a project's `.pi/settings.json`):
151
+
152
+ ```json
153
+ {
154
+ "providerFallback": {
155
+ "fallbacks": { "anthropic": "radius" },
156
+ "restoreAfterMinutes": 30
157
+ }
158
+ }
159
+ ```
160
+
161
+ - `fallbacks` maps a provider to its fallback. A string keeps the model ID; `{ "provider": "radius", "models": { "claude-opus-4-5": "opus" } }` maps IDs. If a fallback lacks the model or credentials, its own fallback is tried.
162
+ - `restoreAfterMinutes` (default `30`, `0` disables): on your next prompt after this time, switch back to the original model. If it is still rate limited, the fallback happens again.
163
+ - `errorPattern` (optional, case-insensitive regex) overrides which error messages trigger the switch. Default: `\b429\b|rate[ _-]?limit`.
164
+
165
+ The switch is a normal model change: it is recorded in the session and loses the prompt cache. A manual `/model` change stops tracking. `/provider-fallback` shows the rules and state; `/provider-fallback restore` switches back now. Requires automatic retry (`retry.enabled`, on by default); otherwise the model is switched and you resend the prompt.
166
+
145
167
  ## Development
146
168
 
147
169
  ```sh
@@ -0,0 +1,211 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CONFIG_DIR_NAME, getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ /**
6
+ * Settings key, in `<agentDir>/settings.json` or `<project>/.pi/settings.json`:
7
+ *
8
+ * ```json
9
+ * "providerFallback": {
10
+ * "fallbacks": { "anthropic": "radius" },
11
+ * "restoreAfterMinutes": 30
12
+ * }
13
+ * ```
14
+ *
15
+ * A fallback is a provider name (same model ID) or `{ "provider": "radius", "models": { "<from-id>": "<to-id>" } }`.
16
+ */
17
+ export const SETTINGS_KEY = "providerFallback";
18
+
19
+ export const DEFAULT_ERROR_PATTERN = "\\b429\\b|rate[ _-]?limit";
20
+ export const DEFAULT_RESTORE_AFTER_MINUTES = 30;
21
+
22
+ export interface FallbackTarget {
23
+ provider: string;
24
+ models?: Record<string, string>;
25
+ }
26
+
27
+ export interface FallbackConfig {
28
+ fallbacks: Record<string, FallbackTarget>;
29
+ errorPattern: RegExp;
30
+ /** 0 disables automatic restore. */
31
+ restoreAfterMs: number;
32
+ }
33
+
34
+ export function parseConfig(raw: unknown): FallbackConfig {
35
+ const value = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
36
+ const fallbacks: Record<string, FallbackTarget> = {};
37
+ const rawFallbacks = value.fallbacks && typeof value.fallbacks === "object" ? (value.fallbacks as Record<string, unknown>) : {};
38
+ for (const [from, target] of Object.entries(rawFallbacks)) {
39
+ if (typeof target === "string" && target.trim()) {
40
+ fallbacks[from] = { provider: target.trim() };
41
+ } else if (target && typeof target === "object" && typeof (target as FallbackTarget).provider === "string") {
42
+ const { provider, models } = target as FallbackTarget;
43
+ fallbacks[from] = {
44
+ provider,
45
+ models: models && typeof models === "object" ? Object.fromEntries(Object.entries(models).filter(([, v]) => typeof v === "string")) : undefined,
46
+ };
47
+ }
48
+ }
49
+ let errorPattern = new RegExp(DEFAULT_ERROR_PATTERN, "i");
50
+ if (typeof value.errorPattern === "string" && value.errorPattern) {
51
+ try {
52
+ errorPattern = new RegExp(value.errorPattern, "i");
53
+ } catch {
54
+ // Keep the default on an invalid pattern.
55
+ }
56
+ }
57
+ const minutes = typeof value.restoreAfterMinutes === "number" && Number.isFinite(value.restoreAfterMinutes) && value.restoreAfterMinutes >= 0
58
+ ? value.restoreAfterMinutes
59
+ : DEFAULT_RESTORE_AFTER_MINUTES;
60
+ return { fallbacks, errorPattern, restoreAfterMs: minutes * 60_000 };
61
+ }
62
+
63
+ function readJson(path: string): Record<string, unknown> {
64
+ try {
65
+ if (!existsSync(path)) return {};
66
+ const parsed = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
67
+ return parsed && typeof parsed === "object" ? parsed : {};
68
+ } catch {
69
+ return {};
70
+ }
71
+ }
72
+
73
+ /** Effective `providerFallback` settings: project values override global ones key by key. */
74
+ export function loadRawSettings(pi: ExtensionAPI, cwd: string): unknown {
75
+ const getSettings = (pi as { getSettings?: () => Record<string, unknown> }).getSettings;
76
+ if (typeof getSettings === "function") return getSettings.call(pi)?.[SETTINGS_KEY];
77
+ // Older Pi versions: merge the two settings files ourselves.
78
+ const global = readJson(join(getAgentDir(), "settings.json"))[SETTINGS_KEY] as Record<string, unknown> | undefined;
79
+ const project = readJson(join(cwd, CONFIG_DIR_NAME, "settings.json"))[SETTINGS_KEY] as Record<string, unknown> | undefined;
80
+ if (!global && !project) return undefined;
81
+ return {
82
+ ...global,
83
+ ...project,
84
+ fallbacks: { ...(global?.fallbacks as object | undefined), ...(project?.fallbacks as object | undefined) },
85
+ };
86
+ }
87
+
88
+ interface AssistantLike {
89
+ role: string;
90
+ stopReason?: string;
91
+ errorMessage?: string;
92
+ provider?: string;
93
+ model?: string;
94
+ }
95
+
96
+ export function isFallbackError(message: AssistantLike, config: FallbackConfig): boolean {
97
+ return message.role === "assistant"
98
+ && message.stopReason === "error"
99
+ && typeof message.errorMessage === "string"
100
+ && config.errorPattern.test(message.errorMessage);
101
+ }
102
+
103
+ interface Switched {
104
+ from: { provider: string; id: string };
105
+ to: { provider: string; id: string };
106
+ at: number;
107
+ }
108
+
109
+ export default function (pi: ExtensionAPI) {
110
+ let config = parseConfig(undefined);
111
+ let pending: { provider: string; id: string; error: string } | undefined;
112
+ let switched: Switched | undefined;
113
+ let switching = false;
114
+
115
+ const reload = (ctx: ExtensionContext) => {
116
+ config = parseConfig(loadRawSettings(pi, ctx.cwd));
117
+ };
118
+
119
+ const setModel = async (ctx: ExtensionContext, provider: string, id: string): Promise<boolean> => {
120
+ const model = ctx.modelRegistry.find(provider, id);
121
+ if (!model) return false;
122
+ switching = true;
123
+ try {
124
+ return await pi.setModel(model);
125
+ } catch {
126
+ return false;
127
+ } finally {
128
+ switching = false;
129
+ }
130
+ };
131
+
132
+ const restore = async (ctx: ExtensionContext, reason: string): Promise<boolean> => {
133
+ if (!switched) return false;
134
+ const { from } = switched;
135
+ const ok = await setModel(ctx, from.provider, from.id);
136
+ if (ok) {
137
+ switched = undefined;
138
+ ctx.ui.notify(`Provider fallback: back on ${from.provider}/${from.id} (${reason}).`, "info");
139
+ }
140
+ return ok;
141
+ };
142
+
143
+ pi.on("session_start", async (_event, ctx) => {
144
+ reload(ctx);
145
+ pending = undefined;
146
+ switched = undefined;
147
+ });
148
+
149
+ // A manual model change ends fallback tracking.
150
+ pi.on("model_select", async () => {
151
+ if (!switching) switched = undefined;
152
+ });
153
+
154
+ pi.on("message_end", async (event) => {
155
+ const message = event.message as AssistantLike;
156
+ if (message.role !== "assistant" || !message.provider || !message.model) return;
157
+ if (!config.fallbacks[message.provider] || !isFallbackError(message, config)) return;
158
+ pending = { provider: message.provider, id: message.model, error: message.errorMessage ?? "" };
159
+ });
160
+
161
+ // Switch after the run ends, before Pi's automatic retry starts, so the retry goes to the fallback.
162
+ pi.on("agent_end", async (_event, ctx) => {
163
+ const failed = pending;
164
+ pending = undefined;
165
+ if (!failed) return;
166
+ // Only switch when the failing provider is still the selected one.
167
+ if (ctx.model?.provider !== failed.provider) return;
168
+ const visited = new Set<string>([failed.provider]);
169
+ let target = config.fallbacks[failed.provider];
170
+ while (target) {
171
+ const id = target.models?.[failed.id] ?? failed.id;
172
+ if (await setModel(ctx, target.provider, id)) {
173
+ // Remember the original model across a chain of fallbacks.
174
+ const origin = switched?.from ?? { provider: failed.provider, id: failed.id };
175
+ switched = { from: origin, to: { provider: target.provider, id }, at: Date.now() };
176
+ ctx.ui.notify(`Provider fallback: ${failed.provider} is rate limited, switched to ${target.provider}/${id}.`, "warning");
177
+ return;
178
+ }
179
+ // Target unavailable (unknown model or no credentials): try its own fallback.
180
+ if (visited.has(target.provider)) break;
181
+ visited.add(target.provider);
182
+ target = config.fallbacks[target.provider];
183
+ }
184
+ ctx.ui.notify(`Provider fallback: ${failed.provider} is rate limited, but no fallback model for ${failed.id} is available.`, "error");
185
+ });
186
+
187
+ // Prefer the primary again on a new prompt once the cooldown has passed.
188
+ pi.on("before_agent_start", async (_event, ctx) => {
189
+ if (!switched || config.restoreAfterMs <= 0) return;
190
+ if (Date.now() - switched.at < config.restoreAfterMs) return;
191
+ await restore(ctx, "cooldown elapsed");
192
+ });
193
+
194
+ pi.registerCommand("provider-fallback", {
195
+ description: "Show provider fallback status, or `restore` to switch back to the primary provider now",
196
+ handler: async (args, ctx) => {
197
+ reload(ctx);
198
+ if (args.trim() === "restore") {
199
+ if (!switched) ctx.ui.notify("Provider fallback: not currently on a fallback.", "info");
200
+ else if (!(await restore(ctx, "restored manually"))) ctx.ui.notify(`Provider fallback: could not switch back to ${switched.from.provider}/${switched.from.id}.`, "error");
201
+ return;
202
+ }
203
+ const rules = Object.entries(config.fallbacks).map(([from, to]) => `${from} → ${to.provider}`).join(", ") || "none configured";
204
+ const restoreText = config.restoreAfterMs > 0 ? `restore after ${config.restoreAfterMs / 60_000} min` : "no automatic restore";
205
+ const state = switched
206
+ ? `on fallback ${switched.to.provider}/${switched.to.id} since ${new Date(switched.at).toLocaleTimeString()} (from ${switched.from.provider}/${switched.from.id})`
207
+ : "on primary";
208
+ ctx.ui.notify(`Provider fallback: ${rules}; ${restoreText}; ${state}.`, "info");
209
+ },
210
+ });
211
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-petrroll",
3
- "version": "0.3.1",
4
- "description": "Small, focused Pi extensions by petrroll: switch projects, track external costs, and mark prompts on the scrollbar.",
3
+ "version": "0.4.0",
4
+ "description": "Small, focused Pi extensions by petrroll: switch projects, track external costs, mark prompts on the scrollbar, and fall back to another provider on rate limits.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Petr Houška (petrroll)",