@blockrun/franklin 3.46.0 → 3.47.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 +26 -7
- package/dist/commands/start.js +4 -0
- package/dist/free-models.js +2 -1
- package/dist/gateway-models.js +34 -66
- package/dist/model-catalog.d.ts +10 -0
- package/dist/model-catalog.js +77 -0
- package/dist/pricing.d.ts +2 -6
- package/dist/pricing.js +16 -3
- package/dist/router/vision.js +9 -1
- package/dist/ui/model-picker.d.ts +1 -2
- package/dist/ui/model-picker.js +34 -117
- package/package.json +6 -4
- package/dist/payments/account.d.ts +0 -17
- package/dist/payments/account.js +0 -105
package/README.md
CHANGED
|
@@ -382,7 +382,7 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
|
|
|
382
382
|
|
|
383
383
|
## Smart Router
|
|
384
384
|
|
|
385
|
-
**<!-- br:models.chatVisible -->
|
|
385
|
+
**<!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
|
|
386
386
|
|
|
387
387
|
You don't pick models. Franklin picks for you.
|
|
388
388
|
|
|
@@ -463,7 +463,7 @@ No email. No phone. No KYC. Your Solana or Base address is your account — port
|
|
|
463
463
|
| Writes code | ✅ | ✅ | ⚠️ | ✅ |
|
|
464
464
|
| **Spends money for you** | ❌ | ❌ | ❌ | ✅ **USDC wallet, x402** |
|
|
465
465
|
| **Buys data + APIs + images + search** | ❌ | ❌ | ❌ | ✅ **55+ APIs, one wallet** |
|
|
466
|
-
| Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->
|
|
466
|
+
| Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models** |
|
|
467
467
|
| Pricing model | Subscription | Subscription | Subscription | **YOPO** — per outcome, USDC |
|
|
468
468
|
| Monthly fee | $20–$200 | $20–$40 | $20+ | **$0** |
|
|
469
469
|
| Rate-limited | Yes | Yes | Yes | No — limited only by wallet |
|
|
@@ -491,14 +491,14 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
|
|
|
491
491
|
**🎨 AI image generation**
|
|
492
492
|
Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
|
|
493
493
|
|
|
494
|
-
**🧠 <!-- br:models.chatVisible -->
|
|
494
|
+
**🧠 <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models via one wallet**
|
|
495
495
|
Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, NVIDIA free tier. One wallet, one interface, automatic fallback.
|
|
496
496
|
|
|
497
497
|
**💳 x402 micropayments (YOPO)**
|
|
498
498
|
HTTP 402 native. Every paid action is a signed USDC micropayment via EIP-712 — non-custodial, your keys never leave your machine. YOPO: you pay only for outcomes.
|
|
499
499
|
|
|
500
500
|
**🧠 Learned model router**
|
|
501
|
-
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->
|
|
501
|
+
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
|
|
502
502
|
|
|
503
503
|
</td>
|
|
504
504
|
<td width="50%" valign="top">
|
|
@@ -554,13 +554,13 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
|
|
|
554
554
|
│ Intent → Smart Router → Tool Use → Spend Control → Result │
|
|
555
555
|
├──────────────────────────────────────────────────────────────┤
|
|
556
556
|
│ Learned Router │
|
|
557
|
-
│ 2M+ requests · <!-- br:models.chatVisible@live -->
|
|
557
|
+
│ 2M+ requests · <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
|
|
558
558
|
├──────────────────────────────────────────────────────────────┤
|
|
559
559
|
│ Agent Loop │
|
|
560
560
|
│ 16 tools · Sessions · Compaction · Pricing · Plugin SDK │
|
|
561
561
|
├──────────────────────────────────────────────────────────────┤
|
|
562
562
|
│ BlockRun Gateway │
|
|
563
|
-
│ <!-- br:models.chatVisible@live -->
|
|
563
|
+
│ <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
|
|
564
564
|
├──────────────────────────────────────────────────────────────┤
|
|
565
565
|
│ x402 Micropayment Protocol │
|
|
566
566
|
│ HTTP 402 · USDC on Solana & Base · signed payment payloads │
|
|
@@ -604,7 +604,7 @@ src/
|
|
|
604
604
|
├── stats/ Usage tracking + insights engine
|
|
605
605
|
├── ui/ Ink-based terminal UI
|
|
606
606
|
├── proxy/ Payment proxy for external tools
|
|
607
|
-
├── router/ Learned model router (<!-- br:models.chatVisible@live -->
|
|
607
|
+
├── router/ Learned model router (<!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models, Elo scoring)
|
|
608
608
|
├── wallet/ Wallet management (Base + Solana)
|
|
609
609
|
├── mcp/ MCP server auto-discovery
|
|
610
610
|
└── commands/ CLI subcommands
|
|
@@ -715,6 +715,25 @@ For the recommended live validation order and failure triage, see [docs/live-e2e
|
|
|
715
715
|
|
|
716
716
|
---
|
|
717
717
|
|
|
718
|
+
## Shared model catalog
|
|
719
|
+
|
|
720
|
+
Franklin uses [BlockRun Model Core](https://github.com/BlockRunAI/model-catalog)
|
|
721
|
+
for model metadata, picker policy and price estimates. The runtime dependency
|
|
722
|
+
is pinned to an immutable commit. On refresh, Franklin reads the public current
|
|
723
|
+
snapshot and the active gateway's catalog, so new models and prices can appear
|
|
724
|
+
without a Franklin release. Base, Solana and API accounts have separate caches.
|
|
725
|
+
|
|
726
|
+
Updates are validated before use. Requests have a four-second deadline each,
|
|
727
|
+
refreshes are cached for five minutes, and failures retain the last valid data
|
|
728
|
+
(or the bundled snapshot on first launch). `BLOCKRUN_MODEL_CATALOG_URL` can
|
|
729
|
+
override the public snapshot URL; an empty value disables remote policy updates.
|
|
730
|
+
`FRANKLIN_CATALOG_OFFLINE=1` uses bundled data without catalog network requests.
|
|
731
|
+
|
|
732
|
+
Existing free shortcuts remain free. Historical explicit IDs and cost records
|
|
733
|
+
remain usable; rolling aliases may select newer models at different prices.
|
|
734
|
+
Payment signing and settlement remain in Franklin and its payment SDK. Auto
|
|
735
|
+
routing's candidate policy remains separate from the shared catalog pilot.
|
|
736
|
+
|
|
718
737
|
## License
|
|
719
738
|
|
|
720
739
|
Apache-2.0. See [LICENSE](LICENSE).
|
package/dist/commands/start.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
|
+
import { refreshModelCatalog } from '../model-catalog.js';
|
|
2
3
|
import fs from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
|
|
@@ -72,6 +73,9 @@ export async function startCommand(options) {
|
|
|
72
73
|
chain = sessMeta.chain;
|
|
73
74
|
}
|
|
74
75
|
}
|
|
76
|
+
// Warm in the background: bundled data already covers startup, and the picker
|
|
77
|
+
// and pricing tables update in place when the refresh lands.
|
|
78
|
+
refreshModelCatalog({ network: chain }).catch(() => { });
|
|
75
79
|
const apiUrl = gatewayBase();
|
|
76
80
|
const config = loadConfig();
|
|
77
81
|
// Resolve model. Priority: explicit --model > resumed session's model > user
|
package/dist/free-models.js
CHANGED
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
* (FREE_POOL_CONTEXT_FLOOR).
|
|
60
60
|
* 4. No free vision — see freeVisionModel().
|
|
61
61
|
*/
|
|
62
|
+
import { getModelCatalog } from './model-catalog.js';
|
|
62
63
|
import { peekGatewayModel } from './gateway-models.js';
|
|
63
64
|
import { FREE_DEFAULT_MODEL, FREE_POOL_CONTEXT_FLOOR, FREE_PREFERENCE_ORDER, } from './free-models.constants.js';
|
|
64
65
|
// Re-exported so every consumer keeps importing from ONE place. The constants
|
|
@@ -356,7 +357,7 @@ export function isFreeModelId(id) {
|
|
|
356
357
|
return true;
|
|
357
358
|
if (!id)
|
|
358
359
|
return false;
|
|
359
|
-
const entry = peekGatewayModel(id);
|
|
360
|
+
const entry = peekGatewayModel(id) ?? getModelCatalog().models.find(model => model.id === id);
|
|
360
361
|
if (entry)
|
|
361
362
|
return entry.billing_mode === 'free';
|
|
362
363
|
if (id in FREE_MODEL_CONTEXT_WINDOWS)
|
package/dist/gateway-models.js
CHANGED
|
@@ -15,17 +15,16 @@
|
|
|
15
15
|
* service fee — the flat-fee estimate over-counts there by ≤$0.001, which
|
|
16
16
|
* is the safe direction for budget tracking).
|
|
17
17
|
*/
|
|
18
|
-
import {
|
|
19
|
-
import { gatewayBase, gatewayHeaders } from './payments/auth-mode.js';
|
|
18
|
+
import { refreshModelCatalog, clearModelCatalogCache, getModelCatalogIdentity } from './model-catalog.js';
|
|
20
19
|
// ─── Cache ──────────────────────────────────────────────────────────────
|
|
21
20
|
const CACHE_TTL_MS = 5 * 60_000; // 5 min — gateway rotates models, but not often
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
let inflight = null;
|
|
21
|
+
const cache = new Map();
|
|
22
|
+
const inflight = new Map();
|
|
25
23
|
/** Test / reset helper. */
|
|
26
24
|
export function clearGatewayModelsCache() {
|
|
27
|
-
cache
|
|
28
|
-
inflight
|
|
25
|
+
cache.clear();
|
|
26
|
+
inflight.clear();
|
|
27
|
+
clearModelCatalogCache();
|
|
29
28
|
}
|
|
30
29
|
/**
|
|
31
30
|
* Synchronous, cache-only lookup. Returns null when the catalog has never been
|
|
@@ -52,25 +51,11 @@ export function clearGatewayModelsCache() {
|
|
|
52
51
|
* Treat this as "better than a blind default", nothing more.
|
|
53
52
|
*/
|
|
54
53
|
export function peekGatewayModel(id) {
|
|
55
|
-
|
|
56
|
-
return null;
|
|
57
|
-
// A catalog fetched for a different chain is not evidence about this one.
|
|
58
|
-
if (cache.chain !== currentChain())
|
|
59
|
-
return null;
|
|
60
|
-
return cache.models.find(m => m.id === id) ?? null;
|
|
61
|
-
}
|
|
62
|
-
/** loadChain() with the throw swallowed — this is a hot, sync path. */
|
|
63
|
-
function currentChain() {
|
|
64
|
-
try {
|
|
65
|
-
return loadChain();
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
return 'base';
|
|
69
|
-
}
|
|
54
|
+
return cache.get(getModelCatalogIdentity())?.models.find(m => m.id === id) ?? null;
|
|
70
55
|
}
|
|
71
56
|
/** Test helper — seed the cache without a network call. */
|
|
72
57
|
export function __primeGatewayModelsCache(models) {
|
|
73
|
-
cache
|
|
58
|
+
cache.set(getModelCatalogIdentity(), { models, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
74
59
|
}
|
|
75
60
|
/**
|
|
76
61
|
* Fire-and-forget catalog warm. Populates the cache so the sync peek above has
|
|
@@ -81,33 +66,13 @@ export function warmGatewayModelsCache() {
|
|
|
81
66
|
}
|
|
82
67
|
// ─── Fetch ──────────────────────────────────────────────────────────────
|
|
83
68
|
async function doFetch() {
|
|
84
|
-
const
|
|
85
|
-
//
|
|
86
|
-
//
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
// typed schema placeholder instead of the data envelope. Documented
|
|
92
|
-
// quirk across other endpoints too.
|
|
93
|
-
const url = `${gatewayBase()}/v1/models?format=json`;
|
|
94
|
-
const ctrl = new AbortController();
|
|
95
|
-
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
|
|
96
|
-
try {
|
|
97
|
-
const res = await fetch(url, {
|
|
98
|
-
signal: ctrl.signal,
|
|
99
|
-
headers: { ...gatewayHeaders(), 'User-Agent': USER_AGENT, Accept: 'application/json' },
|
|
100
|
-
});
|
|
101
|
-
if (!res.ok)
|
|
102
|
-
throw new Error(`Gateway models list returned HTTP ${res.status}`);
|
|
103
|
-
const body = (await res.json());
|
|
104
|
-
if (!Array.isArray(body.data))
|
|
105
|
-
throw new Error('Gateway models list missing data[]');
|
|
106
|
-
return body.data;
|
|
107
|
-
}
|
|
108
|
-
finally {
|
|
109
|
-
clearTimeout(timer);
|
|
110
|
-
}
|
|
69
|
+
const state = await refreshModelCatalog();
|
|
70
|
+
// Bundled rows are not gateway evidence. Surface the failure so callers keep
|
|
71
|
+
// their existing fallbacks (stale cache, static picker) instead of treating
|
|
72
|
+
// the packaged snapshot as a live catalog for five minutes.
|
|
73
|
+
if (state.source !== 'live')
|
|
74
|
+
throw new Error(state.lastError ?? 'Gateway model catalog unavailable');
|
|
75
|
+
return state.models;
|
|
111
76
|
}
|
|
112
77
|
/**
|
|
113
78
|
* Fetch the model catalog, honoring the 5-minute cache. Concurrent callers
|
|
@@ -115,24 +80,27 @@ async function doFetch() {
|
|
|
115
80
|
* the gateway at process start.
|
|
116
81
|
*/
|
|
117
82
|
export async function getGatewayModels() {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
if (
|
|
121
|
-
return
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
83
|
+
const identity = getModelCatalogIdentity();
|
|
84
|
+
const previous = cache.get(identity);
|
|
85
|
+
if (previous && previous.expiresAt > Date.now())
|
|
86
|
+
return previous.models;
|
|
87
|
+
const pending = inflight.get(identity);
|
|
88
|
+
if (pending)
|
|
89
|
+
return pending;
|
|
90
|
+
const request = doFetch().then(models => {
|
|
91
|
+
// A request completing after an account/chain switch only updates its own cache.
|
|
92
|
+
cache.set(identity, { models, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
125
93
|
return models;
|
|
126
|
-
})
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
// rather than break the agent). Only hard-fail cold start.
|
|
130
|
-
if (cache)
|
|
131
|
-
return cache.models;
|
|
94
|
+
}).catch(err => {
|
|
95
|
+
if (previous)
|
|
96
|
+
return previous.models;
|
|
132
97
|
throw err;
|
|
133
|
-
})
|
|
134
|
-
.
|
|
135
|
-
|
|
98
|
+
}).finally(() => {
|
|
99
|
+
if (inflight.get(identity) === request)
|
|
100
|
+
inflight.delete(identity);
|
|
101
|
+
});
|
|
102
|
+
inflight.set(identity, request);
|
|
103
|
+
return request;
|
|
136
104
|
}
|
|
137
105
|
/** Return models filtered to a specific category (e.g. 'image', 'video', 'music'). */
|
|
138
106
|
export async function getModelsByCategory(category) {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Shared model facts and policy; payment credentials stay in Franklin. */
|
|
2
|
+
import { type CatalogState, type Network } from '@blockrun/model-catalog';
|
|
3
|
+
export declare function getModelCatalogIdentity(): string;
|
|
4
|
+
export declare function getModelCatalog(): CatalogState;
|
|
5
|
+
export declare function onModelCatalogChange(listener: (state: CatalogState) => void): () => void;
|
|
6
|
+
export declare function refreshModelCatalog(options?: {
|
|
7
|
+
network?: Network;
|
|
8
|
+
force?: boolean;
|
|
9
|
+
}): Promise<CatalogState>;
|
|
10
|
+
export declare function clearModelCatalogCache(): void;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Shared model facts and policy; payment credentials stay in Franklin. */
|
|
2
|
+
import { createCatalogClient } from '@blockrun/model-catalog';
|
|
3
|
+
import { API_URLS, loadChain, USER_AGENT } from './config.js';
|
|
4
|
+
import { gatewayHeaders, resolvePayMode } from './payments/auth-mode.js';
|
|
5
|
+
const clients = new Map();
|
|
6
|
+
const bundled = new Map();
|
|
7
|
+
function bundledState() {
|
|
8
|
+
const network = sessionNetwork ?? loadChain();
|
|
9
|
+
let state = bundled.get(network);
|
|
10
|
+
if (!state) {
|
|
11
|
+
state = createCatalogClient({ network }).current();
|
|
12
|
+
bundled.set(network, state);
|
|
13
|
+
}
|
|
14
|
+
return state;
|
|
15
|
+
}
|
|
16
|
+
const listeners = new Set();
|
|
17
|
+
let sessionNetwork;
|
|
18
|
+
function activeClient() {
|
|
19
|
+
const mode = resolvePayMode();
|
|
20
|
+
const network = sessionNetwork ?? loadChain();
|
|
21
|
+
const gatewayUrl = `${mode.kind === 'key' ? mode.apiBase : API_URLS[network]}/v1/models?format=json`;
|
|
22
|
+
const catalogUrl = process.env.BLOCKRUN_MODEL_CATALOG_URL
|
|
23
|
+
?? 'https://raw.githubusercontent.com/BlockRunAI/model-catalog/main/dist/snapshot.v1.json';
|
|
24
|
+
// Separate caches for each chain, endpoint and API account; keys never leave memory.
|
|
25
|
+
const identity = JSON.stringify([network, gatewayUrl, catalogUrl, mode.kind === 'key' ? mode.key : '']);
|
|
26
|
+
let client = clients.get(identity);
|
|
27
|
+
if (!client) {
|
|
28
|
+
const headers = { ...gatewayHeaders(mode), 'User-Agent': USER_AGENT };
|
|
29
|
+
client = createCatalogClient({
|
|
30
|
+
network, gatewayUrl, catalogUrl,
|
|
31
|
+
fetch: (url, init) => globalThis.fetch(url, {
|
|
32
|
+
...init,
|
|
33
|
+
// A separately hosted public snapshot must never receive the API key.
|
|
34
|
+
headers: String(url) === gatewayUrl ? { ...init?.headers, ...headers } : init?.headers,
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
clients.set(identity, client);
|
|
38
|
+
}
|
|
39
|
+
return { identity, client };
|
|
40
|
+
}
|
|
41
|
+
export function getModelCatalogIdentity() {
|
|
42
|
+
try {
|
|
43
|
+
return activeClient().identity;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return `unconfigured:${sessionNetwork ?? loadChain()}`;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function getModelCatalog() {
|
|
50
|
+
// Metadata imports precede CLI flag parsing. An invalid saved key must not
|
|
51
|
+
// prevent --help or --wallet from running; request-time refresh still validates auth.
|
|
52
|
+
try {
|
|
53
|
+
return activeClient().client.current();
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return bundledState();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export function onModelCatalogChange(listener) {
|
|
60
|
+
listeners.add(listener);
|
|
61
|
+
return () => { listeners.delete(listener); };
|
|
62
|
+
}
|
|
63
|
+
export async function refreshModelCatalog(options = {}) {
|
|
64
|
+
if (options.network)
|
|
65
|
+
sessionNetwork = options.network;
|
|
66
|
+
const { identity, client } = activeClient();
|
|
67
|
+
const state = process.env.FRANKLIN_CATALOG_OFFLINE === '1'
|
|
68
|
+
? client.current() : await client.refresh({ force: options.force });
|
|
69
|
+
if (identity === activeClient().identity)
|
|
70
|
+
for (const listener of listeners)
|
|
71
|
+
listener(state);
|
|
72
|
+
return state;
|
|
73
|
+
}
|
|
74
|
+
export function clearModelCatalogCache() {
|
|
75
|
+
clients.clear();
|
|
76
|
+
sessionNetwork = undefined;
|
|
77
|
+
}
|
package/dist/pricing.d.ts
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Used by agent loop, proxy server, stats tracker, and router.
|
|
4
|
-
*/
|
|
1
|
+
export declare function hasHistoricalPrice(model: string): boolean;
|
|
2
|
+
/** Gateway prices override historical fallbacks without replacing map identities. */
|
|
5
3
|
export declare const MODEL_PRICING: Record<string, {
|
|
6
4
|
input: number;
|
|
7
5
|
output: number;
|
|
8
6
|
perCall?: number;
|
|
9
7
|
}>;
|
|
10
|
-
/** Opus pricing for savings calculations — tracks the current flagship. */
|
|
11
8
|
export declare const OPUS_PRICING: {
|
|
12
9
|
input: number;
|
|
13
10
|
output: number;
|
|
14
|
-
perCall?: number;
|
|
15
11
|
};
|
|
16
12
|
/**
|
|
17
13
|
* Estimate cost in USD for a request.
|
package/dist/pricing.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { getModelCatalog, onModelCatalogChange } from './model-catalog.js';
|
|
1
2
|
/**
|
|
2
3
|
* Single source of truth for model pricing (per 1M tokens).
|
|
3
4
|
* Used by agent loop, proxy server, stats tracker, and router.
|
|
4
5
|
*/
|
|
5
|
-
|
|
6
|
+
const LEGACY_PRICING = {
|
|
6
7
|
// Routing profiles (blended averages). Auto + Free are the only profiles
|
|
7
8
|
// surfaced after the 2026-05-03 collapse; eco/premium were retired and
|
|
8
9
|
// their parser mapping promotes them to Auto upstream of cost estimation.
|
|
@@ -177,8 +178,20 @@ export const MODEL_PRICING = {
|
|
|
177
178
|
'nvidia/kimi-k2.5': { input: 0.55, output: 2.5 },
|
|
178
179
|
'zai/glm-5.1-turbo': { input: 1.2, output: 4.0 }, // was a client alias for zai/glm-5-turbo
|
|
179
180
|
};
|
|
180
|
-
|
|
181
|
-
|
|
181
|
+
export function hasHistoricalPrice(model) { return model in LEGACY_PRICING; }
|
|
182
|
+
/** Gateway prices override historical fallbacks without replacing map identities. */
|
|
183
|
+
export const MODEL_PRICING = {};
|
|
184
|
+
export const OPUS_PRICING = { input: 5, output: 25 };
|
|
185
|
+
function updatePrices(state) {
|
|
186
|
+
for (const key of Object.keys(MODEL_PRICING))
|
|
187
|
+
delete MODEL_PRICING[key];
|
|
188
|
+
Object.assign(MODEL_PRICING, LEGACY_PRICING, state.pricing);
|
|
189
|
+
const opus = MODEL_PRICING['anthropic/claude-opus-5'];
|
|
190
|
+
if (opus)
|
|
191
|
+
Object.assign(OPUS_PRICING, opus);
|
|
192
|
+
}
|
|
193
|
+
updatePrices(getModelCatalog());
|
|
194
|
+
onModelCatalogChange(updatePrices);
|
|
182
195
|
/**
|
|
183
196
|
* Estimate cost in USD for a request.
|
|
184
197
|
* Falls back to $2/$10 per 1M for unknown models.
|
package/dist/router/vision.js
CHANGED
|
@@ -18,6 +18,8 @@
|
|
|
18
18
|
* model — having no vision pathway — would hallucinate based on the
|
|
19
19
|
* `Image file: <path>` description string. Expensive AND wrong.
|
|
20
20
|
*/
|
|
21
|
+
import { hasHistoricalPrice } from '../pricing.js';
|
|
22
|
+
import { getModelCatalog } from '../model-catalog.js';
|
|
21
23
|
import { freeVisionModel } from '../free-models.js';
|
|
22
24
|
const VISION_MODELS = new Set([
|
|
23
25
|
// Anthropic — native vision across the line
|
|
@@ -120,7 +122,13 @@ export function isVisionModel(modelId) {
|
|
|
120
122
|
// on gateway deploy state and on FRANKLIN_FREE_VISION_MODEL. freeVisionModel()
|
|
121
123
|
// returns null when no free model can be trusted with an image, and this
|
|
122
124
|
// stays false there.
|
|
123
|
-
|
|
125
|
+
if (modelId === freeVisionModel())
|
|
126
|
+
return true;
|
|
127
|
+
// Preserve vetted exclusions for existing models; use metadata for new IDs.
|
|
128
|
+
if (hasHistoricalPrice(modelId))
|
|
129
|
+
return false;
|
|
130
|
+
const model = getModelCatalog().models.find(entry => entry.id === modelId);
|
|
131
|
+
return model?.billing_mode !== 'free' && model?.categories.includes('vision') === true;
|
|
124
132
|
}
|
|
125
133
|
/** Lower-cased copy used for prefix family matching in pickVisionSibling. */
|
|
126
134
|
const VISION_MODELS_LIST = Array.from(VISION_MODELS);
|
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
* Shows categorized model list, supports shortcuts and arrow-key selection.
|
|
4
4
|
*/
|
|
5
5
|
import { type GatewayModel } from '../gateway-models.js';
|
|
6
|
-
export declare const MODEL_SHORTCUTS: Record<string, string>;
|
|
7
6
|
/**
|
|
8
7
|
* Resolve a model name — supports shortcuts. Returns the canonical model id.
|
|
9
8
|
*
|
|
@@ -53,8 +52,8 @@ export interface ModelCategory {
|
|
|
53
52
|
* (pickModel() below) import from this array. To add or remove models,
|
|
54
53
|
* edit this one place.
|
|
55
54
|
*/
|
|
55
|
+
export declare const MODEL_SHORTCUTS: Record<string, string>;
|
|
56
56
|
export declare const PICKER_CATEGORIES: ModelCategory[];
|
|
57
|
-
/** Flat list of all picker models (for index-based navigation). */
|
|
58
57
|
export declare const PICKER_MODELS_FLAT: ModelEntry[];
|
|
59
58
|
export interface HydratedPicker {
|
|
60
59
|
categories: ModelCategory[];
|
package/dist/ui/model-picker.js
CHANGED
|
@@ -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
|
-
|
|
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).
|
|
@@ -281,7 +282,7 @@ export function resolveModelStrict(input) {
|
|
|
281
282
|
}
|
|
282
283
|
const lower = trimmed.toLowerCase();
|
|
283
284
|
if (Object.prototype.hasOwnProperty.call(MODEL_SHORTCUTS, lower)) {
|
|
284
|
-
return { ok: true, id: MODEL_SHORTCUTS[lower], viaShortcut:
|
|
285
|
+
return { ok: true, id: MODEL_SHORTCUTS[lower], viaShortcut: MODEL_SHORTCUTS[lower] !== trimmed };
|
|
285
286
|
}
|
|
286
287
|
if (trimmed.includes('/')) {
|
|
287
288
|
return { ok: true, id: trimmed, viaShortcut: false };
|
|
@@ -331,121 +332,37 @@ const PROVIDER_LABELS = {
|
|
|
331
332
|
* (pickModel() below) import from this array. To add or remove models,
|
|
332
333
|
* edit this one place.
|
|
333
334
|
*/
|
|
334
|
-
export const
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
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);
|
|
335
|
+
export const MODEL_SHORTCUTS = {};
|
|
336
|
+
export const PICKER_CATEGORIES = [];
|
|
337
|
+
export const PICKER_MODELS_FLAT = [];
|
|
338
|
+
function updateCatalogView(state) {
|
|
339
|
+
for (const key of Object.keys(MODEL_SHORTCUTS))
|
|
340
|
+
delete MODEL_SHORTCUTS[key];
|
|
341
|
+
// Franklin's own aliases win over the shared policy: a remote catalog edit may
|
|
342
|
+
// add new shortcuts, but never retarget one a user already relies on (that
|
|
343
|
+
// would change which model runs, and what it costs, without a release). The
|
|
344
|
+
// same rule keeps every existing free shortcut free.
|
|
345
|
+
Object.assign(MODEL_SHORTCUTS, state.shortcuts, LEGACY_SHORTCUTS);
|
|
346
|
+
const categories = [{
|
|
347
|
+
category: '🧠 Smart routing (auto-pick)',
|
|
348
|
+
models: [{ id: 'blockrun/auto', shortcut: 'auto', label: 'Auto', price: 'routed' }],
|
|
349
|
+
}, ...state.groups.filter(group => group.id !== 'other').map(group => ({
|
|
350
|
+
category: group.title,
|
|
351
|
+
models: group.models.map(model => ({
|
|
352
|
+
id: model.id, label: model.name,
|
|
353
|
+
// Shortest alias reads best in the picker column (`opus`, not `opus-5`).
|
|
354
|
+
shortcut: Object.entries(MODEL_SHORTCUTS)
|
|
355
|
+
.filter(([key, target]) => target === model.id && !key.includes('/'))
|
|
356
|
+
.map(([key]) => key)
|
|
357
|
+
.reduce((best, key) => !best || key.length < best.length ? key : best, undefined) ?? model.id,
|
|
358
|
+
price: formatPrice(model),
|
|
359
|
+
})),
|
|
360
|
+
}))];
|
|
361
|
+
PICKER_CATEGORIES.splice(0, PICKER_CATEGORIES.length, ...categories);
|
|
362
|
+
PICKER_MODELS_FLAT.splice(0, PICKER_MODELS_FLAT.length, ...categories.flatMap(c => c.models));
|
|
363
|
+
}
|
|
364
|
+
updateCatalogView(getModelCatalog());
|
|
365
|
+
onModelCatalogChange(updateCatalogView);
|
|
449
366
|
// ─── Live hydration against the gateway catalog ────────────────────────────
|
|
450
367
|
/**
|
|
451
368
|
* 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.
|
|
3
|
+
"version": "3.47.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/2b55804b109cd132bd988096fb3617fb48e67cfb"
|
|
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>;
|
package/dist/payments/account.js
DELETED
|
@@ -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
|
-
}
|