@blockrun/franklin 3.45.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 (49) hide show
  1. package/README.md +13 -11
  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/doctor.js +18 -0
  11. package/dist/commands/usage.d.ts +14 -0
  12. package/dist/commands/usage.js +86 -0
  13. package/dist/commands/wallet-adopt.d.ts +12 -0
  14. package/dist/commands/wallet-adopt.js +49 -0
  15. package/dist/index.js +16 -0
  16. package/dist/payments/account.d.ts +17 -0
  17. package/dist/payments/account.js +105 -0
  18. package/dist/payments/auth-mode.d.ts +5 -19
  19. package/dist/payments/auth-mode.js +15 -17
  20. package/dist/payments/billing-copy.d.ts +37 -0
  21. package/dist/payments/billing-copy.js +57 -0
  22. package/dist/payments/post-with-payment.js +8 -15
  23. package/dist/payments/price-catalog.d.ts +9 -0
  24. package/dist/payments/price-catalog.js +13 -0
  25. package/dist/payments/usage.d.ts +106 -0
  26. package/dist/payments/usage.js +168 -0
  27. package/dist/stats/tracker.d.ts +9 -1
  28. package/dist/stats/tracker.js +6 -1
  29. package/dist/tools/bash.js +17 -7
  30. package/dist/tools/blockrun.js +1 -1
  31. package/dist/tools/defillama.js +2 -2
  32. package/dist/tools/imagegen.js +5 -4
  33. package/dist/tools/modal.js +12 -6
  34. package/dist/tools/musicgen.js +4 -3
  35. package/dist/tools/phone.js +16 -15
  36. package/dist/tools/prediction.js +12 -11
  37. package/dist/tools/realface.js +2 -2
  38. package/dist/tools/rpc.js +2 -2
  39. package/dist/tools/sensitive-paths.d.ts +1 -1
  40. package/dist/tools/sensitive-paths.js +13 -4
  41. package/dist/tools/surf.js +2 -2
  42. package/dist/tools/videogen.js +6 -5
  43. package/dist/tools/voice.d.ts +1 -1
  44. package/dist/tools/voice.js +5 -4
  45. package/dist/wallet/reservation.d.ts +24 -0
  46. package/dist/wallet/reservation.js +50 -4
  47. package/dist/wallet/solana-migration.d.ts +48 -0
  48. package/dist/wallet/solana-migration.js +81 -0
  49. package/package.json +2 -2
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The gateway's own per-request ledger, and how Franklin reconciles to it.
3
+ *
4
+ * Franklin's local numbers in key mode are catalog estimates: the account
5
+ * gateway settles against a prepaid balance and returns no charge on the
6
+ * response, so `franklin stats` reports what a call SHOULD have cost. This
7
+ * module fetches what it DID cost.
8
+ *
9
+ * `GET /v1/usage` returns one row per request with a `request_id` that matches
10
+ * the `x-blockrun-request-id` header the gateway already sends, so the join is
11
+ * line-by-line rather than a comparison of two totals — a total that matches
12
+ * can still be two errors cancelling out.
13
+ *
14
+ * Four properties of this feed change how it must be read, and getting any of
15
+ * them wrong produces a confident wrong answer:
16
+ *
17
+ * `cost_state: 'pending'` means the usage exists and its charge does not yet.
18
+ * Those rows can still be repriced. Summing them as zero understates spend
19
+ * and, worse, looks settled.
20
+ *
21
+ * Zero-cost rows are INCLUDED on purpose. "You were not charged for this" is
22
+ * an answer; a row that is simply absent is indistinguishable from one the
23
+ * client dropped. Never filter them.
24
+ *
25
+ * `unavailable_days` names days the gateway could not list rather than
26
+ * silently returning a short page. Swallowing it makes two correct ledgers
27
+ * look like they disagree.
28
+ *
29
+ * `kind` says whether a row is checkable locally at all. A `chat` charge can
30
+ * be rebuilt from tokens and a published rate; a `service` charge is a
31
+ * per-call figure only the gateway holds, so a local estimate for one is a
32
+ * guess by construction and a mismatch is not evidence of a bug.
33
+ *
34
+ * The cursor is opaque. Do not parse it, and do not construct one.
35
+ */
36
+ export type CostState = 'priced' | 'pending' | 'free';
37
+ export type UsageKind = 'chat' | 'service';
38
+ export interface UsageRow {
39
+ requestId: string;
40
+ timestamp: string;
41
+ endpoint: string;
42
+ model: string | null;
43
+ kind: UsageKind;
44
+ inputTokens: number;
45
+ outputTokens: number;
46
+ costUsd: number;
47
+ costState: CostState;
48
+ status: number;
49
+ }
50
+ export interface UsagePage {
51
+ rows: UsageRow[];
52
+ /** Days the gateway could not list. Surface these; never treat as empty. */
53
+ unavailableDays: string[];
54
+ }
55
+ /**
56
+ * Fetch usage rows, following the cursor. Returns null when there is no key or
57
+ * the gateway is unreachable — callers show what they do know rather than
58
+ * inventing a ledger.
59
+ */
60
+ export declare function fetchUsage(opts?: {
61
+ from?: string;
62
+ to?: string;
63
+ limit?: number;
64
+ timeoutMs?: number;
65
+ }): Promise<UsagePage | null>;
66
+ export interface UsageTotals {
67
+ /** Rows whose charge has settled. This is the number you can trust. */
68
+ pricedUsd: number;
69
+ pricedCount: number;
70
+ /** Usage that exists with no charge yet. Not a zero — it can still be priced. */
71
+ pendingCount: number;
72
+ /** Explicitly not chargeable. Counted, never hidden. */
73
+ freeCount: number;
74
+ chatCount: number;
75
+ serviceCount: number;
76
+ }
77
+ export declare function summarize(rows: readonly UsageRow[]): UsageTotals;
78
+ export interface Reconciliation {
79
+ /** Ledger rows Franklin also has locally, and whether the numbers agree. */
80
+ matched: Array<{
81
+ row: UsageRow;
82
+ localUsd: number;
83
+ deltaUsd: number;
84
+ }>;
85
+ /** Charged by the gateway with no local row. Franklin under-counted. */
86
+ missingLocally: UsageRow[];
87
+ /** Rows Franklin recorded that carry no id to join on. */
88
+ unjoinable: number;
89
+ totals: UsageTotals;
90
+ unavailableDays: string[];
91
+ }
92
+ /**
93
+ * Join the gateway ledger to Franklin's own journal on `request_id`.
94
+ *
95
+ * Only `priced` rows are compared. A `pending` row has no charge to disagree
96
+ * with yet, and a `free` row's zero is an answer rather than a discrepancy.
97
+ *
98
+ * `unjoinable` counts local rows with no id — wallet-mode calls, free-path
99
+ * calls, and anything recorded before the id was captured. They are reported
100
+ * rather than hidden, because "0 mismatches" from a journal that could not be
101
+ * joined is not the same statement as "0 mismatches".
102
+ */
103
+ export declare function reconcile(ledger: UsagePage, local: ReadonlyArray<{
104
+ requestId?: string;
105
+ costUsd: number;
106
+ }>): Reconciliation;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The gateway's own per-request ledger, and how Franklin reconciles to it.
3
+ *
4
+ * Franklin's local numbers in key mode are catalog estimates: the account
5
+ * gateway settles against a prepaid balance and returns no charge on the
6
+ * response, so `franklin stats` reports what a call SHOULD have cost. This
7
+ * module fetches what it DID cost.
8
+ *
9
+ * `GET /v1/usage` returns one row per request with a `request_id` that matches
10
+ * the `x-blockrun-request-id` header the gateway already sends, so the join is
11
+ * line-by-line rather than a comparison of two totals — a total that matches
12
+ * can still be two errors cancelling out.
13
+ *
14
+ * Four properties of this feed change how it must be read, and getting any of
15
+ * them wrong produces a confident wrong answer:
16
+ *
17
+ * `cost_state: 'pending'` means the usage exists and its charge does not yet.
18
+ * Those rows can still be repriced. Summing them as zero understates spend
19
+ * and, worse, looks settled.
20
+ *
21
+ * Zero-cost rows are INCLUDED on purpose. "You were not charged for this" is
22
+ * an answer; a row that is simply absent is indistinguishable from one the
23
+ * client dropped. Never filter them.
24
+ *
25
+ * `unavailable_days` names days the gateway could not list rather than
26
+ * silently returning a short page. Swallowing it makes two correct ledgers
27
+ * look like they disagree.
28
+ *
29
+ * `kind` says whether a row is checkable locally at all. A `chat` charge can
30
+ * be rebuilt from tokens and a published rate; a `service` charge is a
31
+ * per-call figure only the gateway holds, so a local estimate for one is a
32
+ * guess by construction and a mismatch is not evidence of a bug.
33
+ *
34
+ * The cursor is opaque. Do not parse it, and do not construct one.
35
+ */
36
+ import { KEY_API_URL, USER_AGENT } from '../config.js';
37
+ import { loadApiKey } from './auth-mode.js';
38
+ /** Max rows the endpoint will return per page. */
39
+ const MAX_LIMIT = 500;
40
+ /** Stop paging rather than walk an unbounded history. */
41
+ const MAX_PAGES = 40;
42
+ function toRow(raw) {
43
+ const requestId = typeof raw.request_id === 'string' ? raw.request_id : '';
44
+ if (!requestId)
45
+ return null; // without the join key the row is not usable here
46
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
47
+ const state = raw.cost_state;
48
+ return {
49
+ requestId,
50
+ timestamp: typeof raw.timestamp === 'string' ? raw.timestamp : '',
51
+ endpoint: typeof raw.endpoint === 'string' ? raw.endpoint : '',
52
+ model: typeof raw.model === 'string' ? raw.model : null,
53
+ kind: raw.kind === 'chat' ? 'chat' : 'service',
54
+ inputTokens: num(raw.input_tokens),
55
+ outputTokens: num(raw.output_tokens),
56
+ costUsd: num(raw.cost_usd),
57
+ // An unrecognised state is treated as pending, not priced: the safe error
58
+ // is "we do not know yet", never "settled at whatever number came through".
59
+ costState: state === 'priced' || state === 'free' ? state : 'pending',
60
+ status: num(raw.status),
61
+ };
62
+ }
63
+ /**
64
+ * Fetch usage rows, following the cursor. Returns null when there is no key or
65
+ * the gateway is unreachable — callers show what they do know rather than
66
+ * inventing a ledger.
67
+ */
68
+ export async function fetchUsage(opts = {}) {
69
+ const key = loadApiKey();
70
+ if (!key)
71
+ return null;
72
+ const rows = [];
73
+ const unavailableDays = new Set();
74
+ let cursor = null;
75
+ for (let page = 0; page < MAX_PAGES; page++) {
76
+ const url = new URL(`${KEY_API_URL}/v1/usage`);
77
+ if (opts.from)
78
+ url.searchParams.set('from', opts.from);
79
+ if (opts.to)
80
+ url.searchParams.set('to', opts.to);
81
+ url.searchParams.set('limit', String(Math.min(opts.limit ?? MAX_LIMIT, MAX_LIMIT)));
82
+ if (cursor)
83
+ url.searchParams.set('cursor', cursor);
84
+ let body;
85
+ try {
86
+ const res = await fetch(url, {
87
+ headers: { Authorization: `Bearer ${key}`, 'User-Agent': USER_AGENT },
88
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 20_000),
89
+ });
90
+ if (!res.ok)
91
+ return null;
92
+ body = (await res.json());
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ for (const raw of Array.isArray(body.data) ? body.data : []) {
98
+ const row = toRow(raw);
99
+ if (row)
100
+ rows.push(row);
101
+ }
102
+ for (const d of Array.isArray(body.unavailable_days) ? body.unavailable_days : []) {
103
+ if (typeof d === 'string')
104
+ unavailableDays.add(d);
105
+ }
106
+ cursor = typeof body.next_cursor === 'string' && body.next_cursor ? body.next_cursor : null;
107
+ if (!cursor)
108
+ break;
109
+ }
110
+ return { rows, unavailableDays: [...unavailableDays] };
111
+ }
112
+ export function summarize(rows) {
113
+ const t = {
114
+ pricedUsd: 0, pricedCount: 0, pendingCount: 0, freeCount: 0, chatCount: 0, serviceCount: 0,
115
+ };
116
+ for (const r of rows) {
117
+ if (r.costState === 'priced') {
118
+ t.pricedUsd += r.costUsd;
119
+ t.pricedCount++;
120
+ }
121
+ else if (r.costState === 'pending')
122
+ t.pendingCount++;
123
+ else
124
+ t.freeCount++;
125
+ if (r.kind === 'chat')
126
+ t.chatCount++;
127
+ else
128
+ t.serviceCount++;
129
+ }
130
+ return t;
131
+ }
132
+ /**
133
+ * Join the gateway ledger to Franklin's own journal on `request_id`.
134
+ *
135
+ * Only `priced` rows are compared. A `pending` row has no charge to disagree
136
+ * with yet, and a `free` row's zero is an answer rather than a discrepancy.
137
+ *
138
+ * `unjoinable` counts local rows with no id — wallet-mode calls, free-path
139
+ * calls, and anything recorded before the id was captured. They are reported
140
+ * rather than hidden, because "0 mismatches" from a journal that could not be
141
+ * joined is not the same statement as "0 mismatches".
142
+ */
143
+ export function reconcile(ledger, local) {
144
+ const byId = new Map();
145
+ let unjoinable = 0;
146
+ for (const r of local) {
147
+ if (r.requestId)
148
+ byId.set(r.requestId, (byId.get(r.requestId) ?? 0) + r.costUsd);
149
+ else
150
+ unjoinable++;
151
+ }
152
+ const matched = [];
153
+ const missingLocally = [];
154
+ for (const row of ledger.rows) {
155
+ if (row.costState !== 'priced')
156
+ continue;
157
+ const localUsd = byId.get(row.requestId);
158
+ if (localUsd === undefined) {
159
+ // A charge with no local row: real spend Franklin never counted, so it
160
+ // never reached --max-spend either.
161
+ if (row.costUsd > 0)
162
+ missingLocally.push(row);
163
+ continue;
164
+ }
165
+ matched.push({ row, localUsd, deltaUsd: localUsd - row.costUsd });
166
+ }
167
+ return { matched, missingLocally, unjoinable, totals: summarize(ledger.rows), unavailableDays: ledger.unavailableDays };
168
+ }
@@ -11,6 +11,12 @@ export interface UsageRecord {
11
11
  costUsd: number;
12
12
  latencyMs: number;
13
13
  fallback?: boolean;
14
+ /**
15
+ * The gateway's `x-blockrun-request-id` for this call, when it sent one.
16
+ * The join key `franklin usage` uses to line this row up against the
17
+ * account ledger. Absent on wallet-mode and free-path calls.
18
+ */
19
+ requestId?: string;
14
20
  }
