@bizzywork/routing 0.0.0-stage → 0.1.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.
@@ -0,0 +1,433 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ // The package index re-exports the stream class as a type only; omp's own code imports it from here.
6
+ import { AssistantMessageEventStream } from "@oh-my-pi/pi-ai/utils/event-stream";
7
+ import {
8
+ streamSimple as sendOnModel,
9
+ type AssistantMessage,
10
+ type AssistantMessageEvent,
11
+ type Context,
12
+ type Model,
13
+ type SimpleStreamOptions,
14
+ } from "@oh-my-pi/pi-ai";
15
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
16
+ import {
17
+ autoMetadata,
18
+ candidatesFor,
19
+ isTransient,
20
+ modelId,
21
+ realModel,
22
+ routingWindow,
23
+ turnOf,
24
+ } from "./routing.ts";
25
+
26
+ // Written by the installer: where the routing API listens and, optionally, how to start it.
27
+ interface Config {
28
+ url: string;
29
+ server?: { argv: string[]; cwd: string; env: Record<string, string> };
30
+ }
31
+ interface Decision {
32
+ model: string;
33
+ rule: string;
34
+ reason: string;
35
+ notice?: string;
36
+ }
37
+ interface ModelsReply {
38
+ picks: { efficient: string; capable: string } | null;
39
+ }
40
+
41
+ const STEP_MS = 2000;
42
+ // A turn's first step waits for Jev: its 10 s timeout plus the routing API's own time.
43
+ const FIRST_STEP_MS = 12000;
44
+ const POLL_MS = 30000;
45
+ const API = "bizzy-auto";
46
+ const WAITING = "Bizzy Auto · waiting for a request";
47
+ const DISCLOSURE =
48
+ "Bizzy Auto sends each prompt you type to Bizzy's routing API, where Jev picks the capable or efficient model (BIZZY_SHARE_PROMPTS=0 in ~/.bizzy/routing/.env keeps prompts here). /bizzy off stops routing.";
49
+ // Shown once per install: the installer replaces this folder.
50
+ const DISCLOSED = join(dirname(fileURLToPath(import.meta.url)), ".disclosed");
51
+
52
+ const safeId = (value: string) =>
53
+ value
54
+ .replace(/[^A-Za-z0-9._:/-]/g, "-")
55
+ .replace(/^[^A-Za-z0-9]+/, "")
56
+ .slice(0, 128) || "none";
57
+
58
+ function loadConfig(): Config {
59
+ let file: Partial<Config> = {};
60
+ try {
61
+ file = JSON.parse(
62
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), "bizzy.json"), "utf8"),
63
+ ) as Partial<Config>;
64
+ } catch {
65
+ // No installer config: the default URL, and no server to start.
66
+ }
67
+ return {
68
+ url: process.env.BIZZY_ROUTING_URL ?? file.url ?? "http://127.0.0.1:4100",
69
+ ...(file.server ? { server: file.server } : {}),
70
+ };
71
+ }
72
+
73
+ const config = loadConfig();
74
+ // One routing server per machine, however many sessions and subagents load this module.
75
+ let keepingServer = false;
76
+
77
+ type Meta = { contextWindow: number; maxTokens: number; input: string[]; reasoning: boolean };
78
+ // omp runs this extension again for every subagent session, and the last registration owns bizzy/auto for the
79
+ // whole process, so routing state lives here, once, and every registration carries the main session's.
80
+ const shared: {
81
+ ctx?: ExtensionContext;
82
+ enabled: boolean;
83
+ compacted: boolean;
84
+ status: string;
85
+ sent?: string;
86
+ // Why the last turn routed without Jev, shown once per session and in /bizzy status.
87
+ notice?: string | undefined;
88
+ noticed?: boolean;
89
+ // Conservative until the server first names its picks.
90
+ meta: Meta;
91
+ } = {
92
+ enabled: true,
93
+ compacted: false,
94
+ status: WAITING,
95
+ meta: { contextWindow: 128_000, maxTokens: 16_000, input: ["text"], reasoning: false },
96
+ };
97
+
98
+ class ApiError extends Error {
99
+ constructor(readonly status: number) {
100
+ super(`routing API ${status}`);
101
+ }
102
+ }
103
+
104
+ async function post<T>(path: string, body: unknown, ms = STEP_MS): Promise<T> {
105
+ const response = await fetch(`${config.url}/v1/harness/omp/${path}`, {
106
+ method: "POST",
107
+ headers: { "content-type": "application/json" },
108
+ body: JSON.stringify(body),
109
+ signal: AbortSignal.timeout(ms),
110
+ });
111
+ if (!response.ok) throw new ApiError(response.status);
112
+ return (await response.json()) as T;
113
+ }
114
+
115
+ // The harness routes answer 405 to a GET, which says the API is up with them on.
116
+ async function isUp(): Promise<boolean> {
117
+ try {
118
+ const response = await fetch(`${config.url}/v1/harness/omp/step`, {
119
+ signal: AbortSignal.timeout(STEP_MS),
120
+ });
121
+ return response.status === 405;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ function keepServer(c: ExtensionContext) {
128
+ const { server } = config;
129
+ if (!server || keepingServer) return;
130
+ keepingServer = true;
131
+ let child: ReturnType<typeof spawn> | undefined;
132
+ const check = async () => {
133
+ if (child && child.exitCode === null) return;
134
+ if (await isUp()) return;
135
+ child = spawn(server.argv[0]!, server.argv.slice(1), {
136
+ cwd: server.cwd,
137
+ env: { ...process.env, ...server.env },
138
+ stdio: "ignore",
139
+ detached: true,
140
+ });
141
+ child.unref();
142
+ };
143
+ void check();
144
+ c.setInterval(() => void check(), POLL_MS);
145
+ }
146
+
147
+ function failure(model: Model, text: string): AssistantMessage {
148
+ return {
149
+ role: "assistant",
150
+ content: [],
151
+ api: model.api,
152
+ provider: model.provider,
153
+ model: model.id,
154
+ usage: {
155
+ input: 0,
156
+ output: 0,
157
+ cacheRead: 0,
158
+ cacheWrite: 0,
159
+ totalTokens: 0,
160
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
161
+ },
162
+ stopReason: "error",
163
+ errorMessage: text,
164
+ timestamp: Date.now(),
165
+ };
166
+ }
167
+
168
+ export default function (pi: ExtensionAPI) {
169
+ const show = (text: string) => {
170
+ shared.status = text;
171
+ shared.ctx?.ui.setStatus("bizzy", text);
172
+ };
173
+
174
+ const register = (meta: Meta = shared.meta) => {
175
+ shared.meta = meta;
176
+ pi.registerProvider("bizzy", {
177
+ api: API,
178
+ baseUrl: "https://bizzy-auto.invalid/",
179
+ apiKey: "unused-by-bizzy-auto",
180
+ streamSimple,
181
+ models: [
182
+ {
183
+ id: "auto",
184
+ name: "Bizzy Auto",
185
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
186
+ ...meta,
187
+ input: meta.input as ("text" | "image")[],
188
+ },
189
+ ],
190
+ });
191
+ };
192
+
193
+ /** The model sent on when routing is off or refused. */
194
+ const fallbackOf = (c: ExtensionContext) => realModel(c.models.resolve("@default"));
195
+ const candidates = (c: ExtensionContext) => candidatesFor(c.models.list(), fallbackOf(c));
196
+
197
+ // The server keeps the list in memory, so it is sent on every poll: a restarted server has it again within one.
198
+ async function sendModels(c: ExtensionContext) {
199
+ const models = candidates(c);
200
+ const available = models.map(modelId);
201
+ const { picks } = await post<ModelsReply>("models", { fetchedAt: Date.now(), available });
202
+ shared.sent = JSON.stringify(available);
203
+ const efficient = picks && models.find((model) => modelId(model) === picks.efficient);
204
+ const capable = picks && models.find((model) => modelId(model) === picks.capable);
205
+ if (efficient && capable) {
206
+ const meta = autoMetadata(efficient, capable);
207
+ if (JSON.stringify(meta) !== JSON.stringify(shared.meta)) register(meta);
208
+ }
209
+ }
210
+
211
+ const refresh = (c: ExtensionContext) => sendModels(c).catch(() => {});
212
+
213
+ /** The server's answer as one of the user's models, with its own login. */
214
+ const pick = (c: ExtensionContext, id: string) =>
215
+ candidates(c).find((model) => modelId(model) === id) ?? realModel(c.models.resolve(id));
216
+
217
+ function streamSimple(model: Model, context: Context, options?: SimpleStreamOptions) {
218
+ const stream = new AssistantMessageEventStream();
219
+ void run(stream, model, context, options).catch((error) => {
220
+ stream.push({
221
+ type: "error",
222
+ reason: "error",
223
+ error: failure(model, error instanceof Error ? error.message : String(error)),
224
+ });
225
+ });
226
+ return stream;
227
+ }
228
+
229
+ async function run(
230
+ out: AssistantMessageEventStream,
231
+ auto: Model,
232
+ context: Context,
233
+ options?: SimpleStreamOptions,
234
+ ) {
235
+ const c = shared.ctx;
236
+ const fallbackModel = c && fallbackOf(c);
237
+ if (!c || !fallbackModel) {
238
+ out.push({
239
+ type: "error",
240
+ reason: "error",
241
+ error: failure(auto, "Bizzy Auto needs a @default model to send on when routing is off"),
242
+ });
243
+ return;
244
+ }
245
+ const session = safeId(options?.sessionId ?? "omp");
246
+ const turn = turnOf(context.messages as never);
247
+ let target: Model = fallbackModel;
248
+ if (shared.enabled) {
249
+ try {
250
+ if (shared.sent !== JSON.stringify(candidates(c).map(modelId))) await sendModels(c);
251
+ const ask = () =>
252
+ post<Decision>(
253
+ "step",
254
+ {
255
+ session,
256
+ turnId: safeId(turn.turnId),
257
+ index: turn.index,
258
+ depth: turn.depth,
259
+ compacted: shared.compacted,
260
+ messages: routingWindow(context.messages as never),
261
+ ...(turn.prompt ? { prompt: turn.prompt } : {}),
262
+ },
263
+ turn.index === 0 ? FIRST_STEP_MS : STEP_MS,
264
+ );
265
+ // A 409 means the server restarted and lost the list: send it again rather than wait for the next poll.
266
+ const decision = await ask().catch(async (error: unknown) => {
267
+ if (!(error instanceof ApiError && error.status === 409)) throw error;
268
+ await sendModels(c);
269
+ return ask();
270
+ });
271
+ shared.compacted = false;
272
+ target = pick(c, decision.model) ?? fallbackModel;
273
+ if (turn.index === 0) shared.notice = decision.notice;
274
+ show(`Bizzy Auto · ${modelId(target)} · ${shared.notice ? "own rules" : decision.rule}`);
275
+ if (shared.notice && !shared.noticed) {
276
+ shared.noticed = true;
277
+ c.ui.notify(`Bizzy Auto: ${shared.notice}`, "info");
278
+ }
279
+ } catch (error) {
280
+ show(
281
+ `Bizzy Auto unavailable · keeping ${modelId(target)}: ${error instanceof Error ? error.message : String(error)}`,
282
+ );
283
+ }
284
+ } else show("Bizzy Auto off");
285
+
286
+ const send = async (real: Model) =>
287
+ sendOnModel(real, context, {
288
+ ...options,
289
+ apiKey: await c.modelRegistry.getApiKey(real, options?.sessionId),
290
+ headers: {
291
+ ...options?.headers,
292
+ ...(await c.modelRegistry.getProviderHeaders(real.provider)),
293
+ },
294
+ });
295
+
296
+ // Nothing has reached omp before the first real event, so a request that fails on the routed model is sent
297
+ // again on another; once an event has been forwarded, errors pass through as they are.
298
+ const first = async (real: Model) => {
299
+ const source = (await send(real))[Symbol.asyncIterator]();
300
+ const held: AssistantMessageEvent[] = [];
301
+ for (;;) {
302
+ const next = await source.next();
303
+ if (next.done) return { source, held, failed: undefined };
304
+ held.push(next.value);
305
+ if (next.value.type === "start") continue;
306
+ return {
307
+ source,
308
+ held,
309
+ failed: next.value.type === "error" ? next.value.error : undefined,
310
+ };
311
+ }
312
+ };
313
+
314
+ let real = target;
315
+ let opened = await first(real).catch((error) => ({
316
+ source: undefined,
317
+ held: [] as AssistantMessageEvent[],
318
+ failed: failure(real, error instanceof Error ? error.message : String(error)),
319
+ }));
320
+ if (
321
+ opened.failed &&
322
+ opened.failed.stopReason !== "aborted" &&
323
+ shared.enabled &&
324
+ !options?.signal?.aborted
325
+ ) {
326
+ const text = opened.failed.errorMessage ?? "";
327
+ const transient = isTransient(text);
328
+ const again = await post<{ model: string | null }>("fallback", {
329
+ session,
330
+ turnId: safeId(turn.turnId),
331
+ model: safeId(modelId(real)),
332
+ transient,
333
+ }).catch(() => ({ model: null }));
334
+ const other = again.model ? pick(c, again.model) : undefined;
335
+ if (other && modelId(other) !== modelId(real)) {
336
+ show(
337
+ `Bizzy Auto · ${modelId(other)} · ${modelId(real)} ${transient ? "failed" : "unavailable"}`,
338
+ );
339
+ real = other;
340
+ opened = await first(real).catch((error) => ({
341
+ source: undefined,
342
+ held: [] as AssistantMessageEvent[],
343
+ failed: failure(real, error instanceof Error ? error.message : String(error)),
344
+ }));
345
+ }
346
+ }
347
+
348
+ let last = undefined as AssistantMessageEvent | undefined;
349
+ const forward = (event: AssistantMessageEvent) => {
350
+ last = event;
351
+ out.push(event);
352
+ };
353
+ if (opened.failed && !opened.held.length)
354
+ forward({ type: "error", reason: "error", error: opened.failed });
355
+ for (const event of opened.held) forward(event);
356
+ if (opened.source && last?.type !== "error" && last?.type !== "done")
357
+ for (let next = await opened.source.next(); !next.done; next = await opened.source.next())
358
+ forward(next.value);
359
+ // A provider stream that stops without a terminal event would leave omp waiting forever.
360
+ if (last?.type !== "done" && last?.type !== "error")
361
+ forward({
362
+ type: "error",
363
+ reason: "error",
364
+ error: failure(real, "the model's stream ended without a reply"),
365
+ });
366
+
367
+ if (!shared.enabled || !last) return;
368
+ const ended = last as AssistantMessageEvent;
369
+ if (ended.type === "done" && ended.reason === "toolUse") return;
370
+ const message =
371
+ ended.type === "done" ? ended.message : ended.type === "error" ? ended.error : undefined;
372
+ if (!message) return;
373
+ void post("complete", {
374
+ session,
375
+ turnId: safeId(turn.turnId),
376
+ reason:
377
+ ended.type === "done"
378
+ ? "answer"
379
+ : ended.type === "error" && ended.reason === "aborted"
380
+ ? "aborted"
381
+ : "error",
382
+ model: safeId(modelId(real)),
383
+ usage: {
384
+ inputTokens: message.usage.input + message.usage.cacheRead + message.usage.cacheWrite,
385
+ outputTokens: message.usage.output,
386
+ },
387
+ }).catch(() => {});
388
+ }
389
+
390
+ register();
391
+
392
+ pi.on("session_start", async (_event, c) => {
393
+ // Subagents share the main session's routing server, models and context; only the main agent sets them.
394
+ if (c.agent.kind !== "main") return;
395
+ shared.ctx = c;
396
+ shared.notice = undefined;
397
+ shared.noticed = false;
398
+ show(WAITING);
399
+ if (!existsSync(DISCLOSED)) {
400
+ c.ui.notify(DISCLOSURE, "info");
401
+ try {
402
+ writeFileSync(DISCLOSED, "");
403
+ } catch {
404
+ // A read-only install shows it each session rather than never.
405
+ }
406
+ }
407
+ keepServer(c);
408
+ await refresh(c);
409
+ c.setInterval(() => void refresh(c), POLL_MS);
410
+ });
411
+ pi.on("session_switch", (_event, c) => {
412
+ if (c.agent.kind !== "main") return;
413
+ shared.ctx = c;
414
+ shared.notice = undefined;
415
+ shared.noticed = false;
416
+ });
417
+ // Cleared by the next step, which tells the router the window was rewritten.
418
+ pi.on("session_compact", (_event, c) => {
419
+ if (c.agent.kind === "main") shared.compacted = true;
420
+ });
421
+
422
+ pi.registerCommand("bizzy", {
423
+ description: "Bizzy Auto routing: on, off, or status",
424
+ handler: async (args, c) => {
425
+ const action = args.trim() || "status";
426
+ if (action === "off") shared.enabled = false;
427
+ else if (action === "on") shared.enabled = true;
428
+ else if (action !== "status") return c.ui.notify("Usage: /bizzy [on|off|status]", "warning");
429
+ if (action !== "status") show(shared.enabled ? WAITING : "Bizzy Auto off");
430
+ c.ui.notify([shared.status, shared.notice, DISCLOSURE].filter(Boolean).join("\n"), "info");
431
+ },
432
+ });
433
+ }
@@ -0,0 +1,164 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /** An omp message, read loosely: only the fields routing needs. */
4
+ export interface OmpMessage {
5
+ role: string;
6
+ content?: unknown;
7
+ toolCallId?: string;
8
+ isError?: boolean;
9
+ }
10
+
11
+ /** The part of an omp model the adapter reads. */
12
+ export interface TierModel {
13
+ provider: string;
14
+ id: string;
15
+ /** Null when omp doesn't know the limit. */
16
+ contextWindow: number | null;
17
+ maxTokens: number | null;
18
+ input: readonly string[];
19
+ reasoning: boolean;
20
+ }
21
+
22
+ /** A Messages API message as `/v1/harness/:harness/step` reads it. */
23
+ export interface ApiMessage {
24
+ role: "assistant" | "user";
25
+ content: Record<string, unknown>[];
26
+ }
27
+
28
+ const WINDOW = 24;
29
+ const MAX_RESULT = 4000;
30
+ const MAX_PROMPT = 8000;
31
+ // omp's own nudges (idle retries, todos, plan mode, rule violations) ride in user messages; they aren't the prompt.
32
+ const REMINDER = /<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/g;
33
+ // Routing serves the user's real models; the adapter's own provider is never one of them.
34
+ const OWN_PROVIDER = "bizzy";
35
+ // The routing API's id pattern; a model whose id it would refuse is left out rather than refusing the whole list.
36
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
37
+
38
+ // Loosely read: tool arguments and result text are the model's, so nothing here is trusted to be shaped.
39
+ interface Block {
40
+ type?: string;
41
+ text?: unknown;
42
+ id?: unknown;
43
+ name?: unknown;
44
+ arguments?: { command?: unknown };
45
+ }
46
+
47
+ const blocks = (content: unknown): Block[] => (Array.isArray(content) ? (content as Block[]) : []);
48
+ const textOf = (content: unknown) =>
49
+ typeof content === "string"
50
+ ? content
51
+ : blocks(content)
52
+ .map((block) =>
53
+ block?.type === "text" && typeof block.text === "string" ? block.text : "",
54
+ )
55
+ .join("\n");
56
+
57
+ export const modelId = (model: { provider: string; id: string }) => `${model.provider}/${model.id}`;
58
+
59
+ /** Besides the prompt `turnOf` reads for Jev, only tool activity leaves omp: tool names, shell commands and capped results. */
60
+ export function routingWindow(messages: readonly OmpMessage[]): ApiMessage[] {
61
+ return messages.slice(-WINDOW).flatMap((message): ApiMessage[] => {
62
+ if (message.role === "assistant") {
63
+ const content = blocks(message.content).flatMap((block) =>
64
+ block?.type === "toolCall"
65
+ ? [
66
+ {
67
+ type: "tool_use",
68
+ id: block.id,
69
+ name: block.name,
70
+ input:
71
+ typeof block.arguments?.command === "string"
72
+ ? { command: block.arguments.command }
73
+ : {},
74
+ },
75
+ ]
76
+ : [],
77
+ );
78
+ return content.length ? [{ role: "assistant", content }] : [];
79
+ }
80
+ if (message.role === "toolResult")
81
+ return [
82
+ {
83
+ role: "user",
84
+ content: [
85
+ {
86
+ type: "tool_result",
87
+ tool_use_id: message.toolCallId,
88
+ content: textOf(message.content).slice(0, MAX_RESULT),
89
+ is_error: message.isError === true,
90
+ },
91
+ ],
92
+ },
93
+ ];
94
+ return [];
95
+ });
96
+ }
97
+
98
+ /**
99
+ * The turn's id is stable across its steps and changes with the next prompt; omp passes no turn id of its own. On the
100
+ * turn's first step it carries the user's message, without omp's reminders: what Jev reads.
101
+ */
102
+ export function turnOf(messages: readonly OmpMessage[]) {
103
+ const last = messages.map((message) => message.role).lastIndexOf("user");
104
+ const text = last < 0 ? "" : textOf(messages[last]!.content);
105
+ const hash = createHash("sha256").update(text).digest("hex").slice(0, 8);
106
+ const index = messages.slice(last + 1).filter((message) => message.role === "assistant").length;
107
+ const prompt = index === 0 ? text.replace(REMINDER, "").trim().slice(0, MAX_PROMPT) : "";
108
+ return {
109
+ turnId: `t${Math.max(last, 0)}-${hash}`,
110
+ index,
111
+ depth: messages.filter((message) => message.role === "assistant").length,
112
+ ...(prompt ? { prompt } : {}),
113
+ };
114
+ }
115
+
116
+ /** A real model, or undefined for none or for `bizzy/auto` itself. */
117
+ export const realModel = <M extends { provider: string }>(model: M | undefined) =>
118
+ model && model.provider !== OWN_PROVIDER ? model : undefined;
119
+
120
+ /**
121
+ * The models routing may serve: every real one, except those with a known context window or output limit below
122
+ * `floor`'s (the `@default` model), so omp's budgets for `bizzy/auto` hold on whatever it serves.
123
+ */
124
+ export function candidatesFor<M extends TierModel>(
125
+ models: readonly M[],
126
+ floor: M | undefined,
127
+ ): M[] {
128
+ const below = (limit: number | null, least: number | null | undefined) =>
129
+ limit !== null && least != null && limit < least;
130
+ return models.filter(
131
+ (model) =>
132
+ realModel(model) &&
133
+ SAFE_ID.test(modelId(model)) &&
134
+ !below(model.contextWindow, floor?.contextWindow) &&
135
+ !below(model.maxTokens, floor?.maxTokens),
136
+ );
137
+ }
138
+
139
+ // What bizzy/auto advertises when neither pick states a limit.
140
+ const UNKNOWN_LIMITS = { contextWindow: 128_000, maxTokens: 16_000 };
141
+
142
+ /** The smaller of the limits that are known; with neither known, the conservative default. */
143
+ const smaller = (a: number | null, b: number | null, fallback: number) =>
144
+ a === null ? (b ?? fallback) : b === null ? a : Math.min(a, b);
145
+
146
+ /** What `bizzy/auto` advertises: limits that hold on either pick, so omp's budgets and compaction stay safe. */
147
+ export function autoMetadata(efficient: TierModel, capable: TierModel) {
148
+ return {
149
+ contextWindow: smaller(
150
+ efficient.contextWindow,
151
+ capable.contextWindow,
152
+ UNKNOWN_LIMITS.contextWindow,
153
+ ),
154
+ maxTokens: smaller(efficient.maxTokens, capable.maxTokens, UNKNOWN_LIMITS.maxTokens),
155
+ input: efficient.input.filter((kind) => capable.input.includes(kind)),
156
+ reasoning: efficient.reasoning && capable.reasoning,
157
+ };
158
+ }
159
+
160
+ /** A refusal (unknown model, no permission) skips the model for ten minutes; anything else only briefly. */
161
+ export const isTransient = (error: unknown) =>
162
+ !/model|not.?found|404|permission|403/i.test(
163
+ error instanceof Error ? error.message : String(error ?? ""),
164
+ );