@blockrun/franklin 3.44.0 → 3.46.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 (54) hide show
  1. package/README.md +36 -24
  2. package/dist/agent/context.js +58 -10
  3. package/dist/agent/llm.js +14 -6
  4. package/dist/agent/loop.js +34 -6
  5. package/dist/agent/optimize.d.ts +1 -1
  6. package/dist/agent/optimize.js +17 -7
  7. package/dist/agent/secret-redact.d.ts +26 -0
  8. package/dist/agent/secret-redact.js +48 -0
  9. package/dist/agent/streaming-executor.js +15 -0
  10. package/dist/commands/balance.js +37 -5
  11. package/dist/commands/doctor.js +18 -0
  12. package/dist/commands/usage.d.ts +14 -0
  13. package/dist/commands/usage.js +86 -0
  14. package/dist/commands/wallet-adopt.d.ts +12 -0
  15. package/dist/commands/wallet-adopt.js +49 -0
  16. package/dist/index.js +16 -0
  17. package/dist/payments/account.d.ts +17 -0
  18. package/dist/payments/account.js +105 -0
  19. package/dist/payments/auth-mode.d.ts +39 -19
  20. package/dist/payments/auth-mode.js +54 -17
  21. package/dist/payments/billing-copy.d.ts +37 -0
  22. package/dist/payments/billing-copy.js +57 -0
  23. package/dist/payments/post-with-payment.js +8 -15
  24. package/dist/payments/price-catalog.d.ts +70 -0
  25. package/dist/payments/price-catalog.js +154 -6
  26. package/dist/payments/usage.d.ts +106 -0
  27. package/dist/payments/usage.js +168 -0
  28. package/dist/stats/tracker.d.ts +9 -1
  29. package/dist/stats/tracker.js +6 -1
  30. package/dist/tools/bash.js +17 -7
  31. package/dist/tools/blockrun.js +1 -1
  32. package/dist/tools/defillama.d.ts +5 -5
  33. package/dist/tools/defillama.js +13 -13
  34. package/dist/tools/exa.d.ts +1 -1
  35. package/dist/tools/exa.js +27 -18
  36. package/dist/tools/imagegen.js +5 -4
  37. package/dist/tools/modal.js +12 -6
  38. package/dist/tools/musicgen.js +4 -3
  39. package/dist/tools/phone.js +16 -15
  40. package/dist/tools/prediction.js +13 -11
  41. package/dist/tools/realface.js +3 -3
  42. package/dist/tools/rpc.d.ts +1 -1
  43. package/dist/tools/rpc.js +5 -5
  44. package/dist/tools/sensitive-paths.d.ts +1 -1
  45. package/dist/tools/sensitive-paths.js +13 -4
  46. package/dist/tools/surf.js +33 -5
  47. package/dist/tools/videogen.js +6 -5
  48. package/dist/tools/voice.d.ts +1 -1
  49. package/dist/tools/voice.js +5 -4
  50. package/dist/wallet/reservation.d.ts +24 -0
  51. package/dist/wallet/reservation.js +50 -4
  52. package/dist/wallet/solana-migration.d.ts +48 -0
  53. package/dist/wallet/solana-migration.js +81 -0
  54. package/package.json +2 -2
@@ -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,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,
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
19
  import { loadChain, VERSION } from '../config.js';
20
- import { resolveCharge } from '../payments/price-catalog.js';
20
+ import { chargeFromResponse, requestIdFromResponse, resolveCharge } from '../payments/price-catalog.js';
21
21
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
22
22
  import { logger } from '../logger.js';
23
23
  import { recordUsage } from '../stats/tracker.js';
