@blockrun/franklin 3.43.0 → 3.44.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.
Files changed (58) hide show
  1. package/README.md +95 -11
  2. package/dist/agent/intent-prefetch.js +4 -3
  3. package/dist/agent/llm.js +5 -0
  4. package/dist/agent/loop.js +7 -4
  5. package/dist/agent/secret-redact.js +11 -0
  6. package/dist/commands/balance.js +25 -1
  7. package/dist/commands/doctor.js +48 -2
  8. package/dist/commands/login.d.ts +14 -0
  9. package/dist/commands/login.js +97 -0
  10. package/dist/commands/models.js +3 -2
  11. package/dist/commands/plugin.js +3 -2
  12. package/dist/commands/predict.js +3 -2
  13. package/dist/commands/proxy.js +3 -2
  14. package/dist/commands/setup.js +15 -1
  15. package/dist/commands/slack.js +3 -2
  16. package/dist/commands/social.js +3 -2
  17. package/dist/commands/start.js +3 -2
  18. package/dist/commands/stats.js +18 -1
  19. package/dist/commands/telegram.js +3 -2
  20. package/dist/config.d.ts +5 -0
  21. package/dist/config.js +17 -0
  22. package/dist/gateway-models.js +9 -4
  23. package/dist/index.js +26 -3
  24. package/dist/onramp/client.js +3 -2
  25. package/dist/payments/auth-mode.d.ts +114 -0
  26. package/dist/payments/auth-mode.js +186 -0
  27. package/dist/payments/post-with-payment.d.ts +6 -0
  28. package/dist/payments/post-with-payment.js +40 -6
  29. package/dist/payments/price-catalog.d.ts +71 -0
  30. package/dist/payments/price-catalog.js +322 -0
  31. package/dist/phone/client.js +6 -2
  32. package/dist/pricing.js +3 -3
  33. package/dist/proxy/fallback.d.ts +1 -1
  34. package/dist/proxy/fallback.js +21 -2
  35. package/dist/proxy/server.js +38 -1
  36. package/dist/router/index.js +2 -1
  37. package/dist/serve/cloud-sync.d.ts +1 -0
  38. package/dist/serve/server.js +10 -3
  39. package/dist/stats/tracker.d.ts +15 -1
  40. package/dist/stats/tracker.js +14 -2
  41. package/dist/tools/blockrun.js +10 -3
  42. package/dist/tools/defillama.js +9 -3
  43. package/dist/tools/exa.js +22 -9
  44. package/dist/tools/imagegen.js +4 -2
  45. package/dist/tools/modal.js +4 -2
  46. package/dist/tools/musicgen.js +4 -2
  47. package/dist/tools/phone.js +4 -2
  48. package/dist/tools/prediction.js +15 -4
  49. package/dist/tools/realface.js +14 -8
  50. package/dist/tools/rpc.js +10 -3
  51. package/dist/tools/surf.js +12 -4
  52. package/dist/tools/videogen.js +4 -2
  53. package/dist/tools/voice.js +6 -4
  54. package/dist/tools/zerox-base.js +4 -2
  55. package/dist/tools/zerox-gasless.js +6 -4
  56. package/dist/trading/providers/blockrun/client.js +20 -7
  57. package/dist/ui/model-picker.js +1 -1
  58. package/package.json +8 -4