15
21
  export interface ModelStats {
16
22
  requests: number;
@@ -60,7 +66,9 @@ export declare function recordUsage(model: string, inputTokens: number, outputTo
60
66
  * key-mode row is priced locally. Surfaced by `franklin stats` so the ledger
61
67
  * never claims more precision than it has.
62
68
  */
63
- estimated?: boolean): void;
69
+ estimated?: boolean,
70
+ /** Gateway request id, from `requestIdFromResponse`. Enables reconciliation. */
71
+ requestId?: string | null): void;
64
72
  /**
65
73
  * Get stats summary for display
66
74
  */
@@ -200,7 +200,9 @@ export function recordUsage(model, inputTokens, outputTokens, costUsd, latencyMs
200
200
  * key-mode row is priced locally. Surfaced by `franklin stats` so the ledger
201
201
  * never claims more precision than it has.
202
202
  */
203
- estimated = isKeyMode()) {
203
+ estimated = isKeyMode(),
204
+ /** Gateway request id, from `requestIdFromResponse`. Enables reconciliation. */
205
+ requestId) {
204
206
  // Count real spend BEFORE the test/audit gates — the --max-spend ceiling must
205
207
  // see every paid tool call even when history persistence is suppressed.
206
208
  if (Number.isFinite(costUsd) && costUsd > 0)
@@ -262,6 +264,9 @@ estimated = isKeyMode()) {
262
264
  costUsd,
263
265
  latencyMs,
264
266
  fallback,
267
+ // Omit rather than store undefined: history is JSON round-tripped, and an
268
+ // explicit `requestId: undefined` survives as a key with no value.
269
+ ...(requestId ? { requestId } : {}),
265
270
  });
