@blockrun/franklin 3.43.1 → 3.45.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 (59) hide show
  1. package/README.md +105 -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 +57 -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 +148 -0
  26. package/dist/payments/auth-mode.js +225 -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 +132 -0
  30. package/dist/payments/price-catalog.js +457 -0
  31. package/dist/phone/client.js +6 -2
  32. package/dist/pricing.js +3 -3
  33. package/dist/proxy/server.js +11 -0
  34. package/dist/router/index.js +2 -1
  35. package/dist/serve/cloud-sync.d.ts +1 -0
  36. package/dist/serve/server.js +10 -3
  37. package/dist/stats/tracker.d.ts +15 -1
  38. package/dist/stats/tracker.js +14 -2
  39. package/dist/tools/blockrun.js +10 -3
  40. package/dist/tools/defillama.d.ts +5 -5
  41. package/dist/tools/defillama.js +19 -13
  42. package/dist/tools/exa.d.ts +1 -1
  43. package/dist/tools/exa.js +43 -21
  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 +16 -4
  49. package/dist/tools/realface.js +14 -8
  50. package/dist/tools/rpc.d.ts +1 -1
  51. package/dist/tools/rpc.js +12 -5
  52. package/dist/tools/surf.js +42 -6
  53. package/dist/tools/videogen.js +4 -2
  54. package/dist/tools/voice.js +6 -4
  55. package/dist/tools/zerox-base.js +4 -2
  56. package/dist/tools/zerox-gasless.js +6 -4
  57. package/dist/trading/providers/blockrun/client.js +20 -7
  58. package/dist/ui/model-picker.js +1 -1
  59. package/package.json +8 -4
@@ -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 },
@@ -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.
@@ -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
  */