@@ -0,0 +1,71 @@
1
+ /**
2
+ * List prices for the gateway's flat-rate service endpoints.
3
+ *
4
+ * Wallet mode learns what a call costs from the 402 handshake — the amount is
5
+ * in the payment requirements, so the recorded spend is exact. API-key mode
6
+ * has no handshake: the gateway settles against a prepaid balance and answers
7
+ * 200 with no charge amount anywhere in the response. Without a price source,
8
+ * every paid call in key mode would record $0, which silently disables the
9
+ * --max-spend ceiling, the PreSpend hooks and every budget in the product.
10
+ *
11
+ * BlockRun publishes machine-readable prices at `/.well-known/x402`, so that
12
+ * is the source of truth here rather than constants scattered across tools
13
+ * (which had already drifted — surf.ts documented tiered $0.001/$0.005/$0.02
14
+ * against a catalog that says a flat $0.0085).
15
+ *
16
+ * Scope is deliberately narrow: **flat-rate service endpoints only**.
17
+ * Model-priced endpoints — chat, images, video, speech — are already costed by
18
+ * `gateway-models.ts` from the live model catalog, and that path works
19
+ * identically in both modes.
20
+ *
21
+ * Prices from this module are estimates. Callers must tag what they record so
22
+ * the audit trail never claims more precision than it has.
23
+ */
24
+ interface CatalogEntry {
25
+ /** Endpoint pattern as published, e.g. `/api/v1/surf/*`. */
26
+ endpoint: string;
27
+ /** USD per request, or 0 for a free endpoint. */
28
+ usd: number;
29
+ }
30
+ /**
31
+ * Refresh the catalog in the background. Safe to call repeatedly; only one
32
+ * fetch is ever in flight and it is skipped while the cache is fresh.
33
+ */
34
+ export declare function warmPriceCatalog(): void;
35
+ /** Test seam — drop the loaded catalog and fall back to the static floor. */
36
+ export declare function __resetPriceCatalog(): void;
37
+ /** Test seam — install a catalog without touching the network or disk. */
38
+ export declare function __primePriceCatalog(entries: CatalogEntry[]): void;
39
+ /**
40
+ * List price in USD for one gateway path, or null when the path is not a
41
+ * flat-rate service endpoint (chat and the other model-priced endpoints land
42
+ * here, and are costed from the model catalog instead).
43
+ *
44
+ * `apiPath` may be a bare path or a full URL, with or without the `/api`
45
+ * prefix and with or without a query string — the two payment hosts differ on
46
+ * the prefix and callers should not have to care.
47
+ *
48
+ * Synchronous by design: it is called on the response path of every paid tool,
49
+ * where an await would serialise the accounting behind a network fetch. The
50
+ * catalog refreshes in the background via `warmPriceCatalog()`.
51
+ */
52
+ export declare function priceForPath(apiPath: string): number | null;
53
+ /**
54
+ * The amount to record for a completed paid call.
55
+ *
56
+ * `settledUsd` is the exact figure from an x402 settlement and always wins.
57
+ * `reportedUsd` is a charge the endpoint itself returned (Exa's `costDollars`).
58
+ * Otherwise the call is priced from the catalog — an estimate, flagged as such
59
+ * so `franklin stats` can render it honestly.
60
+ */
61
+ export interface ResolvedCharge {
62
+ usd: number;
63
+ estimated: boolean;
64
+ }
65
+ export declare function resolveCharge(opts: {
66
+ apiPath: string;
67
+ settledUsd?: number;
68
+ reportedUsd?: number;
69
+ fallbackUsd?: number;
70
+ }): ResolvedCharge;
71
+ export {};
@@ -0,0 +1,322 @@
1
+ /**
2
+ * List prices for the gateway's flat-rate service endpoints.
3
+ *
4
+ * Wallet mode learns what a call costs from the 402 handshake — the amount is
5
+ * in the payment requirements, so the recorded spend is exact. API-key mode
6
+ * has no handshake: the gateway settles against a prepaid balance and answers
7
+ * 200 with no charge amount anywhere in the response. Without a price source,
8
+ * every paid call in key mode would record $0, which silently disables the
9
+ * --max-spend ceiling, the PreSpend hooks and every budget in the product.
10
+ *
11
+ * BlockRun publishes machine-readable prices at `/.well-known/x402`, so that
12
+ * is the source of truth here rather than constants scattered across tools
13
+ * (which had already drifted — surf.ts documented tiered $0.001/$0.005/$0.02
14
+ * against a catalog that says a flat $0.0085).
15
+ *
16
+ * Scope is deliberately narrow: **flat-rate service endpoints only**.
17
+ * Model-priced endpoints — chat, images, video, speech — are already costed by
18
+ * `gateway-models.ts` from the live model catalog, and that path works
19
+ * identically in both modes.
20
+ *
21
+ * Prices from this module are estimates. Callers must tag what they record so
22
+ * the audit trail never claims more precision than it has.
23
+ */
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { BLOCKRUN_DIR, USER_AGENT } from '../config.js';
27
+ /**
28
+ * The discovery doc is public, unauthenticated, and identical across the
29
+ * payment hosts, so it is always read from the Base origin — including in key
30
+ * mode, where `api.blockrun.ai` does not serve it.
31
+ */
32
+ const CATALOG_URL = 'https://blockrun.ai/.well-known/x402';
33
+ const CACHE_FILE = path.join(BLOCKRUN_DIR, 'price-catalog.json');
34
+ const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // prices move rarely; a stale read is cheap
35
+ const FETCH_TIMEOUT_MS = 8_000;
36
+ /**
37
+ * Offline floor, current as of 2026-09-05. Used before the first successful
38
+ * fetch and whenever the network is unavailable, so key mode never falls back
39
+ * to recording zero. Refreshed automatically from the live catalog.
40
+ */
41
+ const STATIC_CATALOG = [
42
+ { endpoint: '/api/v1/surf/*', usd: 0.0085 },
43
+ { endpoint: '/api/v1/exa/contents', usd: 0.003 },
44
+ { endpoint: '/api/v1/exa/*', usd: 0.011 },
45
+ { endpoint: '/api/v1/rpc/{network}', usd: 0.003 },
46
+ { endpoint: '/api/v1/pm/*', usd: 0.0085 },
47
+ { endpoint: '/api/v1/defillama/*', usd: 0.006 },
48
+ { endpoint: '/api/v1/phone/*', usd: 0.011 },
49
+ { endpoint: '/api/v1/voice/call', usd: 0.541 },
50
+ { endpoint: '/api/v1/modal/sandbox/create', usd: 0.011 },
51
+ { endpoint: '/api/v1/modal/*', usd: 0.002 },
52
+ { endpoint: '/api/v1/realface/*', usd: 0.011 },
53
+ { endpoint: '/api/v1/portrait/*', usd: 0.011 },
54
+ { endpoint: '/api/v1/polymarket/fund', usd: 0.011 },
55
+ { endpoint: '/api/v1/usstock/price/{ticker}', usd: 0.002 },
56
+ { endpoint: '/api/v1/search', usd: 0.025 },
57
+ // Explicitly free — listed so a lookup returns 0 rather than "unknown",
58
+ // which would make callers fall back to a non-zero guess.
59
+ { endpoint: '/api/v1/zerox/*', usd: 0 },
60
+ { endpoint: '/api/v1/crypto/price/{pair}', usd: 0 },
61
+ { endpoint: '/api/v1/fx/price/{pair}', usd: 0 },
62
+ { endpoint: '/api/v1/commodity/price/{symbol}', usd: 0 },
63
+ { endpoint: '/api/v1/onramp/token', usd: 0 },
64
+ { endpoint: '/api/v1/models', usd: 0 },
65
+ ];
66
+ let catalog = STATIC_CATALOG;
67
+ let loadedAt = 0;
68
+ let inFlight = null;
69
+ // ─── Price parsing ──────────────────────────────────────────────────────
70
+ /** `"$0.0085"` / `"0.006"` / `0.003` → 0.0085 / 0.006 / 0.003. Null if unparseable. */
71
+ function toUsd(value) {
72
+ if (typeof value === 'number')
73
+ return Number.isFinite(value) ? value : null;
74
+ if (typeof value !== 'string')
75
+ return null;
76
+ const n = Number(value.replace(/^\$/, '').trim());
77
+ return Number.isFinite(n) ? n : null;
78
+ }
79
+ /**
80
+ * Reduce one service's `pricing` object to a single per-request USD figure,
81
+ * plus any nested endpoint-specific overrides it declares.
82
+ *
83
+ * The catalog uses several shapes for the same idea — `perRequest`, `perCall`,
84
+ * `flat`, `tierN.perRequest`, and grouped `{ endpoints: [...] }` lists. Only
85
+ * flat-rate shapes are handled; per-model maps (chat, images, video, speech)
86
+ * return null because `gateway-models.ts` prices those from the model catalog.
87
+ */
88
+ function parsePricing(endpoint, pricing) {
89
+ if (!pricing || typeof pricing !== 'object')
90
+ return [];
91
+ const p = pricing;
92
+ const out = [];
93
+ if (p.free === true)
94
+ return [{ endpoint, usd: 0 }];
95
+ const direct = toUsd(p.perRequest) ?? toUsd(p.perCall) ?? toUsd(p.flat) ?? toUsd(p.perUrl);
96
+ if (direct !== null)
97
+ out.push({ endpoint, usd: direct });
98
+ // Live search is billed per source queried. Franklin's Search tool sends one
99
+ // source unless the caller widens it, so the single-source price is the
100
+ // floor. A multi-source call is under-counted rather than guessed at — the
101
+ // dashboard remains the authority on the exact figure.
102
+ const perSource = toUsd(p.pricePerSource);
103
+ if (perSource !== null)
104
+ out.push({ endpoint, usd: perSource });
105
+ // Nested groups: { tier1: {...}, tier2: {...} } and
106
+ // { create: { perRequest, endpoint }, operations: { perRequest, endpoints: [] } }.
107
+ for (const [key, value] of Object.entries(p)) {
108
+ if (!value || typeof value !== 'object' || key === 'payment')
109
+ continue;
110
+ const group = value;
111
+ const usd = toUsd(group.perRequest) ?? toUsd(group.perCall) ?? toUsd(group.perUrl);
112
+ if (usd === null)
113
+ continue;
114
+ const own = typeof group.endpoint === 'string' ? [group.endpoint] : [];
115
+ const many = Array.isArray(group.endpoints)
116
+ ? group.endpoints.filter((e) => typeof e === 'string')
117
+ : [];
118
+ const targets = [...own, ...many];
119
+ if (targets.length > 0)
120
+ for (const t of targets)
121
+ out.push({ endpoint: t, usd });
122
+ // A bare tier with no endpoint list prices the whole service. Take the
123
+ // dearest tier so an estimate errs toward over-counting, which is the safe
124
+ // direction for a spend ceiling.
125
+ else if (!out.some((e) => e.endpoint === endpoint && e.usd >= usd)) {
126
+ out.push({ endpoint, usd });
127
+ }
128
+ }
129
+ // A service listing per-endpoint prices as a flat array.
130
+ if (Array.isArray(p.endpoints)) {
131
+ for (const item of p.endpoints) {
132
+ if (!item || typeof item !== 'object')
133
+ continue;
134
+ const row = item;
135
+ const usd = toUsd(row.perRequest) ?? toUsd(row.perCall);
136
+ if (typeof row.endpoint === 'string' && usd !== null) {
137
+ out.push({ endpoint: row.endpoint, usd });
138
+ }
139
+ }
140
+ }
141
+ return out;
142
+ }
143
+ // ─── Pattern matching ───────────────────────────────────────────────────
144
+ /**
145
+ * Turn a published endpoint pattern into a matcher.
146
+ *
147
+ * `/api/v1/surf/*` → any path under /surf/
148
+ * `/api/v1/rpc/{network}` → one path segment
149
+ * `/api/v1/pm/{limitless,opinion}/*` → one of the listed segments
150
+ */
151
+ function patternToRegExp(pattern) {
152
+ let src = '';
153
+ for (const part of pattern.split('/')) {
154
+ if (part === '')
155
+ continue;
156
+ src += '/';
157
+ if (part === '*') {
158
+ src += '.*';
159
+ }
160
+ else if (part.startsWith('{') && part.endsWith('}')) {
161
+ const inner = part.slice(1, -1);
162
+ // A brace group may itself contain slashes and nested braces, e.g.
163
+ // `{identity/{wallet},identities}` — too irregular to model exactly, so
164
+ // treat any such group as "one or more segments".
165
+ src += inner.includes(',') || inner.includes('/') ? '[^?]+' : '[^/?]+';
166
+ }
167
+ else {
168
+ src += part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
169
+ }
170
+ }
171
+ return new RegExp(`^${src}/?$`);
172
+ }
173
+ /** Specificity: more literal segments and no wildcard wins. */
174
+ function specificity(pattern) {
175
+ const segments = pattern.split('/').filter(Boolean);
176
+ const literal = segments.filter((s) => s !== '*' && !s.startsWith('{')).length;
177
+ return literal * 10 - (pattern.includes('*') ? 1 : 0);
178
+ }
179
+ // ─── Cache ──────────────────────────────────────────────────────────────
180
+ function readDiskCache() {
181
+ try {
182
+ const stat = fs.statSync(CACHE_FILE);
183
+ if (Date.now() - stat.mtimeMs > CACHE_TTL_MS)
184
+ return;
185
+ const parsed = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
186
+ if (Array.isArray(parsed) && parsed.length > 0) {
187
+ catalog = parsed;
188
+ loadedAt = stat.mtimeMs;
189
+ }
190
+ }
191
+ catch { /* no cache, or unreadable — the static floor covers it */ }
192
+ }
193
+ function writeDiskCache(entries) {
194
+ try {
195
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
196
+ fs.writeFileSync(CACHE_FILE, JSON.stringify(entries), { mode: 0o600 });
197
+ }
198
+ catch { /* best-effort — an in-memory catalog still works */ }
199
+ }
200
+ async function fetchCatalog() {
201
+ const ctrl = new AbortController();
202
+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
203
+ try {
204
+ const res = await fetch(CATALOG_URL, {
205
+ signal: ctrl.signal,
206
+ headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
207
+ });
208
+ if (!res.ok)
209
+ return;
210
+ const body = (await res.json());
211
+ if (!Array.isArray(body.services))
212
+ return;
213
+ const entries = [];
214
+ for (const svc of body.services) {
215
+ if (!svc || typeof svc !== 'object')
216
+ continue;
217
+ const s = svc;
218
+ if (typeof s.endpoint !== 'string')
219
+ continue;
220
+ entries.push(...parsePricing(s.endpoint, s.pricing));
221
+ }
222
+ if (entries.length === 0)
223
+ return;
224
+ // Keep the static floor underneath so an endpoint the catalog stops
225
+ // listing does not silently become free.
226
+ const merged = new Map();
227
+ for (const e of STATIC_CATALOG)
228
+ merged.set(e.endpoint, e.usd);
229
+ for (const e of entries)
230
+ merged.set(e.endpoint, e.usd);
231
+ catalog = [...merged].map(([endpoint, usd]) => ({ endpoint, usd }));
232
+ loadedAt = Date.now();
233
+ writeDiskCache(catalog);
234
+ }
235
+ catch { /* offline — the static floor covers it */ }
236
+ finally {
237
+ clearTimeout(timer);
238
+ }
239
+ }
240
+ /**
241
+ * Refresh the catalog in the background. Safe to call repeatedly; only one
242
+ * fetch is ever in flight and it is skipped while the cache is fresh.
243
+ */
244
+ export function warmPriceCatalog() {
245
+ if (loadedAt === 0)
246
+ readDiskCache();
247
+ if (Date.now() - loadedAt < CACHE_TTL_MS)
248
+ return;
249
+ if (inFlight)
250
+ return;
251
+ inFlight = fetchCatalog().finally(() => { inFlight = null; });
252
+ }
253
+ /** Test seam — drop the loaded catalog and fall back to the static floor. */
254
+ export function __resetPriceCatalog() {
255
+ catalog = STATIC_CATALOG;
256
+ loadedAt = 0;
257
+ inFlight = null;
258
+ }
259
+ /** Test seam — install a catalog without touching the network or disk. */
260
+ export function __primePriceCatalog(entries) {
261
+ catalog = entries;
262
+ loadedAt = Date.now();
263
+ }
264
+ // ─── Lookup ─────────────────────────────────────────────────────────────
265
+ /**
266
+ * List price in USD for one gateway path, or null when the path is not a
267
+ * flat-rate service endpoint (chat and the other model-priced endpoints land
268
+ * here, and are costed from the model catalog instead).
269
+ *
270
+ * `apiPath` may be a bare path or a full URL, with or without the `/api`
271
+ * prefix and with or without a query string — the two payment hosts differ on
272
+ * the prefix and callers should not have to care.
273
+ *
274
+ * Synchronous by design: it is called on the response path of every paid tool,
275
+ * where an await would serialise the accounting behind a network fetch. The
276
+ * catalog refreshes in the background via `warmPriceCatalog()`.
277
+ */
278
+ export function priceForPath(apiPath) {
279
+ warmPriceCatalog();
280
+ // Accept a bare path or a full gateway URL — call sites already hold the
281
+ // absolute endpoint they fetched, and making them slice it would just
282
+ // duplicate this logic 8 times.
283
+ let normalized = apiPath;
284
+ if (/^https?:\/\//.test(normalized)) {
285
+ try {
286
+ normalized = new URL(normalized).pathname;
287
+ }
288
+ catch { /* fall through */ }
289
+ }
290
+ normalized = normalized.split('?')[0];
291
+ if (!normalized.startsWith('/'))
292
+ normalized = '/' + normalized;
293
+ // The x402 hosts serve these routes under /api, the key host at the root.
294
+ // Catalog patterns use the /api form, so normalise onto that.
295
+ if (!normalized.startsWith('/api/'))
296
+ normalized = '/api' + normalized;
297
+ let best = null;
298
+ for (const entry of catalog) {
299
+ if (!patternToRegExp(entry.endpoint).test(normalized))
300
+ continue;
301
+ const score = specificity(entry.endpoint);
302
+ if (!best || score > best.score)
303
+ best = { usd: entry.usd, score };
304
+ }
305
+ return best ? best.usd : null;
306
+ }
307
+ export function resolveCharge(opts) {
308
+ const { apiPath, settledUsd, reportedUsd, fallbackUsd } = opts;
309
+ if (typeof settledUsd === 'number' && settledUsd > 0) {
310
+ return { usd: settledUsd, estimated: false };
311
+ }
312
+ if (typeof reportedUsd === 'number' && reportedUsd > 0) {
313
+ return { usd: reportedUsd, estimated: false };
314
+ }
315
+ const listed = priceForPath(apiPath);
316
+ if (listed !== null)
317
+ return { usd: listed, estimated: true };
318
+ if (typeof fallbackUsd === 'number' && fallbackUsd > 0) {
319
+ return { usd: fallbackUsd, estimated: true };
320
+ }
321
+ return { usd: 0, estimated: true };
322
+ }
@@ -12,12 +12,16 @@
12
12
  * - phone cache refresh (background)