266
271
  scheduleSave();
267
272
  }
@@ -289,15 +289,25 @@ function executeCommand(command, timeoutMs, ctx) {
289
289
  const shell = fs.existsSync('/bin/bash') ? '/bin/bash' : (process.env.SHELL || '/bin/sh');
290
290
  let child;
291
291
  try {
292
+ // The account bearer key is deliberately withheld from the subprocess.
293
+ // bash-guard auto-approves `printenv` and `echo` as safe, so
294
+ // `printenv BLOCKRUN_API_KEY` ran with no confirmation and returned the
295
+ // key as tool output — into the model prompt and the saved transcript.
296
+ // Wallet private keys are never in the environment at all; this gives
297
+ // the key the same treatment. Franklin's own gateway calls read
298
+ // process.env in-process and are unaffected, and a user who genuinely
299
+ // needs the key in a shell can export it there themselves.
300
+ const childEnv = {
301
+ ...process.env,
302
+ FRANKLIN: '1', // Let scripts detect they're running inside Franklin
303
+ FRANKLIN_WORKDIR: ctx.workingDir,
304
+ RUNCODE: '1', // Backwards compat
305
+ RUNCODE_WORKDIR: ctx.workingDir,
306
+ };
307
+ delete childEnv.BLOCKRUN_API_KEY;
292
308
  child = spawn(shell, ['-c', command], {
293
309
  cwd: ctx.workingDir,
294
- env: {
295
- ...process.env,
296
- FRANKLIN: '1', // Let scripts detect they're running inside Franklin
297
- FRANKLIN_WORKDIR: ctx.workingDir,
298
- RUNCODE: '1', // Backwards compat
299
- RUNCODE_WORKDIR: ctx.workingDir,
300
- },
310
+ env: childEnv,
301
311
  stdio: ['ignore', 'pipe', 'pipe'],
302
312
  // Put the shell in its own process group (pgid = pid) so a timeout
303
313
  // can SIGTERM the entire tree. Without this, signalling only the
@@ -176,7 +176,7 @@ function fmtUsd(n) {
176
176
  export const blockrunCapability = {
177
177
  spec: {
178
178
  name: 'BlockRun',
179
- description: 'Call any BlockRun gateway endpoint. Signs an x402 USDC payment from the user wallet, retries on HTTP 402, and returns the response. ' +
179
+ description: 'Call any BlockRun gateway endpoint. Billed to account credits or, in wallet mode, by signing an x402 USDC payment and retrying on HTTP 402. ' +
180
180
  'Use this for crypto data (Surf — markets, on-chain, social), AI inference (chat / image / video / music), prediction markets, DeFi data, and any other API exposed under https://blockrun.ai/marketplace. ' +
181
181
  'For phone and voice, prefer the typed tools (ListPhoneNumbers, BuyPhoneNumber, RenewPhoneNumber, ReleasePhoneNumber, PhoneLookup, PhoneFraudCheck, VoiceCall, VoiceStatus) — they spell out cost, required fields, and the buy-number-first requirement. ' +
182
182
  'The path must start with "/v1/" or "/.well-known/". ' +
@@ -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 { chargeFromResponse, 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';
@@ -67,7 +67,7 @@ async function getWithPayment(path, ctx) {
67
67
  // call in API-key mode.
68
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());
@@ -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
  }