@blockrun/franklin 3.46.0 → 3.48.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.
@@ -6,8 +6,9 @@ import readline from 'node:readline';
6
6
  import chalk from 'chalk';
7
7
  import { getGatewayModels } from '../gateway-models.js';
8
8
  import { FREE_DEFAULT_MODEL } from '../free-models.js';
9
+ import { getModelCatalog, onModelCatalogChange } from '../model-catalog.js';
9
10
  // ─── Model Shortcuts (same as proxy) ───────────────────────────────────────
10
- export const MODEL_SHORTCUTS = {
11
+ const LEGACY_SHORTCUTS = {
11
12
  // Routing profiles — Auto is the only profile surfaced in the picker.
12
13
  // `eco` / `premium` were retired 2026-05-03 (V4 Pro launch made Auto cheap
13
14
  // enough that separate profiles for "cheap" and "best" were redundant).
@@ -27,6 +28,11 @@ export const MODEL_SHORTCUTS = {
27
28
  'sonnet-4.5': 'anthropic/claude-sonnet-4.5',
28
29
  opus: 'anthropic/claude-opus-5',
29
30
  'opus-5': 'anthropic/claude-opus-5',
31
+ // 2026-10 additions — explicit version pins only. The bare `opus` /
32
+ // `sonnet` / `fable` / `claude` aliases above are deliberately NOT moved.
33
+ 'opus-5.5': 'anthropic/claude-opus-5.5',
34
+ 'sonnet-5.5': 'anthropic/claude-sonnet-5.5',
35
+ 'fable-5.1': 'anthropic/claude-fable-5.1',
30
36
  'opus-4.8': 'anthropic/claude-opus-4.8',
31
37
  'opus-4.7': 'anthropic/claude-opus-4.7',
32
38
  // Hidden from /v1/models since 2026-08, still served (probed 2026-08-29).
@@ -40,13 +46,18 @@ export const MODEL_SHORTCUTS = {
40
46
  gpt5: 'openai/gpt-5.6-sol',
41
47
  'gpt-5': 'openai/gpt-5.6-sol',
42
48
  'gpt-5.6': 'openai/gpt-5.6-sol',
49
+ // GPT-6 family + GPT-5.1 (2026-10) — explicit pins; `gpt` is NOT moved.
50
+ 'gpt-6-astra': 'openai/gpt-6-astra',
51
+ 'gpt-6-sol': 'openai/gpt-6-sol',
52
+ 'gpt-6-luna': 'openai/gpt-6-luna',
53
+ 'gpt-5.1': 'openai/gpt-5.1',
43
54
  'gpt-5.6-sol': 'openai/gpt-5.6-sol',
44
55
  'gpt-5.6-terra': 'openai/gpt-5.6-terra',
45
56
  'gpt-5.6-luna': 'openai/gpt-5.6-luna',
46
57
  // GPT-5.6 pro reasoning tier (gateway, 2026-08). Same base models with pro
47
- // reasoning mode on: Sol Pro matches Sol at $5/$30, while Terra Pro ($1/$6)
48
- // and Luna Pro ($0.1/$0.6) come in UNDER their own base tiers — so the pro
49
- // ids are the better pick for anything reasoning-shaped. `gpt` stays pinned
58
+ // reasoning mode on, each at its base tier's price (Sol Pro $4/$20, Terra
59
+ // Pro $2/$12, Luna Pro $0.2/$1.2 — live 2026-10-02) — so the pro ids are the
60
+ // better pick for anything reasoning-shaped. `gpt` stays pinned
50
61
  // to Sol: bare aliases track the gateway's flagship, not the cheapest
51
62
  // sibling.
52
63
  'gpt-5.6-sol-pro': 'openai/gpt-5.6-sol-pro',
@@ -118,6 +129,9 @@ export const MODEL_SHORTCUTS = {
118
129
  // hidden on the gateway; explicit IDs still resolve.)
119
130
  grok: 'xai/grok-4.5',
120
131
  'grok-4.5': 'xai/grok-4.5',
132
+ // Grok 4.7 / 4.6 (2026-10) — explicit pins; `grok` is NOT moved.
133
+ 'grok-4.7': 'xai/grok-4.7',
134
+ 'grok-4.6': 'xai/grok-4.6',
121
135
  'grok-4.3': 'xai/grok-4.3',
122
136
  'grok-build': 'xai/grok-build-0.1',
123
137
  // grok-3 / grok-4-0709 / the grok-4-1-fast pair are hidden from
@@ -132,7 +146,7 @@ export const MODEL_SHORTCUTS = {
132
146
  // Flash modes upstream); free tier routes through nvidia/*.
133
147
  deepseek: 'deepseek/deepseek-chat', // V4 Flash Chat (paid, $0.20/$0.40)
134
148
  r1: 'deepseek/deepseek-reasoner', // V4 Flash Reasoner (paid)
135
- // V4 Pro: paid flagship, 1.6T MoE / 49B active, 1M ctx, 75% launch promo.
149
+ // V4 Pro: paid flagship, 1.6T MoE / 49B active, 1M ctx, $1.32/$3.96 (live 2026-10-02).
136
150
  'deepseek-v4-pro': 'deepseek/deepseek-v4-pro',
137
151
  'dsv4-pro': 'deepseek/deepseek-v4-pro',
138
152
  'v4-pro': 'deepseek/deepseek-v4-pro',
@@ -281,7 +295,7 @@ export function resolveModelStrict(input) {
281
295
  }
282
296
  const lower = trimmed.toLowerCase();
283
297
  if (Object.prototype.hasOwnProperty.call(MODEL_SHORTCUTS, lower)) {
284
- return { ok: true, id: MODEL_SHORTCUTS[lower], viaShortcut: true };
298
+ return { ok: true, id: MODEL_SHORTCUTS[lower], viaShortcut: MODEL_SHORTCUTS[lower] !== trimmed };
285
299
  }
286
300
  if (trimmed.includes('/')) {
287
301
  return { ok: true, id: trimmed, viaShortcut: false };
@@ -331,121 +345,37 @@ const PROVIDER_LABELS = {
331
345
  * (pickModel() below) import from this array. To add or remove models,
332
346
  * edit this one place.
333
347
  */
334
- export const PICKER_CATEGORIES = [
335
- {
336
- category: '🧠 Smart routing (auto-pick)',
337
- models: [
338
- // Auto is the only routing profile surfaced in the picker. Eco and
339
- // Premium are kept as shortcut aliases (`eco`, `premium`) and resolve
340
- // through the router for back-compat with older configs/sessions, but
341
- // they're hidden from new users — Auto already covers the cheap end
342
- // (V4 Pro at $0.435/$0.87 for SIMPLE/MEDIUM) and the quality end (Opus
343
- // for COMPLEX), so a separate Eco/Premium picker entry just adds
344
- // choice paralysis without distinct value.
345
- { id: 'blockrun/auto', shortcut: 'auto', label: 'Auto', price: 'routed' },
346
- ],
347
- },
348
- {
349
- // Picker trim (v3.9.3): hide superseded / awkward-middle / niche-premium
350
- // entries to bring choice paralysis down. Their shortcuts (`opus-4.6`,
351
- // `gpt-5.4`, `gpt-5.4-pro`, `grok`, `o1`, `o4`, `nano`) all stay live in
352
- // MODEL_SHORTCUTS, so muscle memory keeps working — they just aren't
353
- // listed in the visible picker. Same pattern v3.9.0 used to retire dead
354
- // free-tier entries and v3.9.2 used to retire Kimi K2.5.
355
- category: '✨ Premium frontier',
356
- models: [
357
- { id: 'anthropic/claude-fable-5', shortcut: 'fable', label: 'Claude Fable 5', price: '$10/$50' },
358
- // Opus 5 supersedes 4.8 at the same $5/$25 — 4.8 drops out of the visible
359
- // list (its `opus-4.8` shortcut stays live) rather than sitting next to a
360
- // strictly-better entry at an identical price.
361
- { id: 'anthropic/claude-opus-5', shortcut: 'opus', label: 'Claude Opus 5', price: '$5/$25', highlight: true },
362
- { id: 'anthropic/claude-sonnet-5', shortcut: 'sonnet', label: 'Claude Sonnet 5', price: '$3/$15' },
363
- { id: 'qwen/qwen3.7-max', shortcut: 'qwen-max', label: 'Qwen3.7 Max', price: '$1.475/$4.425', highlight: true },
364
- { id: 'openai/gpt-5.6-sol', shortcut: 'gpt', label: 'GPT-5.6 Sol', price: '$5/$30', highlight: true },
365
- // Gemini 2.5 Pro's row retired here the same way Opus 4.8's did: a
366
- // superseded sibling listed directly under its successor is choice
367
- // paralysis, not choice. `gemini-2.5` still resolves to it.
368
- { id: 'google/gemini-3.1-pro', shortcut: 'gemini', label: 'Gemini 3.1 Pro', price: '$2/$12' },
369
- { id: 'xai/grok-4.5', shortcut: 'grok', label: 'Grok 4.5', price: '$2/$6' },
370
- // Kimi K3 (2026-07): 2.8T open MoE, 1M context, multimodal + reasoning.
371
- // Replaced the budget K2.7 line — now premium-priced ($3/$15).
372
- { id: 'moonshot/kimi-k3', shortcut: 'kimi', label: 'Kimi K3', price: '$3/$15' },
373
- ],
374
- },
375
- {
376
- category: '🔬 Reasoning',
377
- models: [
378
- { id: 'openai/o3', shortcut: 'o3', label: 'O3', price: '$2/$8' },
379
- { id: 'openai/gpt-5.3-codex', shortcut: 'codex', label: 'GPT-5.3 Codex', price: '$1.75/$14' },
380
- // V4 Pro: the 75% launch promo became DeepSeek's permanent list price
381
- // after 2026-05-31. 1M context, 1.6T MoE → punches up to GPT-5.5/Opus
382
- // on hard tasks at <1/10 the price.
383
- { id: 'deepseek/deepseek-v4-pro', shortcut: 'deepseek-v4-pro', label: 'DeepSeek V4 Pro', price: '$0.435/$0.87', highlight: true },
384
- { id: 'deepseek/deepseek-reasoner', shortcut: 'r1', label: 'DeepSeek V4 Flash R.', price: '$0.2/$0.4' },
385
- // Terra Pro took the row grok-4-1-fast-reasoning used to hold: the xAI
386
- // fast family is hidden from /v1/models, so reconcilePicker dropped that
387
- // row on every live render anyway (`grok-fast` still resolves). Terra
388
- // Pro is GPT-5.6 Terra with pro reasoning on, at HALF Terra's price.
389
- { id: 'openai/gpt-5.6-terra-pro', shortcut: 'terra-pro', label: 'GPT-5.6 Terra Pro', price: '$1/$6', highlight: true },
390
- // GLM-5.3: Z.AI's flagship — 1M context, always-on reasoning, strong on
391
- // long-horizon coding. `glm`/`glm5` shortcuts pin it.
392
- { id: 'zai/glm-5.3', shortcut: 'glm-5.3', label: 'GLM-5.3', price: '$1.4/$4.4' },
393
- ],
394
- },
395
- {
396
- category: '💰 Budget',
397
- models: [
398
- { id: 'anthropic/claude-haiku-4.5', shortcut: 'haiku', label: 'Claude Haiku 4.5', price: '$1/$5' },
399
- { id: 'openai/gpt-5-mini', shortcut: 'mini', label: 'GPT-5 Mini', price: '$0.25/$2' },
400
- // GLM-5.3 Flash took Gemini 2.5 Flash's row 2026-08-29: half the price,
401
- // the same 1M context and vision, plus reasoning. `gemini-2.5-flash`
402
- // still resolves — hide the row, keep the shortcut.
403
- { id: 'zai/glm-5.3-flash', shortcut: 'glm-flash', label: 'GLM-5.3 Flash', price: '$0.15/$0.5' },
404
- // Re-aliased to V4 Flash Chat upstream — context 1M, price 30% lower.
405
- { id: 'deepseek/deepseek-chat', shortcut: 'deepseek', label: 'DeepSeek V4 Flash Chat', price: '$0.14/$0.28' },
406
- // Cheapest paid model on the gateway, and it still carries 1M context
407
- // with reasoning — the budget slot GLM-5 used to hold (its flat-rate
408
- // promo ended 2026-06-06 and it now lists at $1/$3.2, no longer a budget
409
- // number; the `glm-5` shortcut stays live).
410
- { id: 'qwen/qwen3.7-flash', shortcut: 'qwen-flash', label: 'Qwen3.7 Flash', price: '$0.03/$0.13', highlight: true },
411
- // Minimax M2.7 hidden to make room for V4 Pro in Reasoning + V4 Flash
412
- // (free) without exceeding the picker's 24-entry cap. Shortcut `minimax`
413
- // still resolves to it.
414
- ],
415
- },
416
- {
417
- category: '🆓 Free (no USDC needed)',
418
- models: [
419
- // Nemotron Nano 9B leads: it's what the `free` shortcut + free routing
420
- // profile resolve to, promoted 2026-08-12 when qwen3-next-80b-a3b-instruct
421
- // hit NVIDIA's EOL (410). All rows are $0 — the free tier never falls
422
- // back to paid.
423
- //
424
- // Caveat worth knowing before editing this list: only the FIRST row is
425
- // available on both chains. The Solana gateway lists exactly one free
426
- // model and 400s ("Unknown model") on the other three, which are
427
- // Base-only as of the 2026-08-30 rotation. That is why `free` — and
428
- // every legacy free alias — points at the chain-safe id, and why the
429
- // ROUTER upgrades to the 550B at runtime from the live catalog rather
430
- // than from this list (see src/free-models.ts, freeChain).
431
- //
432
- // The rows are still worth showing on both chains: the picker hydrates
433
- // against the gateway catalog, and a user who pins a Base-only id on
434
- // Solana gets a clear "Unknown model" rather than a silent wrong model.
435
- //
436
- // Deliberately absent (NOT quarantined — QUARANTINED_FREE_MODELS is
437
- // empty): nemotron-3.5-lightning is merely slow, cohere/north-mini-code
438
- // is a routable chain rung with no picker row, and llama-3.2-11b-vision
439
- // is vision-only. Reasons per id live in src/free-models.ts.
440
- { id: FREE_DEFAULT_MODEL, shortcut: 'free', label: 'Nemotron 3 Nano Omni', price: 'FREE', highlight: true },
441
- { id: 'nvidia/nemotron-3-ultra-550b', shortcut: 'ultra-550b', label: 'Nemotron 3 Ultra 550B', price: 'FREE' },
442
- { id: 'nvidia/nemotron-3-nano-30b', shortcut: 'nano-30b', label: 'Nemotron 3 Nano 30B', price: 'FREE' },
443
- { id: 'poolside/laguna-xs-2.1', shortcut: 'laguna', label: 'Laguna XS 2.1', price: 'FREE' },
444
- ],
445
- },
446
- ];
447
- /** Flat list of all picker models (for index-based navigation). */
448
- export const PICKER_MODELS_FLAT = PICKER_CATEGORIES.flatMap(c => c.models);
348
+ export const MODEL_SHORTCUTS = {};
349
+ export const PICKER_CATEGORIES = [];
350
+ export const PICKER_MODELS_FLAT = [];
351
+ function updateCatalogView(state) {
352
+ for (const key of Object.keys(MODEL_SHORTCUTS))
353
+ delete MODEL_SHORTCUTS[key];
354
+ // Franklin's own aliases win over the shared policy: a remote catalog edit may
355
+ // add new shortcuts, but never retarget one a user already relies on (that
356
+ // would change which model runs, and what it costs, without a release). The
357
+ // same rule keeps every existing free shortcut free.
358
+ Object.assign(MODEL_SHORTCUTS, state.shortcuts, LEGACY_SHORTCUTS);
359
+ const categories = [{
360
+ category: '🧠 Smart routing (auto-pick)',
361
+ models: [{ id: 'blockrun/auto', shortcut: 'auto', label: 'Auto', price: 'routed' }],
362
+ }, ...state.groups.filter(group => group.id !== 'other').map(group => ({
363
+ category: group.title,
364
+ models: group.models.map(model => ({
365
+ id: model.id, label: model.name,
366
+ // Shortest alias reads best in the picker column (`opus`, not `opus-5`).
367
+ shortcut: Object.entries(MODEL_SHORTCUTS)
368
+ .filter(([key, target]) => target === model.id && !key.includes('/'))
369
+ .map(([key]) => key)
370
+ .reduce((best, key) => !best || key.length < best.length ? key : best, undefined) ?? model.id,
371
+ price: formatPrice(model),
372
+ })),
373
+ }))];
374
+ PICKER_CATEGORIES.splice(0, PICKER_CATEGORIES.length, ...categories);
375
+ PICKER_MODELS_FLAT.splice(0, PICKER_MODELS_FLAT.length, ...categories.flatMap(c => c.models));
376
+ }
377
+ updateCatalogView(getModelCatalog());
378
+ onModelCatalogChange(updateCatalogView);
449
379
  // ─── Live hydration against the gateway catalog ────────────────────────────
450
380
  /**
451
381
  * Synthetic ids that are Franklin concepts, not gateway models (`blockrun/auto`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.46.0",
3
+ "version": "3.48.0",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -38,13 +38,14 @@
38
38
  "desktop:package:win": "npm run dist:win --workspace @blockrun/franklin-desktop",
39
39
  "dev": "tsc --watch",
40
40
  "start": "node dist/index.js",
41
- "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs",
41
+ "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs",
42
42
  "test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
43
43
  "e2e:polymarket:readonly": "npm run build && node scripts/polymarket-e2e-readonly.mjs",
44
44
  "test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",
45
45
  "test:all": "npm run test && npm run test:e2e",
46
46
  "test:watch": "node --test --watch test/local.mjs test/skills.local.mjs test/exa.local.mjs test/audit-batch.local.mjs",
47
- "test:e2e:watch": "node --test --watch test/e2e.mjs"
47
+ "test:e2e:watch": "node --test --watch test/e2e.mjs",
48
+ "test:catalog": "npm run build && node --test test/model-catalog.local.mjs"
48
49
  },
49
50
  "keywords": [
50
51
  "franklin",
@@ -98,7 +99,8 @@
98
99
  "react": "^19.2.4",
99
100
  "sharp": "^0.35.3",
100
101
  "viem": "^2.48.1",
101
- "ws": "^8.21.1"
102
+ "ws": "^8.21.1",
103
+ "@blockrun/model-catalog": "https://codeload.github.com/BlockRunAI/model-catalog/tar.gz/465c45941fb8ea9d6858fe8402abc8ba8934be90"
102
104
  },
103
105
  "devDependencies": {
104
106
  "@types/node": "^26.1.1",
@@ -1,17 +0,0 @@
1
- /** Shared account authentication for Franklin's direct gateway requests. */
2
- export declare const ACCOUNT_PORTAL = "https://user.blockrun.ai";
3
- export declare function accountMode(): boolean;
4
- export declare function accountBaseURL(): string;
5
- export declare function accountStatus(): {
6
- authMode: string;
7
- address: string;
8
- chain: string;
9
- balance: null;
10
- balanceUsd: undefined;
11
- portalUrl: string;
12
- creditsUrl: string;
13
- };
14
- export declare function validateAccountConfig(): void;
15
- export declare function gatewayFetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
16
- /** Poll direct API jobs with an abortable deadline; never resubmit a job. */
17
- export declare function pollAccountJob(response: Response, signal?: AbortSignal, intervalMs?: number): Promise<Response>;
@@ -1,105 +0,0 @@
1
- /** Shared account authentication for Franklin's direct gateway requests. */
2
- export const ACCOUNT_PORTAL = 'https://user.blockrun.ai';
3
- export function accountMode() { return process.env.BLOCKRUN_API_KEY !== undefined; }
4
- export function accountBaseURL() {
5
- const raw = (process.env.BLOCKRUN_API_BASE_URL || 'https://api.blockrun.ai').replace(/\/+$/, '').replace(/\/v1$/, '');
6
- const url = new URL(raw);
7
- if (url.username || url.password || url.search || url.hash ||
8
- (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {
9
- throw new Error('BLOCKRUN_API_BASE_URL requires HTTPS (except localhost) and no credentials, query or fragment.');
10
- }
11
- return raw;
12
- }
13
- export function accountStatus() {
14
- return { authMode: 'api-key', address: '', chain: 'account', balance: null, balanceUsd: undefined, portalUrl: ACCOUNT_PORTAL, creditsUrl: `${ACCOUNT_PORTAL}/dashboard/credits` };
15
- }
16
- function key() {
17
- const value = process.env.BLOCKRUN_API_KEY?.trim() || '';
18
- if (!/^brk_[A-Za-z0-9_-]+$/.test(value))
19
- throw new Error(`Invalid BLOCKRUN_API_KEY. Create a key at ${ACCOUNT_PORTAL}/dashboard/keys.`);
20
- return value;
21
- }
22
- export function validateAccountConfig() { if (accountMode()) {
23
- key();
24
- accountBaseURL();
25
- } }
26
- function accountRequestURL(input) {
27
- const base = new URL(accountBaseURL());
28
- const source = new URL(input instanceof Request ? input.url : String(input), `${base}/`);
29
- const gateways = new Set(['https://blockrun.ai', 'https://sol.blockrun.ai', 'https://api.blockrun.ai', base.origin]);
30
- if (!gateways.has(source.origin) || source.username || source.password)
31
- throw new Error('Refusing to forward an account key to an unknown gateway or polling origin.');
32
- source.protocol = base.protocol;
33
- source.host = base.host;
34
- source.pathname = source.pathname.replace(/^\/api\/v1\//, '/v1/');
35
- return source;
36
- }
37
- // Caller receives the actual HTTP status, so existing stream parsers and proxy
38
- // clients keep their error semantics. No x402 branch may run in account mode.
39
- export async function gatewayFetch(input, init) {
40
- if (!accountMode())
41
- return globalThis.fetch(input, init);
42
- const credential = key();
43
- const url = accountRequestURL(input);
44
- const request = input instanceof Request ? input : undefined;
45
- const headers = new Headers(init?.headers ?? request?.headers);
46
- for (const name of [...headers.keys()])
47
- if (/payment/i.test(name) || /^(x-api-key|authorization)$/i.test(name))
48
- headers.delete(name);
49
- headers.set('authorization', `Bearer ${credential}`);
50
- const response = await globalThis.fetch(request ? new Request(url, request) : url, { ...init, headers, redirect: 'error' });
51
- if (response.ok)
52
- return response;
53
- let body;
54
- try {
55
- body = await response.json();
56
- }
57
- catch {
58
- body = {};
59
- }
60
- const outer = body && typeof body === 'object' ? body : {};
61
- const detail = outer.error && typeof outer.error === 'object' ? outer.error : outer;
62
- const safe = Object.fromEntries(['message', 'code', 'type', 'param'].flatMap(name => typeof detail[name] === 'string' ? [[name, detail[name].split(credential).join('[REDACTED]')]] : []));
63
- if (response.status === 402)
64
- safe.message = `BlockRun account credits exhausted (402). Top up at ${ACCOUNT_PORTAL}/dashboard/credits.`;
65
- if (response.status === 401)
66
- safe.message = `BlockRun account authentication failed (401). Check your key at ${ACCOUNT_PORTAL}/dashboard/keys.`;
67
- const safeHeaders = new Headers({ 'content-type': 'application/json' });
68
- const retryAfter = response.headers.get('retry-after');
69
- if (retryAfter)
70
- safeHeaders.set('retry-after', retryAfter);
71
- return new Response(JSON.stringify({ error: safe }), { status: response.status, headers: safeHeaders });
72
- }
73
- /** Poll direct API jobs with an abortable deadline; never resubmit a job. */
74
- export async function pollAccountJob(response, signal, intervalMs = 2000) {
75
- if (!accountMode() || response.status !== 202)
76
- return response;
77
- const initial = await response.clone().json();
78
- if (!initial.poll_url)
79
- throw new Error('Account async response missing poll_url');
80
- const endpoint = accountRequestURL(initial.poll_url);
81
- const deadline = AbortSignal.timeout(15 * 60_000);
82
- const abort = signal ? AbortSignal.any([signal, deadline]) : deadline;
83
- while (!abort.aborted) {
84
- await new Promise((resolve, reject) => {
85
- const onAbort = () => { clearTimeout(timer); reject(abort.reason); };
86
- const timer = setTimeout(() => { abort.removeEventListener('abort', onAbort); resolve(); }, intervalMs);
87
- abort.addEventListener('abort', onAbort, { once: true });
88
- if (abort.aborted)
89
- onAbort();
90
- });
91
- const polled = await gatewayFetch(endpoint, { signal: abort });
92
- if ([502, 503, 504, 522, 524].includes(polled.status)) {
93
- await polled.body?.cancel();
94
- continue;
95
- }
96
- if (!polled.ok)
97
- return polled;
98
- const data = await polled.clone().json();
99
- if (data.status === 'completed')
100
- return polled;
101
- if (['failed', 'cancelled', 'canceled'].includes(data.status || ''))
102
- throw new Error('Account job failed or was cancelled');
103
- }
104
- throw new Error('Account job polling stopped; check job before resubmitting');
105
- }