13
13
  * - future Phone/Call tools surfaced to the agent
14
14
  */
15
- import { API_URLS, loadChain } from '../config.js';
15
+ import { loadChain } from '../config.js';
16
+ import { gatewayBase } from '../payments/auth-mode.js';
16
17
  import { postWithPayment } from '../payments/post-with-payment.js';
17
18
  import { recordUsage } from '../stats/tracker.js';
18
19
  import { writeCache } from './cache.js';
19
20
  function phoneEndpoint(chain, path) {
20
- return `${API_URLS[chain]}/v1/phone/${path}`;
21
+ // `chain` is retained for call-site clarity; the host itself comes from the
22
+ // active pay mode, which is chainless in API-key mode.
23
+ void chain;
24
+ return `${gatewayBase()}/v1/phone/${path}`;
21
25
  }
22
26
  /**
23
27
  * Fetch the wallet's owned numbers from BlockRun. Refreshes the local
package/dist/pricing.js CHANGED
@@ -106,9 +106,9 @@ export const MODEL_PRICING = {
106
106
  'google/gemini-2.5-pro': { input: 1.25, output: 10.0 },
107
107
  'google/gemini-3.1-pro': { input: 2.0, output: 12.0 },
108
108
  // xAI
109
- 'xai/grok-4.3': { input: 1.5, output: 4.0 }, // 1M ctx; demoted from flagship 2026-07-14
110
- 'xai/grok-4.5': { input: 2.5, output: 9.0 }, // xAI flagship — 500K ctx (note: less than 4.3's 1M)
111
- 'xai/grok-build-0.1': { input: 1.5, output: 3.0 }, // agentic coding, OpenRouter resale
109
+ 'xai/grok-4.3': { input: 1.25, output: 2.5 }, // 1M ctx; demoted from flagship 2026-07-14
110
+ 'xai/grok-4.5': { input: 2.0, output: 6.0 }, // xAI flagship — 500K ctx (note: less than 4.3's 1M)
111
+ 'xai/grok-build-0.1': { input: 1.0, output: 2.0 }, // agentic coding, OpenRouter resale
112
112
  // DeepSeek (gateway re-aliased these to V4 Flash on 2026-05-03; price cut
113
113
  // again upstream 2026-08-07 to $0.14/$0.28 — mirrored here 2026-08-12).
114
114
  'deepseek/deepseek-chat': { input: 0.14, output: 0.28 },
@@ -44,4 +44,4 @@ export declare const ROUTING_PROFILES: Set<string>;
44
44
  * nothing more than provider overload. `blockrun/free` was already handled;
45
45
  * a concrete free id was not.
46
46
  */