@@ -65,9 +65,9 @@ async function getWithPayment(path, ctx) {
65
65
  // stats / audit AND count against the --max-spend ceiling (parity with surf.ts).
66
66
  // See rpc.ts — `paidUsd` is 0 whenever no 402 happened, which is every
67
67
  // call in API-key mode.
68
- const charge = resolveCharge({ apiPath: endpoint, settledUsd: paidUsd });
68
+ const charge = resolveCharge({ apiPath: endpoint, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd });
69
69
  try {
70
- recordUsage(`DeFiLlama:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
70
+ recordUsage(`DeFiLlama:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated, requestIdFromResponse(response));
71
71
  }
72
72
  catch { /* best-effort */ }
73
73
  return (await response.json());
@@ -149,7 +149,7 @@ export const defiLlamaProtocolsCapability = {
149
149
  name: 'DeFiLlamaProtocols',
150
150
  description: 'Rank DeFi protocols by total value locked (TVL) across all chains, optionally filtered by category, chain, or minimum TVL. ' +
151
151
  'Returns the top-N protocols (default 20), each with TVL, 24h/7d change, chain breakdown, and slug. ' +
152
- '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. ' +
153
153
  'Categories include: Lending, Liquid Staking, Bridge, Dexes, CDP, Yield, Yield Aggregator, Derivatives, Stablecoins, Insurance, etc.',
154
154
  input_schema: {
155
155
  type: 'object',
@@ -208,7 +208,7 @@ export const defiLlamaProtocolCapability = {
208
208
  description: 'Detailed TVL + chain breakdown for a single DeFi protocol identified by DefiLlama slug ' +
209
209
  '(e.g. "aave", "uniswap", "lido", "jito", "marinade-finance"). ' +
210
210
  'Returns TVL across each chain it operates on, recent change, audits, social. ' +
211
- '$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.',
212
212
  input_schema: {
213
213
  type: 'object',
214
214
  properties: {
@@ -266,7 +266,7 @@ export const defiLlamaProtocolCapability = {
266
266
  export const defiLlamaChainsCapability = {
267
267
  spec: {
268
268
  name: 'DeFiLlamaChains',
269
- 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.',
270
270
  input_schema: {
271
271
  type: 'object',
272
272
  properties: {
@@ -299,7 +299,7 @@ export const defiLlamaYieldsCapability = {
299
299
  spec: {
300
300
  name: 'DeFiLlamaYields',
301
301
  description: 'Search DeFi yield pools (lending, LPs, vaults, staking) by symbol/chain/project, ranked by APY. ' +
302
- '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. ' +
303
303
  'Default filters: TVL > $1M (avoid microcaps), APY > 0. Override via params. ' +
304
304
  'Use stablecoin_only=true for "where can my USDC earn?" queries.',
305
305
  input_schema: {
@@ -372,7 +372,7 @@ export const defiLlamaYieldsCapability = {
372
372
  export const defiLlamaPriceCapability = {
373
373
  spec: {
374
374
  name: 'DeFiLlamaPrice',
375
- 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. ' +
376
376
  'Coin identifier syntax: "{platform}:{address}" or "coingecko:{slug}". ' +
377
377
  'Examples: "coingecko:bitcoin" (BTC USD), "ethereum:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" (WETH), ' +
378
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
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
21
21
  import { loadChain, VERSION } from '../config.js';
22
- import { resolveCharge } from '../payments/price-catalog.js';
22
+ import { chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
23
23
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
24
24
  import { frameUntrusted } from './untrusted.js';
25
25
  import { recordUsage } from '../stats/tracker.js';
@@ -66,7 +66,12 @@ async function postWithPayment(path, body, ctx) {
66
66
  const errText = await response.text().catch(() => '');
67
67
  throw new Error(`Exa ${path} failed (${response.status}): ${errText.slice(0, 200)}`);
68
68
  }
69
- 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
+ };
70
75
  }
71
76
  finally {
72
77
  clearTimeout(timeout);
@@ -83,12 +88,16 @@ async function postWithPayment(path, body, ctx) {
83
88
  // `costDollars`, so prefer that; otherwise price from the catalog. Returning
84
89
  // early on !settled — as this did before key mode — would record $0 for real
85
90
  // spend.
86
- function recordExaSpend(path, settled, reportedUsd, fallbackUsd, latencyMs) {
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 });
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 });
92
101
  if (charge.usd <= 0)
93
102
  return;
94
103
  try {
@@ -146,7 +155,7 @@ async function extractPaymentReq(response) {
146
155
  export const exaSearchCapability = {
147
156
  spec: {
148
157
  name: 'ExaSearch',
149
- 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 ' +
150
159
  'URLs + titles for a natural-language query. Understands meaning, ' +
151
160
  'not just keywords. Optional `category` narrows to github / news / ' +
152
161
  '`research paper` / tweet / pdf / company / etc. Prefer this over ' +
@@ -175,10 +184,10 @@ export const exaSearchCapability = {
175
184
  if (!params.query)
176
185
  return { output: 'Error: query is required', isError: true };
177
186
  try {
178
- 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);
179
188
  const body = res.data ?? res;
180
189
  const cost = body.costDollars?.total;
181
- recordExaSpend('/v1/exa/search', settled, cost, 0.01, latencyMs);
190
+ recordExaSpend('/v1/exa/search', settled, chargedUsd, cost, 0.01, latencyMs);
182
191
  const hits = body.results ?? [];
183
192
  if (hits.length === 0) {
184
193
  return { output: `No Exa results for "${params.query}".` };
@@ -203,7 +212,7 @@ export const exaAnswerCapability = {
203
212
  spec: {
204
213
  name: 'ExaAnswer',
205
214
  description: "Ask a factual question, get a synthesized answer with real source " +
206
- "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 " +
207
216
  "live web content, not LLM memory. Best for 'what is X?', 'how does " +
208
217
  "Y work?', 'what's the current state of Z?'. Prefer this over " +
209
218
  "chaining ExaSearch + ExaReadUrls + LLM synthesis when the user " +
@@ -221,10 +230,10 @@ export const exaAnswerCapability = {
221
230
  if (!params.query)
222
231
  return { output: 'Error: query is required', isError: true };
223
232
  try {
224
- 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);
225
234
  const body = res.data ?? res;
226
235
  const cost = body.costDollars?.total;
227
- recordExaSpend('/v1/exa/answer', settled, cost, 0.01, latencyMs);
236
+ recordExaSpend('/v1/exa/answer', settled, chargedUsd, cost, 0.01, latencyMs);
228
237
  const ans = body.answer ?? '';
229
238
  const cites = body.citations ?? [];
230
239
  const lines = [ans];
@@ -246,7 +255,7 @@ export const exaAnswerCapability = {
246
255
  export const exaReadUrlsCapability = {
247
256
  spec: {
248
257
  name: 'ExaReadUrls',
249
- 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). " +
250
259
  "Up to 100 URLs per call. Much cheaper than chaining 100× WebFetch, " +
251
260
  "and returns text already stripped of HTML/boilerplate — ready to " +
252
261
  "feed into an LLM context window. Prefer over WebFetch when reading " +
@@ -272,11 +281,11 @@ export const exaReadUrlsCapability = {
272
281
  return { output: `Error: max 100 URLs per call (got ${params.urls.length})`, isError: true };
273
282
  }
274
283
  try {
275
- 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);
276
285
  const body = res.data ?? res;
277
286
  const cost = body.costDollars?.total;
278
287
  // $0.002/URL list price as the floor when the gateway omits costDollars.
279
- 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);
280
289
  const results = body.results ?? [];
281
290
  if (results.length === 0) {
282
291
  return { output: `No readable content returned for the ${params.urls.length} URL(s).` };
@@ -14,6 +14,7 @@ import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js
14
14
  import { logger } from '../logger.js';
15
15
  import { ssrfSafeFetch } from './ssrf.js';
16
16
  import { isWalletKeyPath } from './sensitive-paths.js';
17
+ import { noChargeNote, cancelHint } from '../payments/billing-copy.js';
17
18
  /**
18
19
  * Models that accept a reference image via /v1/images/image2image. Mirrors the
19
20
  * gateway's EDIT_SUPPORTED_MODELS (src/app/api/v1/images/image2image/route.ts):
@@ -253,7 +254,7 @@ function buildExecute(deps) {
253
254
  return {
254
255
  output: `## Image generation skipped\n` +
255
256
  `- ${decision.reason}\n\n` +
256
- `No USDC was spent. Choose a cheaper model/size or raise the ` +
257
+ `${noChargeNote()} Choose a cheaper model/size or raise the ` +
257
258
  `content budget before trying again.`,
258
259
  };
259
260
  }
@@ -267,9 +268,9 @@ function buildExecute(deps) {
267
268
  const est = perImageUsd * n;
268
269
  const priceNote = est > 0 ? ` for ~$${est.toFixed(2)}` : '';
269
270
  const countNote = n > 1 ? `${n} images` : 'an image';
270
- const answer = await ctx.onAskUser(`Generate ${countNote} with ${imageModel}${priceNote}? No USDC is spent if you cancel.`, ['Generate', 'Cancel']);
271
+ const answer = await ctx.onAskUser(`Generate ${countNote} with ${imageModel}${priceNote}? ${cancelHint()}`, ['Generate', 'Cancel']);
271
272
  if (answer !== 'Generate') {
272
- return { output: `## Image generation cancelled\n\nNo USDC was spent.` };
273
+ return { output: `## Image generation cancelled\n\n${noChargeNote()}` };
273
274
  }
274
275
  }
275
276
  // Resolve all reference images + the mask into base64 data URIs now, right
@@ -648,7 +649,7 @@ export function createImageGenCapability(deps = {}) {
648
649
  description: "Generate or edit an image. Text-to-image from a prompt, or " +
649
650
  "image-to-image when you pass a reference image (style transfer, " +
650
651
  "character consistency, edits). Supports mask-based inpainting and " +
651
- "multi-image fusion. Costs USDC from the user's wallet — confirm " +
652
+ "multi-image fusion. Billed per image — confirm " +
652
653
  "before generating. Saves to local file(s). Default size: 1024x1024. " +
653
654
  "Do NOT call repeatedly to iterate on style — ask the user first. " +
654
655
  "Pass contentId to attach the result to an existing Content piece: " +
@@ -26,11 +26,12 @@
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, VERSION } from '../config.js';
30
- import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
29
+ import { loadChain, VERSION, DASHBOARD_URL } from '../config.js';
30
+ import { gatewayBase, gatewayHeaders, isKeyMode } from '../payments/auth-mode.js';
31
31
  import { walletReservation, AMBIGUOUS_GRACE_MS } from '../wallet/reservation.js';
32
32
  import { recordUsage } from '../stats/tracker.js';
33
33
  import { logger } from '../logger.js';
34
+ import { noChargeNote } from '../payments/billing-copy.js';
34
35
  // ─── Pricing table (probed from /.well-known/x402 + 402 responses) ─────────
35
36
  const CREATE_PRICE_USD = {
36
37
  cpu: 0.01,
@@ -214,9 +215,14 @@ function describeHeadroom() {
214
215
  parts.push(`${fmtUsd(snap.ambiguousUsd)} is held for ${snap.ambiguousCount} recent payment(s) whose settlement is ` +
215
216
  `unconfirmed (released automatically after the on-chain balance refreshes)`);
216
217
  }
218
+ // In key mode there is no wallet to fund — the ceiling is the prepaid
219
+ // balance, so send the user to the right place.
220
+ const topUp = isKeyMode()
221
+ ? `Top up account credits at ${DASHBOARD_URL}.`
222
+ : 'Fund the wallet.';
217
223
  if (parts.length === 0)
218
- return 'Fund the wallet.';
219
- return parts.join('; ') + ' — wait for those to clear or fund the wallet.';
224
+ return topUp;
225
+ return parts.join('; ') + ` — wait for those to clear, or ${topUp[0].toLowerCase()}${topUp.slice(1)}`;
220
226
  }
221
227
  function signalError(signal) {
222
228
  const reason = signal.reason;
@@ -373,7 +379,7 @@ export const modalCreateCapability = {
373
379
  try {
374
380
  const answer = await ctx.onAskUser(lines.join('\n'), ['Approve', 'Cancel']);
375
381
  if (answer !== 'Approve') {
376
- return { output: '## Sandbox creation cancelled\n\nNo USDC was spent.' };
382
+ return { output: `## Sandbox creation cancelled\n\n${noChargeNote()}` };
377
383
  }
378
384
  }
379
385
  catch {
@@ -387,7 +393,7 @@ export const modalCreateCapability = {
387
393
  reservation = await walletReservation.hold(price);
388
394
  if (!reservation) {
389
395
  return {
390
- output: `Insufficient USDC for ModalCreate (${tier}, ~${fmtUsd(price)}). ` +
396
+ output: `Insufficient ${isKeyMode() ? 'account credit' : 'USDC'} for ModalCreate (${tier}, ~${fmtUsd(price)}). ` +
391
397
  describeHeadroom(),
392
398
  isError: true,
393
399
  };
@@ -22,6 +22,7 @@ import { logger } from '../logger.js';
22
22
  import { isWalletKeyPath } from './sensitive-paths.js';
23
23
  import { findModel, estimateCostUsd } from '../gateway-models.js';
24
24
  import { recordUsage } from '../stats/tracker.js';
25
+ import { noChargeNote } from '../payments/billing-copy.js';
25
26
  const DEFAULT_MODEL = 'minimax/music-2.5+';
26
27
  // Flat per-track price for the default model — already margin-inclusive
27
28
  // ($0.15/track × 1.05 gateway margin). Fallback when the catalog is unavailable.
@@ -65,14 +66,14 @@ function buildExecute(deps) {
65
66
  if (contentId && deps.library) {
66
67
  const content = deps.library.get(contentId);
67
68
  if (!content) {
68
- return { output: `Content ${contentId} not found. No USDC was spent.` };
69
+ return { output: `Content ${contentId} not found. ${noChargeNote()}` };
69
70
  }
70
71
  if (content.spentUsd + trackCostUsd > content.budgetUsd + 1e-9) {
71
72
  return {
72
73
  output: `## Music generation skipped\n` +
73
74
  `- Would exceed budget: spent $${content.spentUsd.toFixed(2)} + fixed ` +
74
75
  `$${trackCostUsd.toFixed(2)} > cap $${content.budgetUsd.toFixed(2)}\n\n` +
75
- `No USDC was spent.`,
76
+ noChargeNote(),
76
77
  };
77
78
  }
78
79
  }
@@ -263,7 +264,7 @@ export function createMusicGenCapability(deps = {}) {
263
264
  name: 'MusicGen',
264
265
  description: "Generate a ~3-minute MP3 track from a text prompt (plus optional " +
265
266
  "lyrics or instrumental flag). Calls BlockRun's /v1/audio/generations. " +
266
- "Costs $0.1575 USDC per call — bills a flat rate, MiniMax ignores " +
267
+ "Costs $0.1575 per call — bills a flat rate, MiniMax ignores " +
267
268
  "duration hints and always returns ~3 min. Generation takes 1–3 " +
268
269
  "minutes. ALWAYS confirm with the user before calling — music is " +
269
270
  "expensive and slow. Pass contentId to attach to a Content piece " +
@@ -16,6 +16,7 @@ import { loadChain, VERSION } from '../config.js';
16
16
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
17
17
  import { logger } from '../logger.js';
18
18
  import { recordUsage } from '../stats/tracker.js';
19
+ import { chargedNote, noChargeNote, cancelHint } from '../payments/billing-copy.js';
19
20
  const PHONE_TIMEOUT_MS = 30_000;
20
21
  async function postWithPayment(path, body, ctx, meta) {
21
22
  const startMs = Date.now();
@@ -119,7 +120,7 @@ export const listPhoneNumbersCapability = {
119
120
  name: 'ListPhoneNumbers',
120
121
  description: 'List the phone numbers your wallet currently owns (US/CA, leased 30 days at a time). ' +
121
122
  'Use this before any phone-related action to remind the agent what numbers are available. ' +
122
- 'Costs $0.001 USDC. Returns each number with country, area code, expiration timestamp, ' +
123
+ 'Costs $0.001 per call. Returns each number with country, area code, expiration timestamp, ' +
123
124
  'and current status (active/expiring/expired).',
124
125
  input_schema: { type: 'object', properties: {} },
125
126
  },
@@ -127,7 +128,7 @@ export const listPhoneNumbersCapability = {
127
128
  try {
128
129
  const res = await postWithPayment('/v1/phone/numbers/list', {}, ctx, { tool: 'ListPhoneNumbers', priceUsd: 0.001 });
129
130
  return {
130
- output: `## Phone numbers (wallet-owned)\n\n` +
131
+ output: `## Phone numbers (provisioned to this account)\n\n` +
131
132
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
132
133
  };
133
134
  }
@@ -139,7 +140,7 @@ export const listPhoneNumbersCapability = {
139
140
  export const buyPhoneNumberCapability = {
140
141
  spec: {
141
142
  name: 'BuyPhoneNumber',
142
- description: 'Provision a new US or CA phone number for the wallet for 30 days. Costs $5 USDC. ' +
143
+ description: 'Provision a new US or CA phone number for 30 days. Costs $5.00 per number. ' +
143
144
  'Optionally pin a 3-digit area code (best effort). The provisioned number is auto-registered ' +
144
145
  'as a valid caller ID for outbound VoiceCall. A wallet can hold multiple numbers; this adds ' +
145
146
  'one, never replaces. To pick the country: country="US" (default) or country="CA".',
@@ -162,15 +163,15 @@ export const buyPhoneNumberCapability = {
162
163
  // callers (FRANKLIN_MEDIA_AUTO_APPROVE_ALL=1 or no onAskUser bridge) proceed.
163
164
  const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
164
165
  if (!autoApprove && ctx.onAskUser) {
165
- const answer = await ctx.onAskUser(`Buy a new ${body.country || 'US'} phone number for $5.00 USDC? No USDC is spent if you cancel.`, ['Buy', 'Cancel']);
166
+ const answer = await ctx.onAskUser(`Buy a new ${body.country || 'US'} phone number for $5.00? ${cancelHint()}`, ['Buy', 'Cancel']);
166
167
  if (answer !== 'Buy') {
167
- return { output: `## Phone number purchase cancelled\n\nNo USDC was spent.` };
168
+ return { output: `## Phone number purchase cancelled\n\n${noChargeNote()}` };
168
169
  }
169
170
  }
170
171
  try {
171
172
  const res = await postWithPayment('/v1/phone/numbers/buy', body, ctx, { tool: 'BuyPhoneNumber', priceUsd: 5.0 });
172
173
  return {
173
- output: `## Number provisioned ($5 USDC charged)\n\n` +
174
+ output: `## Number provisioned (${chargedNote(5)})\n\n` +
174
175
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
175
176
  };
176
177
  }
@@ -182,7 +183,7 @@ export const buyPhoneNumberCapability = {
182
183
  export const renewPhoneNumberCapability = {
183
184
  spec: {
184
185
  name: 'RenewPhoneNumber',
185
- description: 'Extend the 30-day lease on a wallet-owned phone number. Costs $5 USDC. Use ListPhoneNumbers ' +
186
+ description: 'Extend the 30-day lease on a BlockRun-provisioned phone number. Costs $5.00. Use ListPhoneNumbers ' +
186
187
  'first to confirm the number is yours. Released or expired numbers cannot be renewed — buy a ' +
187
188
  'new one with BuyPhoneNumber instead.',
188
189
  input_schema: {
@@ -200,15 +201,15 @@ export const renewPhoneNumberCapability = {
200
201
  // Confirm the $5 spend before charging (parity with BuyPhoneNumber / ModalCreate).
201
202
  const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
202
203
  if (!autoApprove && ctx.onAskUser) {
203
- const answer = await ctx.onAskUser(`Renew ${input.phone_number} for 30 days at $5.00 USDC? No USDC is spent if you cancel.`, ['Renew', 'Cancel']);
204
+ const answer = await ctx.onAskUser(`Renew ${input.phone_number} for 30 days at $5.00? ${cancelHint()}`, ['Renew', 'Cancel']);
204
205
  if (answer !== 'Renew') {
205
- return { output: `## Renewal cancelled\n\nNo USDC was spent.` };
206
+ return { output: `## Renewal cancelled\n\n${noChargeNote()}` };
206
207
  }
207
208
  }
208
209
  try {
209
210
  const res = await postWithPayment('/v1/phone/numbers/renew', { phoneNumber: input.phone_number }, ctx, { tool: 'RenewPhoneNumber', priceUsd: 5.0 });
210
211
  return {
211
- output: `## Lease renewed (+30 days, $5 USDC charged)\n\n` +
212
+ output: `## Lease renewed (+30 days, ${chargedNote(5)})\n\n` +
212
213
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
213
214
  };
214
215
  }
@@ -220,7 +221,7 @@ export const renewPhoneNumberCapability = {
220
221
  export const releasePhoneNumberCapability = {
221
222
  spec: {
222
223
  name: 'ReleasePhoneNumber',
223
- description: 'Release a wallet-owned phone number back to the BlockRun pool before its lease expires. ' +
224
+ description: 'Release a BlockRun-provisioned phone number back to the pool before its lease expires. ' +
224
225
  'Free. The number is gone after this — it may be picked up by another wallet. Use when you ' +
225
226
  "no longer need a test number and want it out of your ListPhoneNumbers result.",
226
227
  input_schema: {
@@ -251,8 +252,8 @@ export const phoneLookupCapability = {
251
252
  spec: {
252
253
  name: 'PhoneLookup',
253
254
  description: 'Look up carrier and line type information for ANY phone number (does not need to be ' +
254
- 'wallet-owned). Returns carrier name, line type (mobile/landline/voip), country, and ' +
255
- 'portability info. Costs $0.01 USDC. Use to validate a number before texting/calling or ' +
255
+ 'BlockRun-provisioned). Returns carrier name, line type (mobile/landline/voip), country, and ' +
256
+ 'portability info. Costs $0.01 per lookup. Use to validate a number before texting/calling or ' +
256
257
  'to figure out whether a contact number is a real mobile.',
257
258
  input_schema: {
258
259
  type: 'object',
@@ -269,7 +270,7 @@ export const phoneLookupCapability = {
269
270
  try {
270
271
  const res = await postWithPayment('/v1/phone/lookup', { phoneNumber: input.phone_number }, ctx, { tool: 'PhoneLookup', priceUsd: 0.01 });
271
272
  return {
272
- output: `## Phone lookup ($0.01 USDC charged)\n\n` +
273
+ output: `## Phone lookup (${chargedNote(0.01)})\n\n` +
273
274
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
274
275
  };
275
276
  }
@@ -299,7 +300,7 @@ export const phoneFraudCheckCapability = {
299
300
  try {
300
301
  const res = await postWithPayment('/v1/phone/lookup/fraud', { phoneNumber: input.phone_number }, ctx, { tool: 'PhoneFraudCheck', priceUsd: 0.05 });
301
302
  return {
302
- output: `## Fraud check ($0.05 USDC charged)\n\n` +
303
+ output: `## Fraud check (${chargedNote(0.05)})\n\n` +
303
304
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
304
305
  };
305
306
  }
@@ -37,12 +37,13 @@
37
37
  */
38
38
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
39
39
  import { loadChain, VERSION } from '../config.js';
40
- import { resolveCharge } from '../payments/price-catalog.js';
40
+ import { chargeFromResponse, requestIdFromResponse, resolveCharge } from '../payments/price-catalog.js';
41
41
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
42
42
  import { logger } from '../logger.js';
43
43
  import { recordFetch } from '../trading/providers/telemetry.js';
44
44
  import { recordUsage } from '../stats/tracker.js';
45
45
  import { frameUntrusted } from './untrusted.js';
46
+ import { receiptLine } from '../payments/billing-copy.js';
46
47
  const TIMEOUT_MS = 30_000;
47
48
  const DEFAULT_LIMIT = 20;
48
49
  const MAX_LIMIT = 50;
@@ -116,6 +117,7 @@ async function getWithPayment(path, query, ctx) {
116
117
  // to this module's own price table, then to the published catalog.
117
118
  const charge = resolveCharge({
118
119
  apiPath: endpoint,
120
+ chargedUsd: chargeFromResponse(response),
119
121
  settledUsd: costRecorded,
120
122
  fallbackUsd: priceForPath(path),
121
123
  });
@@ -130,7 +132,7 @@ async function getWithPayment(path, query, ctx) {
130
132
  // restart). Without this, Predexon spend is absent from `franklin stats`
131
133
  // and invisible to the --max-spend ceiling (parity with surf.ts).
132
134
  try {
133
- recordUsage(`PredictionMarket:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
135
+ recordUsage(`PredictionMarket:${path}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated, requestIdFromResponse(response));
134
136
  }
135
137
  catch { /* best-effort */ }
136
138
  return (await response.json());
@@ -408,7 +410,7 @@ async function execute(input, ctx) {
408
410
  lines.push(`${i + 1}. **[${platform}]** ${title}`);
409
411
  });
410
412
  }
411
- lines.push(`_$0.005 paid via x402._`);
413
+ lines.push(receiptLine(0.005));
412
414
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
413
415
  }
414
416
  case 'leaderboard': {
@@ -456,7 +458,7 @@ async function execute(input, ctx) {
456
458
  parts.push(`win ${formatPct(winRate, 0)}`);
457
459
  lines.push(`${i + 1}. \`${w}\`${handle}` + (parts.length > 0 ? ` — ${parts.join(' · ')}` : ''));
458
460
  });
459
- lines.push('', `_$0.001 paid via x402._`);
461
+ lines.push('', receiptLine(0.001));
460
462
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
461
463
  }
462
464
  case 'walletProfile': {
@@ -571,7 +573,7 @@ async function execute(input, ctx) {
571
573
  if (recent.length > 0)
572
574
  lines.push(` ${recent.join(' · ')}`);
573
575
  });
574
- lines.push('', `_$0.005 paid via x402._`);
576
+ lines.push('', receiptLine(0.005));
575
577
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
576
578
  }
577
579
  case 'walletPnl': {
@@ -647,7 +649,7 @@ async function execute(input, ctx) {
647
649
  });
648
650
  }
649
651
  }
650
- lines.push('', `_$0.005 paid via x402._`);
652
+ lines.push('', receiptLine(0.005));
651
653
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
652
654
  }
653
655
  case 'walletPositions': {
@@ -713,7 +715,7 @@ async function execute(input, ctx) {
713
715
  }
714
716
  lines.push(`${i + 1}. **${title}** — ${parts.join(' · ')}`);
715
717
  });
716
- lines.push('', `_$0.005 paid via x402._`);
718
+ lines.push('', receiptLine(0.005));
717
719
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
718
720
  }
719
721
  case 'smartActivity': {
@@ -754,7 +756,7 @@ async function execute(input, ctx) {
754
756
  stats.push(`${formatPct(netBuyersPct, 0)} net buyers`);
755
757
  lines.push(`${i + 1}. **${title}**${cidTag}` + (stats.length > 0 ? `\n ${stats.join(' · ')}` : ''));
756
758
  });
757
- lines.push('', `_$0.005 paid via x402._`);
759
+ lines.push('', receiptLine(0.005));
758
760
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
759
761
  }
760
762
  case 'smartMoney': {
@@ -809,7 +811,7 @@ async function execute(input, ctx) {
809
811
  perf.push(`win ${formatPct(pos.avg_smart_win_rate, 0)}`);
810
812
  lines.push(`**Smart performance:** ${perf.join(' · ')}`);
811
813
  }
812
- lines.push('', `_$0.005 paid via x402._`);
814
+ lines.push('', receiptLine(0.005));
813
815
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
814
816
  }
815
817
  case 'searchPolymarket': {
@@ -856,7 +858,7 @@ async function execute(input, ctx) {
856
858
  ` prices: ${yesPx} · vol: ${formatUsd(vol)} · liq: ${formatUsd(liq)}` +
857
859
  (end ? ` · ends ${String(end).slice(0, 10)}` : ''));
858
860
  });
859
- lines.push('', `_$0.001 paid via x402._`);
861
+ lines.push('', receiptLine(0.001));
860
862
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
861
863
  }
862
864
  case 'searchKalshi': {
@@ -892,7 +894,7 @@ async function execute(input, ctx) {
892
894
  ` yes ${yes} · vol: ${m.volume?.toLocaleString() ?? 'n/a'} · OI: ${m.open_interest?.toLocaleString() ?? 'n/a'}` +
893
895
  (m.close_time ? ` · closes ${String(m.close_time).slice(0, 10)}` : ''));
894
896
  });
895
- lines.push('', `_$0.001 paid via x402._`);
897
+ lines.push('', receiptLine(0.001));
896
898
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
897
899
  }
898
900
  case 'crossPlatform': {
@@ -27,7 +27,7 @@
27
27
  */
28
28
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
29
29
  import { loadChain, USER_AGENT } from '../config.js';
30
- import { resolveCharge } from '../payments/price-catalog.js';
30
+ import { chargeFromResponse, requestIdFromResponse, resolveCharge } from '../payments/price-catalog.js';
31
31
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
32
32
  import { recordUsage } from '../stats/tracker.js';
33
33
  import { logger } from '../logger.js';
@@ -191,10 +191,10 @@ async function actionEnroll(base, chain, input, ctx) {
191
191
  paidUsd = 0;
192
192
  // 0 whenever no 402 was settled, which is every call in API-key mode.
193
193
  const charge = res.ok
194
- ? resolveCharge({ apiPath: url, settledUsd: paidUsd })
194
+ ? resolveCharge({ apiPath: url, chargedUsd: chargeFromResponse(res), settledUsd: paidUsd })
195
195
  : { usd: 0, estimated: false };
196
196
  try {
197
- recordUsage('RealFace:enroll', 0, 0, charge.usd, Date.now() - start, false, charge.estimated);
197
+ recordUsage('RealFace:enroll', 0, 0, charge.usd, Date.now() - start, false, charge.estimated, requestIdFromResponse(res));
198
198
  }
199
199
  catch { /* best-effort */ }
200
200
  if (res.status === 425) {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Multi-chain RPC — read-only JSON-RPC across 40+ chains via the BlockRun
3
3
  * `/v1/rpc/{network}` endpoint (Tatum gateway). x402-paid against the user's
4
- * USDC wallet, flat $0.002 per call.
4
+ * USDC wallet, flat $0.0020 base + $0.001 settlement fee (measured 2026-09-05).
5
5
  *
6
6
  * For a trading agent this covers the on-chain reads the dedicated tools don't:
7
7
  * native + ERC-20 balances on any chain, contract reads (eth_call), gas price,