@@ -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)
@@ -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, API_URLS, USER_AGENT } from '../config.js';
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 = API_URLS[chain]; // ends in /api
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
- recordUsage(`BlockRun:${path}`, 0, 0, result.paidUsd, result.latencyMs);
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) {
@@ -5,11 +5,11 @@
5
5
  *
6
6
  * Five tools, each filtered + formatted on the way back so we don't dump
7
7
  * 5–10 MB of raw DefiLlama JSON into agent context:
8
- * - DeFiLlamaProtocols $0.005/call — top-N protocols by TVL
9
- * - DeFiLlamaProtocol $0.005/call — single protocol detail
10
- * - DeFiLlamaChains $0.005/call — TVL ranked by chain
11
- * - DeFiLlamaYields $0.005/call — yield pools, filtered + ranked
12
- * - DeFiLlamaPrice $0.001/call — token price lookup
8
+ * - DeFiLlamaProtocols $0.0050/call base (plus a $0.001 settlement fee on a wallet) — top-N protocols by TVL
9
+ * - DeFiLlamaProtocol $0.0050/call base (plus a $0.001 settlement fee on a wallet) — single protocol detail
10
+ * - DeFiLlamaChains $0.0050/call base (plus a $0.001 settlement fee on a wallet) — TVL ranked by chain
11
+ * - DeFiLlamaYields $0.0050/call base (plus a $0.001 settlement fee on a wallet) — yield pools, filtered + ranked
12
+ * - DeFiLlamaPrice $0.0050/call base (plus a $0.001 settlement fee on a wallet) — token price lookup
13
13
  *
14
14
  * DefiLlama is Apache 2.0 / "free for public and commercial use" — the
15
15
  * BlockRun gateway adds metering + (future) caching/reliability layers,
@@ -5,18 +5,20 @@
5
5
  *
6
6
  * Five tools, each filtered + formatted on the way back so we don't dump
7
7
  * 5–10 MB of raw DefiLlama JSON into agent context:
8
- * - DeFiLlamaProtocols $0.005/call — top-N protocols by TVL
9
- * - DeFiLlamaProtocol $0.005/call — single protocol detail
10
- * - DeFiLlamaChains $0.005/call — TVL ranked by chain
11
- * - DeFiLlamaYields $0.005/call — yield pools, filtered + ranked
12
- * - DeFiLlamaPrice $0.001/call — token price lookup
8
+ * - DeFiLlamaProtocols $0.0050/call base (plus a $0.001 settlement fee on a wallet) — top-N protocols by TVL
9
+ * - DeFiLlamaProtocol $0.0050/call base (plus a $0.001 settlement fee on a wallet) — single protocol detail
10
+ * - DeFiLlamaChains $0.0050/call base (plus a $0.001 settlement fee on a wallet) — TVL ranked by chain
11
+ * - DeFiLlamaYields $0.0050/call base (plus a $0.001 settlement fee on a wallet) — yield pools, filtered + ranked
12
+ * - DeFiLlamaPrice $0.0050/call base (plus a $0.001 settlement fee on a wallet) — token price lookup
13
13
  *
14
14
  * DefiLlama is Apache 2.0 / "free for public and commercial use" — the
15
15
  * BlockRun gateway adds metering + (future) caching/reliability layers,
16
16
  * which is what the per-call charge funds.
17
17
  */
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
- import { loadChain, API_URLS, VERSION } from '../config.js';
19
+ import { loadChain, VERSION } from '../config.js';
20
+ import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
21
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
20
22
  import { logger } from '../logger.js';
21
23
  import { recordUsage } from '../stats/tracker.js';
22
24
  import { frameUntrusted } from './untrusted.js';
@@ -24,9 +26,10 @@ const TIMEOUT_MS = 30_000;
24
26
  // ─── Shared GET-with-x402 flow ────────────────────────────────────────────
25
27
  async function getWithPayment(path, ctx) {
26
28
  const chain = loadChain();
27
- const apiUrl = API_URLS[chain];
29
+ const apiUrl = gatewayBase();
28
30
  const endpoint = `${apiUrl}${path}`;
29
31
  const headers = {
32
+ ...gatewayHeaders(),
30
33
  Accept: 'application/json',
31
34
  'User-Agent': `franklin/${VERSION}`,
32
35
  };
@@ -60,8 +63,11 @@ async function getWithPayment(path, ctx) {
60
63
  }
61
64
  // Record the settled x402 spend so DeFiLlama calls show up in franklin
62
65
  // stats / audit AND count against the --max-spend ceiling (parity with surf.ts).
66
+ // See rpc.ts — `paidUsd` is 0 whenever no 402 happened, which is every
67
+ // call in API-key mode.
68
+ const charge = resolveCharge({ apiPath: endpoint, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd });
63
69
  try {
64
- recordUsage(`DeFiLlama:${path}`, 0, 0, paidUsd, Date.now() - startedAt);
70
+ recordUsage(`DeFiLlama:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
65
71
  }
66
72
  catch { /* best-effort */ }
67
73
  return (await response.json());
@@ -143,7 +149,7 @@ export const defiLlamaProtocolsCapability = {
143
149
  name: 'DeFiLlamaProtocols',
144
150
  description: 'Rank DeFi protocols by total value locked (TVL) across all chains, optionally filtered by category, chain, or minimum TVL. ' +
145
151
  'Returns the top-N protocols (default 20), each with TVL, 24h/7d change, chain breakdown, and slug. ' +
146
- 'Uses BlockRun gateway → DefiLlama. $0.005 per call. ' +
152
+ 'Uses BlockRun gateway → DefiLlama. $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. ' +
147
153
  'Categories include: Lending, Liquid Staking, Bridge, Dexes, CDP, Yield, Yield Aggregator, Derivatives, Stablecoins, Insurance, etc.',
148
154
  input_schema: {
149
155
  type: 'object',
@@ -202,7 +208,7 @@ export const defiLlamaProtocolCapability = {
202
208
  description: 'Detailed TVL + chain breakdown for a single DeFi protocol identified by DefiLlama slug ' +
203
209
  '(e.g. "aave", "uniswap", "lido", "jito", "marinade-finance"). ' +
204
210
  'Returns TVL across each chain it operates on, recent change, audits, social. ' +
205
- '$0.005 per call. To find a slug, run DeFiLlamaProtocols first.',
211
+ '$0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. To find a slug, run DeFiLlamaProtocols first.',
206
212
  input_schema: {
207
213
  type: 'object',
208
214
  properties: {
@@ -260,7 +266,7 @@ export const defiLlamaProtocolCapability = {
260
266
  export const defiLlamaChainsCapability = {
261
267
  spec: {
262
268
  name: 'DeFiLlamaChains',
263
- description: 'TVL ranking across every chain DefiLlama tracks. Default returns top 20 by TVL. $0.005 per call.',
269
+ description: 'TVL ranking across every chain DefiLlama tracks. Default returns top 20 by TVL. $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet.',
264
270
  input_schema: {
265
271
  type: 'object',
266
272
  properties: {
@@ -293,7 +299,7 @@ export const defiLlamaYieldsCapability = {
293
299
  spec: {
294
300
  name: 'DeFiLlamaYields',
295
301
  description: 'Search DeFi yield pools (lending, LPs, vaults, staking) by symbol/chain/project, ranked by APY. ' +
296
- 'Returns top-N pools (default 10). $0.005 per call. ' +
302
+ 'Returns top-N pools (default 10). $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. ' +
297
303
  'Default filters: TVL > $1M (avoid microcaps), APY > 0. Override via params. ' +
298
304
  'Use stablecoin_only=true for "where can my USDC earn?" queries.',
299
305
  input_schema: {
@@ -366,7 +372,7 @@ export const defiLlamaYieldsCapability = {
366
372
  export const defiLlamaPriceCapability = {
367
373
  spec: {
368
374
  name: 'DeFiLlamaPrice',
369
- description: 'Token price lookup via DefiLlama (covers thousands of tokens — anything DEX-listed). $0.001 per call. ' +
375
+ description: 'Token price lookup via DefiLlama (covers thousands of tokens — anything DEX-listed). $0.0050 per call base, plus a $0.001 settlement fee when paying from a wallet. ' +
370
376
  'Coin identifier syntax: "{platform}:{address}" or "coingecko:{slug}". ' +
371
377
  'Examples: "coingecko:bitcoin" (BTC USD), "ethereum:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" (WETH), ' +
372
378
  '"solana:So11111111111111111111111111111111111111112" (SOL/wSOL), ' +
@@ -5,7 +5,7 @@
5
5
  * Three tools:
6
6
  * - ExaSearch — semantic search for URLs ($0.01/call)
7
7
  * - ExaAnswer — synthesized answer with citations ($0.01/call)
8
- * - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.002/URL)
8
+ * - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.0030/URL)
9
9
  *
10
10
  * Why these matter for an economic agent: ExaAnswer is Perplexity-in-a-
11
11
  * tool — the agent gets a grounded reply with sources, avoiding the
package/dist/tools/exa.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * Three tools:
6
6
  * - ExaSearch — semantic search for URLs ($0.01/call)
7
7
  * - ExaAnswer — synthesized answer with citations ($0.01/call)
8
- * - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.002/URL)
8
+ * - ExaReadUrls — batch-fetch clean Markdown from URLs ($0.0030/URL)
9
9
  *
10
10
  * Why these matter for an economic agent: ExaAnswer is Perplexity-in-a-
11
11
  * tool — the agent gets a grounded reply with sources, avoiding the
@@ -18,17 +18,20 @@
18
18
  * 402 triggers a signed USDC transfer, retry succeeds.
19
19
  */
20
20
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
21
- import { loadChain, API_URLS, VERSION } from '../config.js';
21
+ import { loadChain, VERSION } from '../config.js';
22
+ import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
23
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
22
24
  import { frameUntrusted } from './untrusted.js';
23
25
  import { recordUsage } from '../stats/tracker.js';
24
26
  import { logger } from '../logger.js';
25
27
  const GEN_TIMEOUT_MS = 30_000;
26
28
  async function postWithPayment(path, body, ctx) {
27
29
  const chain = loadChain();
28
- const apiUrl = API_URLS[chain];
30
+ const apiUrl = gatewayBase();
29
31
  const endpoint = `${apiUrl}${path}`;
30
32
  const bodyStr = JSON.stringify(body);
31
33
  const headers = {
34
+ ...gatewayHeaders(),
32
35
  'Content-Type': 'application/json',
33
36
  'User-Agent': `franklin/${VERSION}`,
34
37
  };
@@ -63,23 +66,42 @@ async function postWithPayment(path, body, ctx) {
63
66
  const errText = await response.text().catch(() => '');
64
67
  throw new Error(`Exa ${path} failed (${response.status}): ${errText.slice(0, 200)}`);
65
68
  }
66
- return { data: (await response.json()), settled, latencyMs: Date.now() - start };
69
+ return {
70
+ data: (await response.json()),
71
+ settled,
72
+ chargedUsd: chargeFromResponse(response),
73
+ latencyMs: Date.now() - start,
74
+ };
67
75
  }
68
76
  finally {
69
77
  clearTimeout(timeout);
70
78
  ctx.abortSignal.removeEventListener('abort', onAbort);
71
79
  }
72
80
  }
73
- // Fold a settled Exa charge into the live-spend accumulator so it counts against
81
+ // Fold an Exa charge into the live-spend accumulator so it counts against
74
82
  // --max-spend and shows in stats — exactly like surf.ts / blockrun.ts. Without
75
- // this, every Exa tool spent real USDC invisibly to the budget ceiling. Use the
76
- // gateway-reported charge when present, else the tool's list price as a floor.
77
- function recordExaSpend(path, settled, reportedUsd, fallbackUsd, latencyMs) {
78
- if (!settled)
79
- return; // free/already-paid (200-first) path — no charge to record
80
- const usd = typeof reportedUsd === 'number' && reportedUsd > 0 ? reportedUsd : fallbackUsd;
83
+ // this, every Exa tool spent real USDC invisibly to the budget ceiling.
84
+ //
85
+ // `settled` is true only when an x402 handshake happened. It is false on two
86
+ // very different paths: a genuinely free 200, and every API-key call, where the
87
+ // gateway charges the prepaid balance without a 402. Exa itself returns
88
+ // `costDollars`, so prefer that; otherwise price from the catalog. Returning
89
+ // early on !settled — as this did before key mode — would record $0 for real
90
+ // spend.
91
+ function recordExaSpend(path, settled, chargedUsd, reportedUsd, fallbackUsd, latencyMs) {
92
+ // `reportedUsd` is Exa's own costDollars — its upstream cost, NOT what
93
+ // BlockRun charged. Measured 2026-09-05: Exa said $0.007 on a call the
94
+ // gateway charged $0.010 for. It is no longer treated as exact anywhere;
95
+ // x-blockrun-cost-usd is the authority when present.
96
+ const charge = chargedUsd !== null
97
+ ? { usd: chargedUsd, estimated: false }
98
+ : settled
99
+ ? { usd: fallbackUsd, estimated: false }
100
+ : resolveCharge({ apiPath: path, reportedUsd, fallbackUsd });
101
+ if (charge.usd <= 0)
102
+ return;
81
103
  try {
82
- recordUsage(`Exa:${path}`, 0, 0, usd, latencyMs);
104
+ recordUsage(`Exa:${path}`, 0, 0, charge.usd, latencyMs, false, charge.estimated);
83
105
  }
84
106
  catch { /* best-effort accounting */ }
85
107
  }
@@ -133,7 +155,7 @@ async function extractPaymentReq(response) {
133
155
  export const exaSearchCapability = {
134
156
  spec: {
135
157
  name: 'ExaSearch',
136
- description: 'Neural web search via Exa ($0.01/call). Returns a ranked list of ' +
158
+ description: 'Neural web search via Exa ($0.0100/call base, plus a $0.001 settlement fee on a wallet). Returns a ranked list of ' +
137
159
  'URLs + titles for a natural-language query. Understands meaning, ' +
138
160
  'not just keywords. Optional `category` narrows to github / news / ' +
139
161
  '`research paper` / tweet / pdf / company / etc. Prefer this over ' +
@@ -162,10 +184,10 @@ export const exaSearchCapability = {
162
184
  if (!params.query)
163
185
  return { output: 'Error: query is required', isError: true };
164
186
  try {
165
- const { data: res, settled, latencyMs } = await postWithPayment('/v1/exa/search', params, ctx);
187
+ const { data: res, settled, chargedUsd, latencyMs } = await postWithPayment('/v1/exa/search', params, ctx);
166
188
  const body = res.data ?? res;
167
189
  const cost = body.costDollars?.total;
168
- recordExaSpend('/v1/exa/search', settled, cost, 0.01, latencyMs);
190
+ recordExaSpend('/v1/exa/search', settled, chargedUsd, cost, 0.01, latencyMs);
169
191
  const hits = body.results ?? [];
170
192
  if (hits.length === 0) {
171
193
  return { output: `No Exa results for "${params.query}".` };
@@ -190,7 +212,7 @@ export const exaAnswerCapability = {
190
212
  spec: {
191
213
  name: 'ExaAnswer',
192
214
  description: "Ask a factual question, get a synthesized answer with real source " +
193
- "citations ($0.01/call). Like Perplexity in a tool — grounded in " +
215
+ "citations ($0.0100/call base, plus a $0.001 settlement fee on a wallet). Like Perplexity in a tool — grounded in " +
194
216
  "live web content, not LLM memory. Best for 'what is X?', 'how does " +
195
217
  "Y work?', 'what's the current state of Z?'. Prefer this over " +
196
218
  "chaining ExaSearch + ExaReadUrls + LLM synthesis when the user " +
@@ -208,10 +230,10 @@ export const exaAnswerCapability = {
208
230
  if (!params.query)
209
231
  return { output: 'Error: query is required', isError: true };
210
232
  try {
211
- const { data: res, settled, latencyMs } = await postWithPayment('/v1/exa/answer', params, ctx);
233
+ const { data: res, settled, chargedUsd, latencyMs } = await postWithPayment('/v1/exa/answer', params, ctx);
212
234
  const body = res.data ?? res;
213
235
  const cost = body.costDollars?.total;
214
- recordExaSpend('/v1/exa/answer', settled, cost, 0.01, latencyMs);
236
+ recordExaSpend('/v1/exa/answer', settled, chargedUsd, cost, 0.01, latencyMs);
215
237
  const ans = body.answer ?? '';
216
238
  const cites = body.citations ?? [];
217
239
  const lines = [ans];
@@ -233,7 +255,7 @@ export const exaAnswerCapability = {
233
255
  export const exaReadUrlsCapability = {
234
256
  spec: {
235
257
  name: 'ExaReadUrls',
236
- description: "Batch-fetch clean Markdown content from a list of URLs ($0.002/URL). " +
258
+ description: "Batch-fetch clean Markdown content from a list of URLs ($0.0020/URL base, plus a $0.001 settlement fee on a wallet). " +
237
259
  "Up to 100 URLs per call. Much cheaper than chaining 100× WebFetch, " +
238
260
  "and returns text already stripped of HTML/boilerplate — ready to " +
239
261
  "feed into an LLM context window. Prefer over WebFetch when reading " +
@@ -259,11 +281,11 @@ export const exaReadUrlsCapability = {
259
281
  return { output: `Error: max 100 URLs per call (got ${params.urls.length})`, isError: true };
260
282
  }
261
283
  try {
262
- const { data: res, settled, latencyMs } = await postWithPayment('/v1/exa/contents', params, ctx);
284
+ const { data: res, settled, chargedUsd, latencyMs } = await postWithPayment('/v1/exa/contents', params, ctx);
263
285
  const body = res.data ?? res;
264
286
  const cost = body.costDollars?.total;
265
287
  // $0.002/URL list price as the floor when the gateway omits costDollars.
266
- recordExaSpend('/v1/exa/contents', settled, cost, 0.002 * params.urls.length, latencyMs);
288
+ recordExaSpend('/v1/exa/contents', settled, chargedUsd, cost, 0.002 * params.urls.length, latencyMs);
267
289
  const results = body.results ?? [];
268
290
  if (results.length === 0) {
269
291
  return { output: `No readable content returned for the ${params.urls.length} URL(s).` };
@@ -5,7 +5,8 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
8
- import { loadChain, API_URLS, VERSION } from '../config.js';
8
+ import { loadChain, VERSION } from '../config.js';
9
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
9
10
  import { checkImageBudget, recordImageAsset } from '../content/record-image.js';
10
11
  import { estimateImageCostUsd } from '../content/image-pricing.js';
11
12
  import { recordUsage } from '../stats/tracker.js';
@@ -288,7 +289,7 @@ function buildExecute(deps) {
288
289
  }
289
290
  }
290
291
  const chain = loadChain();
291
- const apiUrl = API_URLS[chain];
292
+ const apiUrl = gatewayBase();
292
293
  // Reference-image mode hits the dedicated /v1/images/image2image endpoint;
293
294
  // otherwise stay on text-to-image generations.
294
295
  const endpoint = editMode
@@ -323,6 +324,7 @@ function buildExecute(deps) {
323
324
  response_format: 'b64_json',
324
325
  });
325
326
  const headers = {
327
+ ...gatewayHeaders(),
326
328
  'Content-Type': 'application/json',
327
329
  'User-Agent': `franklin/${VERSION}`,
328
330
  };
@@ -26,7 +26,8 @@
26
26
  * the SessionSandboxTracker registry.
27
27
  */
28
28
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
29
- import { loadChain, API_URLS, VERSION } from '../config.js';
29
+ import { loadChain, VERSION } from '../config.js';
30
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
30
31
  import { walletReservation, AMBIGUOUS_GRACE_MS } from '../wallet/reservation.js';
31
32
  import { recordUsage } from '../stats/tracker.js';
32
33
  import { logger } from '../logger.js';
@@ -137,6 +138,7 @@ async function extractPaymentReq(response) {
137
138
  export async function postWithPayment(endpoint, body, resourceDescription, abortSignal, timeoutMs, reservation) {
138
139
  const chain = loadChain();
139
140
  const headers = {
141
+ ...gatewayHeaders(),
140
142
  'Content-Type': 'application/json',
141
143
  'User-Agent': `franklin/${VERSION}`,
142
144
  };
@@ -237,7 +239,7 @@ function definitelyNotSent(err) {
237
239
  }
238
240
  function modalEndpoint(path) {
239
241
  const chain = loadChain();
240
- return `${API_URLS[chain]}/v1/modal/sandbox/${path}`;
242
+ return `${gatewayBase()}/v1/modal/sandbox/${path}`;
241
243
  }
242
244
  /**
243
245
  * Normalize the agent's `command` input into the execve-style array Modal
@@ -16,7 +16,8 @@
16
16
  import fs from 'node:fs';
17
17
  import path from 'node:path';
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
- import { loadChain, API_URLS, VERSION } from '../config.js';
19
+ import { loadChain, VERSION } from '../config.js';
20
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
20
21
  import { logger } from '../logger.js';
21
22
  import { isWalletKeyPath } from './sensitive-paths.js';
22
23
  import { findModel, estimateCostUsd } from '../gateway-models.js';
@@ -76,7 +77,7 @@ function buildExecute(deps) {
76
77
  }
77
78
  }
78
79
  const chain = loadChain();
79
- const apiUrl = API_URLS[chain];
80
+ const apiUrl = gatewayBase();
80
81
  const endpoint = `${apiUrl}/v1/audio/generations`;
81
82
  const outPath = output_path
82
83
  ? (path.isAbsolute(output_path) ? output_path : path.resolve(ctx.workingDir, output_path))
@@ -93,6 +94,7 @@ function buildExecute(deps) {
93
94
  ...(duration_seconds ? { duration_seconds } : {}),
94
95
  });
95
96
  const headers = {
97
+ ...gatewayHeaders(),
96
98
  'Content-Type': 'application/json',
97
99
  'User-Agent': `franklin/${VERSION}`,
98
100
  };
@@ -12,17 +12,19 @@
12
12
  * a signed USDC transfer (Base or Solana), retry succeeds.
13
13
  */
14
14
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
15
- import { loadChain, API_URLS, VERSION } from '../config.js';
15
+ import { loadChain, VERSION } from '../config.js';
16
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
16
17
  import { logger } from '../logger.js';
17
18
  import { recordUsage } from '../stats/tracker.js';
18
19
  const PHONE_TIMEOUT_MS = 30_000;
19
20
  async function postWithPayment(path, body, ctx, meta) {
20
21
  const startMs = Date.now();
21
22
  const chain = loadChain();
22
- const apiUrl = API_URLS[chain];
23
+ const apiUrl = gatewayBase();
23
24
  const endpoint = `${apiUrl}${path}`;
24
25
  const bodyStr = JSON.stringify(body);
25
26
  const headers = {
27
+ ...gatewayHeaders(),
26
28
  'Content-Type': 'application/json',
27
29
  'User-Agent': `franklin/${VERSION}`,
28
30
  };