@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
@@ -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) {
@@ -16,7 +16,9 @@
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 { 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, 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());
package/dist/tools/exa.js CHANGED
@@ -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 { 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
  };
@@ -70,16 +73,26 @@ async function postWithPayment(path, body, ctx) {
70
73
  ctx.abortSignal.removeEventListener('abort', onAbort);
71
74
  }
72
75
  }
73
- // Fold a settled Exa charge into the live-spend accumulator so it counts against
76
+ // Fold an Exa charge into the live-spend accumulator so it counts against
74
77
  // --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.
78
+ // this, every Exa tool spent real USDC invisibly to the budget ceiling.
79
+ //
80
+ // `settled` is true only when an x402 handshake happened. It is false on two
81
+ // very different paths: a genuinely free 200, and every API-key call, where the
82
+ // gateway charges the prepaid balance without a 402. Exa itself returns
83
+ // `costDollars`, so prefer that; otherwise price from the catalog. Returning
84
+ // early on !settled — as this did before key mode — would record $0 for real
85
+ // spend.
77
86
  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;
87
+ const charge = settled
88
+ // Settled through x402: the gateway-reported charge, else the list price.
89
+ // Either way it reflects money that demonstrably moved.
90
+ ? { usd: reportedUsd && reportedUsd > 0 ? reportedUsd : fallbackUsd, estimated: false }
91
+ : resolveCharge({ apiPath: path, reportedUsd, fallbackUsd });
92
+ if (charge.usd <= 0)
93
+ return;
81
94
  try {
82
- recordUsage(`Exa:${path}`, 0, 0, usd, latencyMs);
95
+ recordUsage(`Exa:${path}`, 0, 0, charge.usd, latencyMs, false, charge.estimated);
83
96
  }
84
97
  catch { /* best-effort accounting */ }
85
98
  }
@@ -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
  };
@@ -36,7 +36,9 @@
36
36
  * need more should narrow the search.
37
37
  */
38
38
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
39
- import { loadChain, API_URLS, VERSION } from '../config.js';
39
+ import { loadChain, VERSION } from '../config.js';
40
+ import { resolveCharge } from '../payments/price-catalog.js';
41
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
40
42
  import { logger } from '../logger.js';
41
43
  import { recordFetch } from '../trading/providers/telemetry.js';
42
44
  import { recordUsage } from '../stats/tracker.js';
