@blockrun/franklin 3.43.1 → 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.
- package/README.md +95 -11
- package/dist/agent/intent-prefetch.js +4 -3
- package/dist/agent/llm.js +5 -0
- package/dist/agent/loop.js +7 -4
- package/dist/agent/secret-redact.js +11 -0
- package/dist/commands/balance.js +25 -1
- package/dist/commands/doctor.js +48 -2
- package/dist/commands/login.d.ts +14 -0
- package/dist/commands/login.js +97 -0
- package/dist/commands/models.js +3 -2
- package/dist/commands/plugin.js +3 -2
- package/dist/commands/predict.js +3 -2
- package/dist/commands/proxy.js +3 -2
- package/dist/commands/setup.js +15 -1
- package/dist/commands/slack.js +3 -2
- package/dist/commands/social.js +3 -2
- package/dist/commands/start.js +3 -2
- package/dist/commands/stats.js +18 -1
- package/dist/commands/telegram.js +3 -2
- package/dist/config.d.ts +5 -0
- package/dist/config.js +17 -0
- package/dist/gateway-models.js +9 -4
- package/dist/index.js +26 -3
- package/dist/onramp/client.js +3 -2
- package/dist/payments/auth-mode.d.ts +114 -0
- package/dist/payments/auth-mode.js +186 -0
- package/dist/payments/post-with-payment.d.ts +6 -0
- package/dist/payments/post-with-payment.js +40 -6
- package/dist/payments/price-catalog.d.ts +71 -0
- package/dist/payments/price-catalog.js +322 -0
- package/dist/phone/client.js +6 -2
- package/dist/pricing.js +3 -3
- package/dist/proxy/server.js +11 -0
- package/dist/router/index.js +2 -1
- package/dist/serve/cloud-sync.d.ts +1 -0
- package/dist/serve/server.js +10 -3
- package/dist/stats/tracker.d.ts +15 -1
- package/dist/stats/tracker.js +14 -2
- package/dist/tools/blockrun.js +10 -3
- package/dist/tools/defillama.js +9 -3
- package/dist/tools/exa.js +22 -9
- package/dist/tools/imagegen.js +4 -2
- package/dist/tools/modal.js +4 -2
- package/dist/tools/musicgen.js +4 -2
- package/dist/tools/phone.js +4 -2
- package/dist/tools/prediction.js +15 -4
- package/dist/tools/realface.js +14 -8
- package/dist/tools/rpc.js +10 -3
- package/dist/tools/surf.js +12 -4
- package/dist/tools/videogen.js +4 -2
- package/dist/tools/voice.js +6 -4
- package/dist/tools/zerox-base.js +4 -2
- package/dist/tools/zerox-gasless.js +6 -4
- package/dist/trading/providers/blockrun/client.js +20 -7
- package/dist/ui/model-picker.js +1 -1
- 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
|
+
}
|
package/dist/phone/client.js
CHANGED
|
@@ -12,12 +12,16 @@
|
|
|
12
12
|
* - phone cache refresh (background)
|
|
13
13
|
* - future Phone/Call tools surfaced to the agent
|
|
14
14
|
*/
|
|
15
|
-
import {
|
|
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
|
-
|
|
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.
|
|
110
|
-
'xai/grok-4.5': { input: 2.
|
|
111
|
-
'xai/grok-build-0.1': { input: 1.
|
|
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 },
|
package/dist/proxy/server.js
CHANGED
|
@@ -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).
|
|
@@ -450,6 +451,16 @@ export function createProxy(options) {
|
|
|
450
451
|
headers[key] = Array.isArray(value) ? value[0] : value;
|
|
451
452
|
}
|
|
452
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);
|
|
453
464
|
// Safety net: if requestModel is still a routing profile (blockrun/auto etc.)
|
|
454
465
|
// after all resolution attempts, force-route it to a concrete model.
|
|
455
466
|
// This prevents 404s from the backend which doesn't recognize virtual model names.
|
package/dist/router/index.js
CHANGED
|
@@ -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 =
|
|
531
|
+
apiUrl = authMod.gatewayBase();
|
|
531
532
|
}
|
|
532
533
|
catch {
|
|
533
534
|
return null;
|
package/dist/serve/server.js
CHANGED
|
@@ -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,
|
|
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 =
|
|
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
|
-
|
|
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' });
|
package/dist/stats/tracker.d.ts
CHANGED
|
@@ -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
|
|
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
|
*/
|
package/dist/stats/tracker.js
CHANGED
|
@@ -7,6 +7,7 @@ import path from 'node:path';
|
|
|
7
7
|
import os from 'node:os';
|
|
8
8
|
import { OPUS_PRICING } from '../pricing.js';
|
|
9
9
|
import { BLOCKRUN_DIR } from '../config.js';
|
|
10
|
+
import { isKeyMode } from '../payments/auth-mode.js';
|
|
10
11
|
import { isTestFixtureModel } from './test-fixture.js';
|
|
11
12
|
import { atomicWriteFileSync } from '../storage/atomic.js';
|
|
12
13
|
let resolvedStatsFile = null;
|
|
@@ -65,6 +66,7 @@ const EMPTY_STATS = {
|
|
|
65
66
|
version: 1,
|
|
66
67
|
totalRequests: 0,
|
|
67
68
|
totalCostUsd: 0,
|
|
69
|
+
totalEstimatedCostUsd: 0,
|
|
68
70
|
totalInputTokens: 0,
|
|
69
71
|
totalOutputTokens: 0,
|
|
70
72
|
totalFallbacks: 0,
|
|
@@ -85,7 +87,7 @@ function parseStatsFile(file) {
|
|
|
85
87
|
merged.history = [];
|
|
86
88
|
if (!merged.byModel || typeof merged.byModel !== 'object' || Array.isArray(merged.byModel))
|
|
87
89
|
merged.byModel = {};
|
|
88
|
-
const numKeys = ['totalRequests', 'totalCostUsd', 'totalInputTokens', 'totalOutputTokens', 'totalFallbacks'];
|
|
90
|
+
const numKeys = ['totalRequests', 'totalCostUsd', 'totalEstimatedCostUsd', 'totalInputTokens', 'totalOutputTokens', 'totalFallbacks'];
|
|
89
91
|
for (const k of numKeys) {
|
|
90
92
|
if (!Number.isFinite(merged[k]))
|
|
91
93
|
merged[k] = 0;
|
|
@@ -190,7 +192,15 @@ export function resetLiveSpend() {
|
|
|
190
192
|
/**
|
|
191
193
|
* Record a completed request for stats tracking
|
|
192
194
|
*/
|
|
193
|
-
export function recordUsage(model, inputTokens, outputTokens, costUsd, latencyMs, fallback = false
|
|
195
|
+
export function recordUsage(model, inputTokens, outputTokens, costUsd, latencyMs, fallback = false,
|
|
196
|
+
/**
|
|
197
|
+
* Whether `costUsd` is a list-price estimate rather than an exact settled
|
|
198
|
+
* amount. Defaults to the active pay mode: an x402 settlement reports the
|
|
199
|
+
* real figure, while the API-key gateway returns no charge at all, so every
|
|
200
|
+
* key-mode row is priced locally. Surfaced by `franklin stats` so the ledger
|
|
201
|
+
* never claims more precision than it has.
|
|
202
|
+
*/
|
|
203
|
+
estimated = isKeyMode()) {
|
|
194
204
|
// Count real spend BEFORE the test/audit gates — the --max-spend ceiling must
|
|
195
205
|
// see every paid tool call even when history persistence is suppressed.
|
|
196
206
|
if (Number.isFinite(costUsd) && costUsd > 0)
|
|
@@ -212,6 +222,8 @@ export function recordUsage(model, inputTokens, outputTokens, costUsd, latencyMs
|
|
|
212
222
|
// Update totals
|
|
213
223
|
stats.totalRequests++;
|
|
214
224
|
stats.totalCostUsd += costUsd;
|
|
225
|
+
if (estimated)
|
|
226
|
+
stats.totalEstimatedCostUsd += costUsd;
|
|
215
227
|
stats.totalInputTokens += inputTokens;
|
|
216
228
|
stats.totalOutputTokens += outputTokens;
|
|
217
229
|
if (fallback)
|
package/dist/tools/blockrun.js
CHANGED
|
@@ -18,7 +18,9 @@
|
|
|
18
18
|
* shared module (out of scope; would touch unrelated tools).
|
|
19
19
|
*/
|
|
20
20
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
21
|
-
import { loadChain,
|
|
21
|
+
import { loadChain, USER_AGENT } from '../config.js';
|
|
22
|
+
import { resolveCharge } from '../payments/price-catalog.js';
|
|
23
|
+
import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
|
|
22
24
|
import { recordUsage } from '../stats/tracker.js';
|
|
23
25
|
import { logger } from '../logger.js';
|
|
24
26
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
@@ -92,6 +94,7 @@ async function callGateway(url, method, body, resourceDescription, abortSignal,
|
|
|
92
94
|
const start = Date.now();
|
|
93
95
|
const chain = loadChain();
|
|
94
96
|
const headers = {
|
|
97
|
+
...gatewayHeaders(),
|
|
95
98
|
'Accept': 'application/json',
|
|
96
99
|
'User-Agent': USER_AGENT,
|
|
97
100
|
};
|
|
@@ -145,7 +148,7 @@ async function callGateway(url, method, body, resourceDescription, abortSignal,
|
|
|
145
148
|
}
|
|
146
149
|
function buildUrl(path, params) {
|
|
147
150
|
const chain = loadChain();
|
|
148
|
-
const base =
|
|
151
|
+
const base = gatewayBase(); // wallet host ends in /api; the key host does not
|
|
149
152
|
const clean = path.startsWith('/') ? path : `/${path}`;
|
|
150
153
|
const url = `${base}${clean}`;
|
|
151
154
|
if (!params || Object.keys(params).length === 0)
|
|
@@ -233,7 +236,11 @@ export const blockrunCapability = {
|
|
|
233
236
|
const result = await callGateway(url, method, method === 'POST' ? body : undefined, resourceDescription, ctx.abortSignal, timeoutMs);
|
|
234
237
|
// Telemetry — show in the panel Audit tab regardless of success
|
|
235
238
|
try {
|
|
236
|
-
|
|
239
|
+
// `paidUsd` comes from the 402 settlement and is 0 in API-key mode,
|
|
240
|
+
// where the gateway charges without a handshake. Price from the catalog
|
|
241
|
+
// so raw gateway calls still count against --max-spend.
|
|
242
|
+
const charge = resolveCharge({ apiPath: path, settledUsd: result.paidUsd });
|
|
243
|
+
recordUsage(`BlockRun:${path}`, 0, 0, charge.usd, result.latencyMs, false, charge.estimated);
|
|
237
244
|
}
|
|
238
245
|
catch { /* best-effort */ }
|
|
239
246
|
if (!result.ok) {
|