pi-petrroll 0.3.0 → 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
 
@@ -128,8 +129,10 @@ Pi's totals include all entries in the session file, including abandoned branche
128
129
 
129
130
  Marks where your prompts and the assistant's replies start on the scrollbar at the right of Pi's fullscreen transcript, like an editor's overview ruler:
130
131
 
131
- - **Prompts**: `━` in the theme's accent color. A prompt under the thumb shows as an accent `█`.
132
- - **Replies** (assistant text): `─` in the text color. Replies under the thumb are not shown separately.
132
+ - **Prompts**: `━` in the theme's accent color.
133
+ - **Replies** (assistant text): `─` in the text color.
134
+
135
+ Under the thumb, a mark crosses it as `╋` (accent for prompts, the thumb color for replies), so the thumb keeps its width. While you drag the scrollbar, Pi shows a solid `█` thumb. Prompts then recolor it to accent, and reply marks are hidden.
133
136
 
134
137
  Each mark sits at its proportional position in the transcript, so dragging or scrolling the thumb onto a mark brings that message into view. Prompts win when both fall on the same row. Tool output, thinking-only, and tool-call-only assistant turns are not marked.
135
138
 
@@ -140,6 +143,27 @@ Limitations:
140
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.
141
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.
142
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
+
143
167
  ## Development
144
168
 
145
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
+ }
@@ -44,8 +44,13 @@ export function createMarkStyles(theme: ThemeLike): MarkStyles {
44
44
  const color = (kind: MarkKind) => (kind === "prompt" ? "accent" : "text");
45
45
  return {
46
46
  track: (kind) => theme.fg(color(kind), kind === "prompt" ? "━" : "─"),
47
- // Pi's thumb already uses the text color, so only prompts stand out on it.
48
- thumb: (kind, glyph) => (kind === "prompt" ? theme.fg("accent", "█") : undefined),
47
+ // Keep the thumb's width: the idle thumb "┃" becomes a heavy cross "╋" (the same tick as on the
48
+ // track, crossing the thumb); the active block thumb "█" cannot carry a tick, so only prompts
49
+ // recolor it. Replies stay in Pi's thumb color so the thumb never changes width or vanishes.
50
+ thumb: (kind, glyph, piThumb) => {
51
+ const cell = glyph === "┃" ? "╋" : glyph;
52
+ return kind === "prompt" ? theme.fg("accent", cell) : piThumb(cell);
53
+ },
49
54
  };
50
55
  }
51
56
 
@@ -16,8 +16,11 @@ const ZONE_START = /^(?:\x1b\]133;[BC](?:\x07|\x1b\\))*\x1b\]133;A(?:\x07|\x1b\\
16
16
  export interface MarkStyles {
17
17
  /** Track cell (outside the thumb) for a row containing a mark. */
18
18
  track(kind: MarkKind): string;
19
- /** Thumb cell for a row containing a mark; receives Pi's thumb glyph. Return undefined to keep Pi's thumb. */
20
- thumb(kind: MarkKind, glyph: string): string | undefined;
19
+ /**
20
+ * Thumb cell for a row containing a mark; receives Pi's thumb glyph and Pi's thumb styler.
21
+ * Return undefined to keep Pi's thumb unchanged.
22
+ */
23
+ thumb(kind: MarkKind, glyph: string, piThumb: (text: string) => string): string | undefined;
21
24
  }
22
25
 
23
26
  /** Minimal structural view of `@earendil-works/pi-tui`'s ScrollView that this module relies on. */
@@ -115,7 +118,7 @@ export function attachScrollbarMarks(view: ScrollViewLike, options: AttachOption
115
118
  };
116
119
  view.scrollbarThumbStyle = (text) => {
117
120
  const kind = track[row++];
118
- return (kind && options.styles.thumb(kind, text)) ?? originalThumb(text);
121
+ return (kind && options.styles.thumb(kind, text, originalThumb)) ?? originalThumb(text);
119
122
  };
120
123
 
121
124
  let restored = false;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-petrroll",
3
- "version": "0.3.0",
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)",