@@ -67,7 +69,7 @@ function priceForPath(path) {
67
69
  // ─── Shared GET-with-x402 flow ────────────────────────────────────────────
68
70
  async function getWithPayment(path, query, ctx) {
69
71
  const chain = loadChain();
70
- const apiUrl = API_URLS[chain];
72
+ const apiUrl = gatewayBase();
71
73
  const qs = new URLSearchParams();
72
74
  for (const [k, v] of Object.entries(query)) {
73
75
  if (v == null || v === '')
@@ -77,6 +79,7 @@ async function getWithPayment(path, query, ctx) {
77
79
  const queryStr = qs.toString();
78
80
  const endpoint = `${apiUrl}${path}${queryStr ? `?${queryStr}` : ''}`;
79
81
  const headers = {
82
+ ...gatewayHeaders(),
80
83
  Accept: 'application/json',
81
84
  'User-Agent': `franklin/${VERSION}`,
82
85
  };
@@ -108,18 +111,26 @@ async function getWithPayment(path, query, ctx) {
108
111
  recordFetch({ provider: 'blockrun', endpoint: path, ok: false, latencyMs: Date.now() - startedAt });
109
112
  throw new Error(`PredictionMarket ${path} failed (${response.status}): ${errText.slice(0, 600)}`);
110
113
  }
114
+ // `costRecorded` is only set on the post-402 settlement, so it is 0 for
115
+ // every call in API-key mode, where the gateway charges silently. Fall back
116
+ // to this module's own price table, then to the published catalog.
117
+ const charge = resolveCharge({
118
+ apiPath: endpoint,
119
+ settledUsd: costRecorded,
120
+ fallbackUsd: priceForPath(path),
121
+ });
111
122
  recordFetch({
112
123
  provider: 'blockrun',
113
124
  endpoint: path,
114
125
  ok: true,
115
126
  latencyMs: Date.now() - startedAt,
116
- costUsd: costRecorded > 0 ? costRecorded : undefined,
127
+ costUsd: charge.usd > 0 ? charge.usd : undefined,
117
128
  });
118
129
  // ALSO persist to franklin-stats (recordFetch is in-memory only, lost on
119
130
  // restart). Without this, Predexon spend is absent from `franklin stats`
120
131
  // and invisible to the --max-spend ceiling (parity with surf.ts).
121
132
  try {
122
- recordUsage(`PredictionMarket:${path}`, 0, 0, costRecorded, Date.now() - startedAt);
133
+ recordUsage(`PredictionMarket:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
123
134
  }
124
135
  catch { /* best-effort */ }
125
136
  return (await response.json());
@@ -26,7 +26,9 @@
26
26
  * per the same rationale documented there — a shared module is out of scope).
27
27
  */
28
28
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
29
- import { loadChain, API_URLS, USER_AGENT } from '../config.js';
29
+ import { loadChain, USER_AGENT } from '../config.js';
30
+ import { resolveCharge } from '../payments/price-catalog.js';
31
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
30
32
  import { recordUsage } from '../stats/tracker.js';
31
33
  import { logger } from '../logger.js';
32
34
  const REQUEST_TIMEOUT_MS = 60_000;
@@ -113,7 +115,7 @@ async function actionInit(base, input, ctx) {
113
115
  const body = JSON.stringify(groupId ? { name, groupId } : { name });
114
116
  const res = await timedFetch(`${base}/v1/realface/init`, {
115
117
  method: 'POST',
116
- headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': USER_AGENT },
118
+ headers: { ...gatewayHeaders(), 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': USER_AGENT },
117
119
  body,
118
120
  }, ctx);
119
121
  const raw = await res.text().catch(() => '');
@@ -139,7 +141,7 @@ async function actionStatus(base, input, ctx) {
139
141
  break;
140
142
  const res = await timedFetch(`${base}/v1/realface/status?groupId=${encodeURIComponent(groupId)}`, {
141
143
  method: 'GET',
142
- headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
144
+ headers: { ...gatewayHeaders(), Accept: 'application/json', 'User-Agent': USER_AGENT },
143
145
  }, ctx);
144
146
  raw = await res.text().catch(() => '');
145
147
  if (!res.ok)
@@ -173,7 +175,7 @@ async function actionEnroll(base, chain, input, ctx) {
173
175
  }
174
176
  const url = `${base}/v1/realface/enroll`;
175
177
  const body = JSON.stringify({ name, image_url: imageUrl, group_id: groupId });
176
- const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': USER_AGENT };
178
+ const headers = { ...gatewayHeaders(), 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': USER_AGENT };
177
179
  const start = Date.now();
178
180
  let res = await timedFetch(url, { method: 'POST', headers, body }, ctx);
179
181
  let paidUsd = 0;
@@ -187,8 +189,12 @@ async function actionEnroll(base, chain, input, ctx) {
187
189
  const raw = await res.text().catch(() => '');
188
190
  if (!res.ok)
189
191
  paidUsd = 0;
192
+ // 0 whenever no 402 was settled, which is every call in API-key mode.
193
+ const charge = res.ok
194
+ ? resolveCharge({ apiPath: url, settledUsd: paidUsd })
195
+ : { usd: 0, estimated: false };
190
196
  try {
191
- recordUsage('RealFace:enroll', 0, 0, paidUsd, Date.now() - start);
197
+ recordUsage('RealFace:enroll', 0, 0, charge.usd, Date.now() - start, false, charge.estimated);
192
198
  }
193
199
  catch { /* best-effort */ }
194
200
  if (res.status === 425) {
@@ -201,7 +207,7 @@ async function actionEnroll(base, chain, input, ctx) {
201
207
  return { output: `RealFace enroll failed (status ${res.status}). No charge if 4xx pre-payment.\n${raw.slice(0, 600)}`, isError: true };
202
208
  }
203
209
  return {
204
- output: `RealFace enrolled → $${paidUsd.toFixed(4)} · ${Date.now() - start}ms. ` +
210
+ output: `RealFace enrolled → $${charge.usd.toFixed(4)} · ${Date.now() - start}ms. ` +
205
211
  `Use the returned \`asset_id\` (ta_xxx) as \`real_face_asset_id\` on a VideoGen call with ` +
206
212
  `bytedance/seedance-2.0 or -fast for a real-person clip.${fence(raw)}`,
207
213
  };
@@ -210,7 +216,7 @@ async function actionList(base, chain, ctx) {
210
216
  const addr = await walletAddress(chain);
211
217
  const res = await timedFetch(`${base}/v1/wallet/${addr}/realfaces`, {
212
218
  method: 'GET',
213
- headers: { Accept: 'application/json', 'User-Agent': USER_AGENT },
219
+ headers: { ...gatewayHeaders(), Accept: 'application/json', 'User-Agent': USER_AGENT },
214
220
  }, ctx);
215
221
  const raw = await res.text().catch(() => '');
216
222
  if (!res.ok)
@@ -220,7 +226,7 @@ async function actionList(base, chain, ctx) {
220
226
  async function execute(input, ctx) {
221
227
  const action = typeof input.action === 'string' ? input.action.trim() : '';
222
228
  const chain = loadChain();
223
- const base = API_URLS[chain]; // ends in /api
229
+ const base = gatewayBase(); // wallet host ends in /api; the key host does not
224
230
  switch (action) {
225
231
  case 'init': return actionInit(base, input, ctx);
226
232
  case 'status': return actionStatus(base, input, ctx);
package/dist/tools/rpc.js CHANGED
@@ -17,7 +17,9 @@
17
17
  * depend on the SDK's RpcClient, so it works on the pinned @blockrun/llm 2.x.
18
18
  */
19
19
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
20
- import { loadChain, API_URLS, VERSION } from '../config.js';
20
+ import { loadChain, VERSION } from '../config.js';
21
+ import { resolveCharge } from '../payments/price-catalog.js';
22
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
21
23
  import { logger } from '../logger.js';
22
24
  import { recordUsage } from '../stats/tracker.js';
23
25
  const TIMEOUT_MS = 30_000;
@@ -46,10 +48,11 @@ const WRITE_METHODS = new Set([
46
48
  ].map((m) => m.toLowerCase()));
47
49
  async function postRpcWithPayment(network, jsonRpcBody, ctx) {
48
50
  const chain = loadChain();
49
- const apiUrl = API_URLS[chain];
51
+ const apiUrl = gatewayBase();
50
52
  const endpoint = `${apiUrl}/v1/rpc/${network}`;
51
53
  const bodyStr = JSON.stringify(jsonRpcBody);
52
54
  const headers = {
55
+ ...gatewayHeaders(),
53
56
  'Content-Type': 'application/json',
54
57
  Accept: 'application/json',
55
58
  'User-Agent': `franklin/${VERSION}`,
@@ -86,8 +89,12 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
86
89
  }
87
90
  // Record the settled x402 spend so RPC calls show up in franklin stats /
88
91
  // audit AND count against the --max-spend ceiling (parity with surf.ts).
92
+ // `paidUsd` is only ever set by the 402 branch, so in API-key mode — where
93
+ // the gateway settles silently and never sends a 402 — it stays 0. Price the
94
+ // call from the published catalog instead of recording a free call.
95
+ const charge = resolveCharge({ apiPath: endpoint, settledUsd: paidUsd });
89
96
  try {
90
- recordUsage(`MultiChainRPC:${network}`, 0, 0, paidUsd, Date.now() - startedAt);
97
+ recordUsage(`MultiChainRPC:${network}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
91
98
  }
92
99
  catch { /* best-effort */ }
93
100
  return {
@@ -16,7 +16,9 @@
16
16
  * rationale documented there — refactoring into a shared module is out of scope).
17
17
  */
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
- import { loadChain, API_URLS, USER_AGENT } from '../config.js';
19
+ import { loadChain, USER_AGENT } from '../config.js';
20
+ import { resolveCharge } from '../payments/price-catalog.js';
21
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
20
22
  import { frameUntrusted } from './untrusted.js';
21
23
  import { recordUsage } from '../stats/tracker.js';
22
24
  import { logger } from '../logger.js';
@@ -166,7 +168,7 @@ async function callSurf(toolName, table, input, ctx) {
166
168
  };
167
169
  }
168
170
  const chain = loadChain();
169
- const base = API_URLS[chain]; // ends in /api
171
+ const base = gatewayBase(); // wallet host ends in /api; the key host does not
170
172
  let url = `${base}/v1/surf/${entry.path}`;
171
173
  const body = entry.method === 'POST'
172
174
  ? (input.body && typeof input.body === 'object' ? input.body : query)
@@ -187,7 +189,7 @@ async function callSurf(toolName, table, input, ctx) {
187
189
  const onAbort = () => ctrl.abort();
188
190
  ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
189
191
  const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
190
- const headers = { Accept: 'application/json', 'User-Agent': USER_AGENT };
192
+ const headers = { ...gatewayHeaders(), Accept: 'application/json', 'User-Agent': USER_AGENT };
191
193
  if (entry.method === 'POST')
192
194
  headers['Content-Type'] = 'application/json';
193
195
  const payload = body !== undefined ? JSON.stringify(body) : undefined;
@@ -208,8 +210,14 @@ async function callSurf(toolName, table, input, ctx) {
208
210
  if (!response.ok)
209
211
  paidUsd = 0;
210
212
  const raw = await response.text().catch(() => '');
213
+ // `paidUsd` is 0 unless a 402 was settled — i.e. always 0 in API-key mode.
214
+ // Fall back to the catalog price so Surf spend still counts against
215
+ // --max-spend and shows in stats.
216
+ const charge = response.ok
217
+ ? resolveCharge({ apiPath: url, settledUsd: paidUsd })
218
+ : { usd: 0, estimated: false };
211
219
  try {
212
- recordUsage(`${toolName}:${entry.path}`, 0, 0, paidUsd, Date.now() - start);
220
+ recordUsage(`${toolName}:${entry.path}`, 0, 0, charge.usd, Date.now() - start, false, charge.estimated);
213
221
  }
214
222
  catch { /* best-effort */ }
215
223
  if (!response.ok) {
@@ -22,7 +22,8 @@
22
22
  import fs from 'node:fs';
23
23
  import path from 'node:path';
24
24
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
25
- import { loadChain, API_URLS, VERSION } from '../config.js';
25
+ import { loadChain, VERSION } from '../config.js';
26
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
26
27
  import { logger } from '../logger.js';
27
28
  import { resolveReferenceImage } from './imagegen.js';
28
29
  import { isWalletKeyPath } from './sensitive-paths.js';
@@ -161,7 +162,7 @@ function buildExecute(deps) {
161
162
  }
162
163
  }
163
164
  const chain = loadChain();
164
- const apiUrl = API_URLS[chain];
165
+ const apiUrl = gatewayBase();
165
166
  const endpoint = `${apiUrl}/v1/videos/generations`;
166
167
  const outPath = output_path
167
168
  ? (path.isAbsolute(output_path) ? output_path : path.resolve(ctx.workingDir, output_path))
@@ -187,6 +188,7 @@ function buildExecute(deps) {
187
188
  ...(real_face_asset_id ? { real_face_asset_id } : {}),
188
189
  });
189
190
  const headers = {
191
+ ...gatewayHeaders(),
190
192
  'Content-Type': 'application/json',
191
193
  'User-Agent': `franklin/${VERSION}`,
192
194
  };
@@ -15,7 +15,8 @@
15
15
  * x402 payment flow mirrors src/tools/exa.ts.
16
16
  */
17
17
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
18
- import { loadChain, API_URLS, VERSION } from '../config.js';
18
+ import { loadChain, VERSION } from '../config.js';
19
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
19
20
  import { logger } from '../logger.js';
20
21
  import { recordUsage } from '../stats/tracker.js';
21
22
  import { frameUntrusted } from './untrusted.js';
@@ -57,10 +58,11 @@ const VOICE_TIMEOUT_MS = 30_000;
57
58
  async function postWithPayment(path, body, ctx, meta) {
58
59
  const startMs = Date.now();
59
60
  const chain = loadChain();
60
- const apiUrl = API_URLS[chain];
61
+ const apiUrl = gatewayBase();
61
62
  const endpoint = `${apiUrl}${path}`;
62
63
  const bodyStr = JSON.stringify(body);
63
64
  const headers = {
65
+ ...gatewayHeaders(),
64
66
  'Content-Type': 'application/json',
65
67
  'User-Agent': `franklin/${VERSION}`,
66
68
  };
@@ -107,7 +109,7 @@ async function postWithPayment(path, body, ctx, meta) {
107
109
  async function getNoPayment(path, ctx, meta, record = true) {
108
110
  const startMs = Date.now();
109
111
  const chain = loadChain();
110
- const apiUrl = API_URLS[chain];
112
+ const apiUrl = gatewayBase();
111
113
  const endpoint = `${apiUrl}${path}`;
112
114
  const controller = new AbortController();
113
115
  const timeout = setTimeout(() => controller.abort(), VOICE_TIMEOUT_MS);
@@ -117,7 +119,7 @@ async function getNoPayment(path, ctx, meta, record = true) {
117
119
  const resp = await fetch(endpoint, {
118
120
  method: 'GET',
119
121
  signal: controller.signal,
120
- headers: { 'User-Agent': `franklin/${VERSION}` },
122
+ headers: { ...gatewayHeaders(), 'User-Agent': `franklin/${VERSION}` },
121
123
  });
122
124
  if (!resp.ok) {
123
125
  const errText = await resp.text().catch(() => '');
@@ -26,7 +26,8 @@ import { privateKeyToAccount } from 'viem/accounts';
26
26
  import { base } from 'viem/chains';
27
27
  import { getOrCreateWallet } from '@blockrun/llm';
28
28
  import { loadConfig } from '../commands/config.js';
29
- import { loadChain, API_URLS, VERSION } from '../config.js';
29
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
30
+ import { loadChain, VERSION } from '../config.js';
30
31
  import { appendSwap } from '../stats/swap-log.js';
31
32
  // ─── BlockRun affiliate identity on Base ─────────────────────────────────
32
33
  // Reuses the existing BlockRun ops wallet that already receives x402
@@ -150,9 +151,10 @@ function makeClient(account) {
150
151
  // ─── 0x calls via BlockRun gateway (free public passthrough) ─────────────
151
152
  async function gatewayGet(path, params, ctx) {
152
153
  const chain = loadChain();
153
- const apiUrl = API_URLS[chain];
154
+ const apiUrl = gatewayBase();
154
155
  const endpoint = `${apiUrl}${ZEROX_GATEWAY_PATH}/${path}?${params.toString()}`;
155
156
  const headers = {
157
+ ...gatewayHeaders(),
156
158
  Accept: 'application/json',
157
159
  'User-Agent': `franklin/${VERSION}`,
158
160
  };
@@ -23,7 +23,8 @@ import { base } from 'viem/chains';
23
23
  import { createWalletClient, http, publicActions } from 'viem';
24
24
  import { getOrCreateWallet } from '@blockrun/llm';
25
25
  import { loadConfig } from '../commands/config.js';
26
- import { loadChain, API_URLS, VERSION } from '../config.js';
26
+ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
27
+ import { VERSION } from '../config.js';
27
28
  import { appendSwap } from '../stats/swap-log.js';
28
29
  import { logger } from '../logger.js';
29
30
  // ─── Constants ────────────────────────────────────────────────────────────
@@ -145,7 +146,7 @@ function makeClient(account) {
145
146
  }).extend(publicActions);
146
147
  }
147
148
  async function gatewayGet(pathSuffix, query, timeoutMs, ctx) {
148
- const apiUrl = API_URLS[loadChain()];
149
+ const apiUrl = gatewayBase();
149
150
  const url = `${apiUrl}${ZEROX_GATEWAY_PATH}/${pathSuffix}?${query.toString()}`;
150
151
  const controller = new AbortController();
151
152
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -154,7 +155,7 @@ async function gatewayGet(pathSuffix, query, timeoutMs, ctx) {
154
155
  try {
155
156
  const res = await fetch(url, {
156
157
  method: 'GET',
157
- headers: { Accept: 'application/json', 'User-Agent': `franklin/${VERSION}` },
158
+ headers: { ...gatewayHeaders(), Accept: 'application/json', 'User-Agent': `franklin/${VERSION}` },
158
159
  signal: controller.signal,
159
160
  });
160
161
  if (!res.ok) {
@@ -169,7 +170,7 @@ async function gatewayGet(pathSuffix, query, timeoutMs, ctx) {
169
170
  }
170
171
  }
171
172
  async function gatewayPost(pathSuffix, body, timeoutMs, ctx) {
172
- const apiUrl = API_URLS[loadChain()];
173
+ const apiUrl = gatewayBase();
173
174
  const url = `${apiUrl}${ZEROX_GATEWAY_PATH}/${pathSuffix}`;
174
175
  const controller = new AbortController();
175
176
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -179,6 +180,7 @@ async function gatewayPost(pathSuffix, body, timeoutMs, ctx) {
179
180
  const res = await fetch(url, {
180
181
  method: 'POST',
181
182
  headers: {
183
+ ...gatewayHeaders(),
182
184
  Accept: 'application/json',
183
185
  'Content-Type': 'application/json',
184
186
  'User-Agent': `franklin/${VERSION}`,