47
- export declare function buildFallbackChain(startModel: string, config?: FallbackConfig): string[];
47
+ export declare function buildFallbackChain(startModel: string, config?: FallbackConfig, needsVision?: boolean): string[];
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { logger } from '../logger.js';
6
6
  import { FREE_DEFAULT_MODEL, isFreeModelId } from '../free-models.js';
7
+ import { isVisionModel } from '../router/vision.js';
7
8
  export const DEFAULT_FALLBACK_CONFIG = {
8
9
  chain: [
9
10
  'deepseek/deepseek-chat', // Direct fallback — cheap & reliable
@@ -124,9 +125,27 @@ export const ROUTING_PROFILES = new Set([
124
125
  * nothing more than provider overload. `blockrun/free` was already handled;
125
126
  * a concrete free id was not.
126
127
  */
127
- export function buildFallbackChain(startModel, config = DEFAULT_FALLBACK_CONFIG) {
128
+ export function buildFallbackChain(startModel, config = DEFAULT_FALLBACK_CONFIG, needsVision = false) {
128
129
  // Never include routing profiles in the chain — they'd cause 400s
129
- const safeChain = config.chain.filter(m => !ROUTING_PROFILES.has(m));
130
+ let safeChain = config.chain.filter(m => !ROUTING_PROFILES.has(m));
131
+ // A request carrying images must not fall back onto a text-only model.
132
+ //
133
+ // The pre-request guard in proxy/server.ts swaps a text-only pick for a
134
+ // vision sibling, but it runs ONCE, before the call. This chain is walked
135
+ // AFTER a failure, so the guard was bypassed on every retry: an image sent
136
+ // to claude-sonnet-4.6 that hit a 429 fell straight to
137
+ // deepseek/deepseek-chat, which cannot read images at all.
138
+ //
139
+ // That costs real money. The gateway does not always refuse these before
140
+ // payment — probed 2026-08-31, Base returns 402 (a payment quote) for an
141
+ // image request to deepseek/deepseek-chat and the whole zai/glm-5.x line,
142
+ // while Solana correctly 400s them pre-payment. So on Base the retry is
143
+ // quoted, signed, settled, and THEN rejected upstream — or worse, answered
144
+ // without the image. Same shape as the free-tier guard above: the chain has
145
+ // to know what the request needs, not just what it costs.
146
+ if (needsVision) {
147
+ safeChain = safeChain.filter(m => isVisionModel(m));
148
+ }
130
149
  // Free start model → free-only chain. Ends the walk rather than reaching for
131
150
  // a paid rung; the caller gets the failure instead of a surprise charge.
132
151
  if (isFreeModelId(startModel)) {
@@ -1,5 +1,6 @@
1
1
  import http from 'node:http';
2
2
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
3
+ import { applyGatewayAuth } from '../payments/auth-mode.js';
3
4
  import { recordUsage } from '../stats/tracker.js';
4
5
  // Single source of truth for shortcuts — shared with the /model picker so the
5
6
  // proxy can never drift from the interactive UI (it did before: grok→grok-3).
@@ -180,6 +181,28 @@ function withinRateLimit() {
180
181
  rateWindow.push(now);
181
182
  return true;
182
183
  }
184
+ /**
185
+ * Does this raw request body carry image content?
186
+ *
187
+ * The pre-request vision guard computes this from the already-parsed body, but
188
+ * that binding is out of scope by the time the FALLBACK chain is built — and
189
+ * the fallback walk is exactly where an unguarded retry drops an image onto a
190
+ * text-only model the gateway will still charge for. Re-derived from the raw
191
+ * body so the retry path cannot silently lose the requirement.
192
+ */
193
+ function bodyNeedsVision(body) {
194
+ if (!body)
195
+ return false;
196
+ try {
197
+ const parsed = JSON.parse(body);
198
+ return messagesNeedVision((parsed.messages ?? []));
199
+ }
200
+ catch {
201
+ // Unparseable body: assume no images rather than filtering the chain down
202
+ // on a guess. The pre-request guard already ran on the parsed copy.
203
+ return false;
204
+ }
205
+ }
183
206
  export function createProxy(options) {
184
207
  // Wire stderr-mirroring of unified logger output to the proxy's debug
185
208
  // flag — same pattern as interactiveSession in agent/loop. File writes
@@ -428,6 +451,16 @@ export function createProxy(options) {
428
451
  headers[key] = Array.isArray(value) ? value[0] : value;
429
452
  }
430
453
  }
454
+ // Applied AFTER the forwarding loop so our credential wins over
455
+ // whatever the proxied client sent. Anthropic-compatible clients
456
+ // routinely set their own `authorization` / `x-api-key`; in API-key
457
+ // mode those must not reach the gateway in place of Franklin's key.
458
+ // In wallet mode this contributes no auth at all and payment still
459
+ // rides on the PAYMENT-SIGNATURE header added on the 402 retry.
460
+ // applyGatewayAuth also strips the client's own Authorization header
461
+ // in every case variant — without that, fetch sends two of them and
462
+ // the gateway reads the wrong one (verified: 401 through the proxy).
463
+ applyGatewayAuth(headers);
431
464
  // Safety net: if requestModel is still a routing profile (blockrun/auto etc.)
432
465
  // after all resolution attempts, force-route it to a concrete model.
433
466
  // This prevents 404s from the backend which doesn't recognize virtual model names.
@@ -467,7 +500,11 @@ export function createProxy(options) {
467
500
  chain: [
468
501
  ...new Set([
469
502
  ...routerCandidates,
470
- ...buildFallbackChain(requestModel),
503
+ // Recomputed here rather than reused from the pre-request
504
+ // guard above: that const is out of scope by this point, and
505
+ // without it the RETRY path drops images onto a text-only
506
+ // model that the gateway will happily charge for.
507
+ ...buildFallbackChain(requestModel, DEFAULT_FALLBACK_CONFIG, bodyNeedsVision(body)),
471
508
  ]),
472
509
  ],
473
510
  };
@@ -525,9 +525,10 @@ export async function llmClassifyRequest(prompt) {
525
525
  try {
526
526
  const llmMod = await import('../agent/llm.js');
527
527
  const cfgMod = await import('../config.js');
528
+ const authMod = await import('../payments/auth-mode.js');
528
529
  ModelClientCtor = llmMod.ModelClient;
529
530
  chain = cfgMod.loadChain();
530
- apiUrl = cfgMod.API_URLS[chain];
531
+ apiUrl = authMod.gatewayBase();
531
532
  }
532
533
  catch {
533
534
  return null;
@@ -16,6 +16,7 @@ export interface CloudConversation {
16
16
  createdAt: number;
17
17
  updatedAt: number;
18
18
  messages: unknown[];
19
+ pinnedAt?: number;
19
20
  }
20
21
  export declare function isCloudSyncEnabled(): boolean;
21
22
  export declare function cloudList(): Promise<CloudConversation[]>;
@@ -23,7 +23,8 @@ import path from 'node:path';
23
23
  // `ws` 8 moved the server class off the default export onto a named one. The
24
24
  // default import stays for the `WebSocket` type and its `OPEN` constant.
25
25
  import WebSocket, { WebSocketServer } from 'ws';
26
- import { loadChain, API_URLS, BLOCKRUN_DIR } from '../config.js';
26
+ import { loadChain, BLOCKRUN_DIR } from '../config.js';
27
+ import { gatewayBase, isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
27
28
  import { loadConfig, setConfigValue } from '../commands/config.js';
28
29
  import { assembleInstructions } from '../agent/context.js';
29
30
  import { interactiveSession } from '../agent/loop.js';
@@ -399,7 +400,7 @@ export async function startServer(opts) {
399
400
  let { port } = opts;
400
401
  const { workDir, debug } = opts;
401
402
  const chain = loadChain();
402
- const apiUrl = API_URLS[chain];
403
+ const apiUrl = gatewayBase();
403
404
  const userConfig = loadConfig();
404
405
  const desktopBoundary = process.env.FRANKLIN_DESKTOP_WORKSPACE_BOUNDARY === '1';
405
406
  const desktopPermissionPolicy = desktopBoundary
@@ -728,7 +729,13 @@ export async function startServer(opts) {
728
729
  // string instead of accidentally serializing a pending Promise as {}.
729
730
  const address = await client.getWalletAddress();
730
731
  const balanceUsd = await fetchBalanceUsd(); // best-effort; undefined on failure
731
- send(ws, id, 'response', { address, chain, balanceUsd });
732
+ // The wallet still exists in API-key mode, but it is not what pays.
733
+ // Ship the active mode so the panel does not present a wallet balance
734
+ // as the spending source when spend is coming out of prepaid credit.
735
+ const key = loadApiKey();
736
+ const payMode = isKeyMode() ? 'api-key' : 'wallet';
737
+ const apiKeyMasked = isKeyMode() && key ? maskApiKey(key) : undefined;
738
+ send(ws, id, 'response', { address, chain, balanceUsd, payMode, apiKeyMasked });
732
739
  }
733
740
  catch (err) {
734
741
  send(ws, id, 'error', { message: err instanceof Error ? err.message : 'wallet error' });
@@ -25,6 +25,12 @@ export interface Stats {
25
25
  version: number;
26
26
  totalRequests: number;
27
27
  totalCostUsd: number;
28
+ /**
29
+ * Portion of totalCostUsd that is a list-price estimate rather than a
30
+ * settled x402 amount. Non-zero only in API-key mode, where the gateway
31
+ * reports no per-call charge.
32
+ */
33
+ totalEstimatedCostUsd: number;
28
34
  totalInputTokens: number;
29
35
  totalOutputTokens: number;
30
36
  totalFallbacks: number;
@@ -46,7 +52,15 @@ export declare function resetLiveSpend(): void;
46
52
  /**
47
53
  * Record a completed request for stats tracking
48
54
  */
49
- export declare function recordUsage(model: string, inputTokens: number, outputTokens: number, costUsd: number, latencyMs: number, fallback?: boolean): void;
55
+ export declare function recordUsage(model: string, inputTokens: number, outputTokens: number, costUsd: number, latencyMs: number, fallback?: boolean,
56
+ /**
57
+ * Whether `costUsd` is a list-price estimate rather than an exact settled
58
+ * amount. Defaults to the active pay mode: an x402 settlement reports the
59
+ * real figure, while the API-key gateway returns no charge at all, so every
60
+ * key-mode row is priced locally. Surfaced by `franklin stats` so the ledger
61
+ * never claims more precision than it has.
62
+ */
63
+ estimated?: boolean): void;
50
64
  /**
51
65
  * Get stats summary for display
52
66
  */