@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
package/dist/tools/rpc.js CHANGED
@@ -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,
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
20
20
  import { loadChain, VERSION } from '../config.js';
21
- import { resolveCharge } from '../payments/price-catalog.js';
21
+ import { chargeFromResponse, requestIdFromResponse, resolveCharge } from '../payments/price-catalog.js';
22
22
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
23
23
  import { logger } from '../logger.js';
24
24
  import { recordUsage } from '../stats/tracker.js';
@@ -92,9 +92,9 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
92
92
  // `paidUsd` is only ever set by the 402 branch, so in API-key mode — where
93
93
  // the gateway settles silently and never sends a 402 — it stays 0. Price the
94
94
  // call from the published catalog instead of recording a free call.
95
- const charge = resolveCharge({ apiPath: endpoint, settledUsd: paidUsd });
95
+ const charge = resolveCharge({ apiPath: endpoint, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd });
96
96
  try {
97
- recordUsage(`MultiChainRPC:${network}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated);
97
+ recordUsage(`MultiChainRPC:${network}`, 0, 0, charge.usd, Date.now() - startedAt, false, charge.estimated, requestIdFromResponse(response));
98
98
  }
99
99
  catch { /* best-effort */ }
100
100
  return {
@@ -162,7 +162,7 @@ export const multiChainRpcCapability = {
162
162
  spec: {
163
163
  name: 'MultiChainRPC',
164
164
  description: 'Read-only JSON-RPC against 40+ chains through the BlockRun gateway (one endpoint, no per-chain key). ' +
165
- '$0.002 per call (USDC). Use for on-chain reads the other tools do not cover: native/token balances on any ' +
165
+ '$0.0020 per call, plus a $0.001 settlement fee when paying from a wallet. Use for on-chain reads the other tools do not cover: native/token balances on any ' +
166
166
  'chain, contract reads (eth_call), gas price, nonce, block height, and tx receipt checks ("did my swap land?"). ' +
167
167
  'EVM chains speak eth_* (eth_blockNumber, eth_getBalance, eth_call, eth_gasPrice, eth_getTransactionReceipt, ...); ' +
168
168
  'Solana speaks getSlot/getBalance/getAccountInfo/getTransaction; Bitcoin-family speaks getblockcount etc. ' +
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Wallet secret-material guard for the model-facing file tools.
2
+ * Secret-material guard for the model-facing file tools.
3
3
  *
4
4
  * Franklin IS the wallet: a steered model (prompt injection via a fetched page,
5
5
  * MCP result, file contents, etc.) that can Read/Write/Edit arbitrary paths
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Wallet secret-material guard for the model-facing file tools.
2
+ * Secret-material guard for the model-facing file tools.
3
3
  *
4
4
  * Franklin IS the wallet: a steered model (prompt injection via a fetched page,
5
5
  * MCP result, file contents, etc.) that can Read/Write/Edit arbitrary paths
@@ -11,13 +11,22 @@
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import { BLOCKRUN_DIR } from '../config.js';
15
- /** Private-key / wallet-secret files under ~/.blockrun. */
14
+ import { API_KEY_FILE, BLOCKRUN_DIR } from '../config.js';
15
+ /**
16
+ * Secret-material files under ~/.blockrun.
17
+ *
18
+ * Appended to, never reordered: test/local.mjs indexes this list positionally.
19
+ */
16
20
  const WALLET_KEY_FILES = [
17
21
  path.join(BLOCKRUN_DIR, '.session'), // EVM private key (0x hex)
18
22
  path.join(BLOCKRUN_DIR, '.solana-session'), // Solana secret key (base58)
19
23
  path.join(BLOCKRUN_DIR, '.solana-session-key2'),
20
- path.join(BLOCKRUN_DIR, 'solana-wallet.json'), // legacy { address, private_key }
24
+ path.join(BLOCKRUN_DIR, 'solana-wallet.json'), // legacy { address, privateKey }
25
+ // Account bearer key (brk_...). Not a private key, but it spends: it draws
26
+ // on a prepaid balance with no per-call signature and no chain-level
27
+ // ceiling, so `cat ~/.blockrun/api-key` is exfiltration in one Read. It
28
+ // belongs behind the same guard as the wallet keys above.
29
+ API_KEY_FILE,
21
30
  ];
22
31
  // macOS (APFS) and Windows are case-INSENSITIVE by default, and fs.realpathSync
23
32
  // does NOT canonicalize case — so `.SOLANA-SESSION` opens the real
@@ -17,7 +17,8 @@
17
17
  */
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
19
  import { loadChain, USER_AGENT } from '../config.js';
20
- import { resolveCharge } from '../payments/price-catalog.js';
20
+ import { basePriceForPath, chargeFromResponse, requestIdFromResponse, resolveCharge } from '../payments/price-catalog.js';
21
+ import { GATEWAY_TRANSACTION_FEE_USD } from '../gateway-models.js';
21
22
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
22
23
  import { frameUntrusted } from './untrusted.js';
23
24
  import { recordUsage } from '../stats/tracker.js';
@@ -59,7 +60,7 @@ const CHAIN_ENDPOINTS = [
59
60
  { path: 'onchain/tx', method: 'GET', required: ['hash', 'chain'], desc: 'Transaction details by hash.' },
60
61
  { path: 'onchain/schema', method: 'GET', required: [], desc: 'Schema introspection for the SQL tables.' },
61
62
  { path: 'onchain/query', method: 'POST', required: [], desc: 'Structured chain query (POST body).' },
62
- { path: 'onchain/sql', method: 'POST', required: [], desc: 'Raw SQL against 80+ indexed chain tables (POST body, Tier-3 $0.02).' },
63
+ { path: 'onchain/sql', method: 'POST', required: [], desc: 'Raw SQL against 80+ indexed chain tables (POST body).' },
63
64
  { path: 'token/tokenomics', method: 'GET', required: [], desc: 'Token supply / unlock / distribution.' },
64
65
  { path: 'token/dex-trades', method: 'GET', required: ['address'], desc: 'Recent DEX trades for a token.' },
65
66
  { path: 'token/holders', method: 'GET', required: ['address', 'chain'], desc: 'Top holders / concentration.' },
@@ -214,10 +215,10 @@ async function callSurf(toolName, table, input, ctx) {
214
215
  // Fall back to the catalog price so Surf spend still counts against
215
216
  // --max-spend and shows in stats.
216
217
  const charge = response.ok
217
- ? resolveCharge({ apiPath: url, settledUsd: paidUsd })
218
+ ? resolveCharge({ apiPath: url, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd })
218
219
  : { usd: 0, estimated: false };
219
220
  try {
220
- recordUsage(`${toolName}:${entry.path}`, 0, 0, charge.usd, Date.now() - start, false, charge.estimated);
221
+ recordUsage(`${toolName}:${entry.path}`, 0, 0, charge.usd, Date.now() - start, false, charge.estimated, requestIdFromResponse(response));
221
222
  }
222
223
  catch { /* best-effort */ }
223
224
  if (!response.ok) {
@@ -238,13 +239,40 @@ async function callSurf(toolName, table, input, ctx) {
238
239
  }
239
240
  }
240
241
  // ── Tool specs ───────────────────────────────────────────────────────────────
242
+ /**
243
+ * Price sentence for the tool description, read from the catalog rather than
244
+ * typed in.
245
+ *
246
+ * This used to read "Tier-1 $0.001, Tier-2 $0.005, Tier-3 $0.02", which the
247
+ * payment layer had long since replaced with one flat rate. Measured against
248
+ * the authoritative 402 on 2026-09-05: every Surf endpoint quotes $0.0085, so
249
+ * the description understated tier-1 by 8.5x and overstated tier-3 by 2.4x.
250
+ *
251
+ * That matters more than an inaccurate comment, because the agent reads this
252
+ * string to decide whether a call is worth making — it was being told the
253
+ * cheapest Surf call costs about a tenth of what it does. A hand-typed price
254
+ * is a published number with no owner; sourcing it from the catalog gives it
255
+ * one, and the guard test keeps literals from creeping back in.
256
+ *
257
+ * It states the BASE price and names the fee separately because there are two
258
+ * real prices per endpoint: the key rail charges the base, the wallet rail adds
259
+ * a settlement fee. One number cannot be right for both, and this phrasing is
260
+ * true on either.
261
+ */
262
+ function surfPriceBlurb() {
263
+ const base = basePriceForPath('/v1/surf/market/ranking');
264
+ return base === null || base <= 0
265
+ ? 'Each call is charged per request; the 402 quote states the exact price.'
266
+ : `Flat $${base.toFixed(4)} per call, plus a $${GATEWAY_TRANSACTION_FEE_USD.toFixed(3)} `
267
+ + 'settlement fee when paying from a wallet.';
268
+ }
241
269
  function makeSurfTool(name, blurb, table, extraParams) {
242
270
  const endpointList = table.map((e) => `\`${e.path}\`${e.required.length ? ` (needs ${e.required.join('+')})` : ''} — ${e.desc}`).join('\n');
243
271
  return {
244
272
  spec: {
245
273
  name,
246
274
  description: `${blurb} Picks an endpoint from a fixed list and signs the x402 USDC payment from the wallet automatically — ` +
247
- `you do not build paths or handle payment. Tier-1 $0.001, Tier-2 $0.005, Tier-3 $0.02.\n\nEndpoints:\n${endpointList}`,
275
+ `you do not build paths or handle payment. ${surfPriceBlurb()}\n\nEndpoints:\n${endpointList}`,
248
276
  input_schema: {
249
277
  type: 'object',
250
278
  properties: {
@@ -29,6 +29,7 @@ import { resolveReferenceImage } from './imagegen.js';
29
29
  import { isWalletKeyPath } from './sensitive-paths.js';
30
30
  import { recordUsage } from '../stats/tracker.js';
31
31
  import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
32
+ import { noChargeNote, cancelHint } from '../payments/billing-copy.js';
32
33
  // BytePlus RealFace asset IDs from the RealFace tool (after H5 liveness +
33
34
  // enrollment). Format: `ta_` + alphanumeric.
34
35
  const REAL_FACE_ASSET_ID_REGEX = /^ta_[A-Za-z0-9]+$/;
@@ -141,23 +142,23 @@ function buildExecute(deps) {
141
142
  // Model-aware estimate so the quoted price matches the model we name in
142
143
  // the prompt (flat per-second fallback only when the model is unknown).
143
144
  const est = resolveVideoUnitCost(videoCatalogModel, duration);
144
- const answer = await ctx.onAskUser(`Generate a ${duration}s video with ${videoModel} for ~$${est.toFixed(2)}? No USDC is spent if you cancel.`, ['Generate', 'Cancel']);
145
+ const answer = await ctx.onAskUser(`Generate a ${duration}s video with ${videoModel} for ~$${est.toFixed(2)}? ${cancelHint()}`, ['Generate', 'Cancel']);
145
146
  if (answer !== 'Generate') {
146
- return { output: `## Video generation cancelled\n\nNo USDC was spent.` };
147
+ return { output: `## Video generation cancelled\n\n${noChargeNote()}` };
147
148
  }
148
149
  }
149
150
  const estCost = resolveVideoUnitCost(videoCatalogModel, duration);
150
151
  if (contentId && deps.library) {
151
152
  const content = deps.library.get(contentId);
152
153
  if (!content) {
153
- return { output: `Content ${contentId} not found. No USDC was spent.` };
154
+ return { output: `Content ${contentId} not found. ${noChargeNote()}` };
154
155
  }
155
156
  if (content.spentUsd + estCost > content.budgetUsd + 1e-9) {
156
157
  return {
157
158
  output: `## Video generation skipped\n` +
158
159
  `- Would exceed budget: spent $${content.spentUsd.toFixed(2)} + estimated ` +
159
160
  `$${estCost.toFixed(2)} > cap $${content.budgetUsd.toFixed(2)}\n\n` +
160
- `No USDC was spent.`,
161
+ noChargeNote(),
161
162
  };
162
163
  }
163
164
  }
@@ -486,7 +487,7 @@ export function createVideoGenCapability(deps = {}) {
486
487
  spec: {
487
488
  name: 'VideoGen',
488
489
  description: "Generate a short MP4 video from a text prompt (optional seed image). " +
489
- "Calls BlockRun's /v1/videos/generations. Costs USDC — default model " +
490
+ "Calls BlockRun's /v1/videos/generations. Billed per generation — default model " +
490
491
  "xai/grok-imagine-video bills $0.05/s (8s default ≈ $0.42). Generation " +
491
492
  "takes ~20–60s. ALWAYS confirm with the user before calling — videos " +
492
493
  "are expensive and slow. Pass contentId to attach to a Content piece " +
@@ -7,7 +7,7 @@
7
7
  * - VoiceStatus — GET /v1/voice/call/{call_id} (free). Polls for transcript
8
8
  * + recording + final disposition.
9
9
  *
10
- * Voice calls require a wallet-owned BlockRun phone number as caller ID —
10
+ * Voice calls require a BlockRun-provisioned phone number as caller ID —
11
11
  * use BuyPhoneNumber (or ListPhoneNumbers if one already exists) before
12
12
  * calling VoiceCall, otherwise the gateway returns 400 with the buy
13
13
  * instructions inline.
@@ -7,7 +7,7 @@
7
7
  * - VoiceStatus — GET /v1/voice/call/{call_id} (free). Polls for transcript
8
8
  * + recording + final disposition.
9
9
  *
10
- * Voice calls require a wallet-owned BlockRun phone number as caller ID —
10
+ * Voice calls require a BlockRun-provisioned phone number as caller ID —
11
11
  * use BuyPhoneNumber (or ListPhoneNumbers if one already exists) before
12
12
  * calling VoiceCall, otherwise the gateway returns 400 with the buy
13
13
  * instructions inline.
@@ -21,6 +21,7 @@ import { logger } from '../logger.js';
21
21
  import { recordUsage } from '../stats/tracker.js';
22
22
  import { frameUntrusted } from './untrusted.js';
23
23
  import { CallLog } from '../phone/call-log.js';
24
+ import { chargedNote } from '../payments/billing-copy.js';
24
25
  /** Singleton, lazy — paths are computed at first use so tests can stub homedir. */
25
26
  let _callLog = null;
26
27
  function callLog() {
@@ -228,7 +229,7 @@ export const voiceCallCapability = {
228
229
  'Common use cases: appointment reminders, verification callbacks, voice surveys, customer ' +
229
230
  'outreach, OTP retrieval, two-party verification calls.\n\n' +
230
231
  'Requirements:\n' +
231
- ' - `from` MUST be a wallet-owned BlockRun phone number — use ListPhoneNumbers to find ' +
232
+ ' - `from` MUST be a BlockRun-provisioned phone number — use ListPhoneNumbers to find ' +
232
233
  'one or BuyPhoneNumber to provision one ($5, 30-day lease).\n' +
233
234
  ' - `to` and `from` must be E.164 format (+ country code prefix, e.g. +14155552671).\n' +
234
235
  ' - `task` must be ≥10 chars, ≤4000 chars.\n' +
@@ -306,7 +307,7 @@ export const voiceCallCapability = {
306
307
  if (typeof input.to !== 'string')
307
308
  return { output: 'to (E.164) required', isError: true };
308
309
  if (typeof input.from !== 'string')
309
- return { output: 'from (wallet-owned E.164) required — use ListPhoneNumbers / BuyPhoneNumber', isError: true };
310
+ return { output: 'from (BlockRun-provisioned E.164) required — use ListPhoneNumbers / BuyPhoneNumber', isError: true };
310
311
  if (typeof input.task !== 'string' || input.task.length < 10) {
311
312
  return { output: 'task required (10–4000 chars natural-language description)', isError: true };
312
313
  }
@@ -345,7 +346,7 @@ export const voiceCallCapability = {
345
346
  }
346
347
  catch { /* best-effort */ }
347
348
  return {
348
- output: `## Voice call initiated ($0.54 USDC charged)\n\n` +
349
+ output: `## Voice call initiated (${chargedNote(0.54)})\n\n` +
349
350
  `**call_id:** \`${callId}\`\n\nPoll with VoiceStatus call_id="${callId}" to get the ` +
350
351
  `transcript and disposition. The call typically completes in 1–6 minutes.\n\n` +
351
352
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
@@ -40,6 +40,30 @@ export interface ReservationToken {
40
40
  * Callers pass `graceMs = timeoutMs + AMBIGUOUS_GRACE_MS`.
41
41
  */
42
42
  export declare const AMBIGUOUS_GRACE_MS = 30000;
43
+ /**
44
+ * A Solana zero is not a balance — it is the SDK's error value too.
45
+ *
46
+ * `SolanaLLMClient.getBalance()` catches every transport error and returns 0,
47
+ * and an RPC that answers 200 with a JSON-RPC error body reaches the same 0
48
+ * through `data.result?.value || []`. So a zero means "empty wallet" OR "the
49
+ * endpoint is not answering", and Franklin cannot tell which from the number.
50
+ *
51
+ * Refusing on it is the worse mistake of the two. A false zero blocks every
52
+ * paid tool for the length of an RPC blip — precisely the outcome
53
+ * `fetchBalance`'s fail-open exists to prevent — while trusting it costs
54
+ * nothing when the wallet really is empty, because those calls fail at payment
55
+ * anyway. The reservation layer's job is stopping concurrent calls from
56
+ * over-committing a KNOWN balance; there is nothing to over-commit at zero.
57
+ *
58
+ * This THROWS rather than returning Infinity on purpose. `fetchBalance` prunes
59
+ * ambiguous settlement entries only on a read that came back, so a throw both
60
+ * trips the fail-open and keeps those holds from being pruned against a number
61
+ * that reflects nothing (blockrun#140).
62
+ *
63
+ * Base is unaffected: its `getBalance()` propagates errors, so a zero there is
64
+ * a real zero.
65
+ */
66
+ export declare function readSolanaBalance(getBalance: () => Promise<number>): Promise<number>;
43
67
  declare class WalletReservationManager {
44
68
  private reserved;
45
69
  private ambiguous;
@@ -30,6 +30,7 @@
30
30
  */
31
31
  import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
32
32
  import { loadChain } from '../config.js';
33
+ import { fetchCreditBalance, isKeyMode } from '../payments/auth-mode.js';
33
34
  const BALANCE_CACHE_MS = 5_000;
34
35
  /**
35
36
  * Settlement margin added on top of the caller-supplied request timeout for
@@ -39,10 +40,55 @@ const BALANCE_CACHE_MS = 5_000;
39
40
  * Callers pass `graceMs = timeoutMs + AMBIGUOUS_GRACE_MS`.
40
41
  */
41
42
  export const AMBIGUOUS_GRACE_MS = 30_000;
42
- async function readChainBalance() {
43
+ /**
44
+ * A Solana zero is not a balance — it is the SDK's error value too.
45
+ *
46
+ * `SolanaLLMClient.getBalance()` catches every transport error and returns 0,
47
+ * and an RPC that answers 200 with a JSON-RPC error body reaches the same 0
48
+ * through `data.result?.value || []`. So a zero means "empty wallet" OR "the
49
+ * endpoint is not answering", and Franklin cannot tell which from the number.
50
+ *
51
+ * Refusing on it is the worse mistake of the two. A false zero blocks every
52
+ * paid tool for the length of an RPC blip — precisely the outcome
53
+ * `fetchBalance`'s fail-open exists to prevent — while trusting it costs
54
+ * nothing when the wallet really is empty, because those calls fail at payment
55
+ * anyway. The reservation layer's job is stopping concurrent calls from
56
+ * over-committing a KNOWN balance; there is nothing to over-commit at zero.
57
+ *
58
+ * This THROWS rather than returning Infinity on purpose. `fetchBalance` prunes
59
+ * ambiguous settlement entries only on a read that came back, so a throw both
60
+ * trips the fail-open and keeps those holds from being pruned against a number
61
+ * that reflects nothing (blockrun#140).
62
+ *
63
+ * Base is unaffected: its `getBalance()` propagates errors, so a zero there is
64
+ * a real zero.
65
+ */
66
+ export async function readSolanaBalance(getBalance) {
67
+ const balance = await getBalance();
68
+ if (balance === 0) {
69
+ throw new Error('Solana balance read returned 0, which the SDK also returns on RPC failure — treating the balance as unknown');
70
+ }
71
+ return balance;
72
+ }
73
+ async function readSpendableBalance() {
74
+ // Key mode has no wallet to read. Gating on one made every Modal call fail
75
+ // with "Insufficient USDC — fund the wallet" for a user whose account
76
+ // credits were fine, because an unfunded (or absent) wallet reads $0.
77
+ //
78
+ // The right ceiling in key mode is the prepaid balance, so use it when the
79
+ // gateway reports one. `remainingUsd: null` means an ungated account with
80
+ // no ceiling, and a null balance means the gateway was unreachable — in
81
+ // both cases return Infinity rather than invent a limit. That is not
82
+ // "unbounded": the gateway still 402s when credits run out, and --max-spend
83
+ // still bounds the session. This layer only prevents Franklin from
84
+ // over-committing against a balance it can actually see.
85
+ if (isKeyMode()) {
86
+ const credit = await fetchCreditBalance().catch(() => null);
87
+ return credit?.remainingUsd ?? Number.POSITIVE_INFINITY;
88
+ }
43
89
  if (loadChain() === 'solana') {
44
90
  const client = await setupAgentSolanaWallet({ silent: true });
45
- return client.getBalance();
91
+ return readSolanaBalance(() => client.getBalance());
46
92
  }
47
93
  const client = setupAgentWallet({ silent: true });
48
94
  return client.getBalance();
@@ -52,7 +98,7 @@ class WalletReservationManager {
52
98
  ambiguous = new Map();
53
99
  cachedBalance = null;
54
100
  balanceFetchInflight = null;
55
- balanceFetcher = readChainBalance;
101
+ balanceFetcher = readSpendableBalance;
56
102
  async fetchBalance() {
57
103
  if (this.cachedBalance && Date.now() - this.cachedBalance.fetchedAt < BALANCE_CACHE_MS) {
58
104
  return this.cachedBalance.value;
@@ -171,7 +217,7 @@ class WalletReservationManager {
171
217
  this.ambiguous.clear();
172
218
  this.cachedBalance = null;
173
219
  this.balanceFetchInflight = null;
174
- this.balanceFetcher = fetcher ?? readChainBalance;
220
+ this.balanceFetcher = fetcher ?? readSpendableBalance;
175
221
  }
176
222
  /** Testing only — seed the balance cache so hold() never touches RPC. */
177
223
  _seedBalanceForTests(value) {
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Detect a Solana wallet the upgrade silently stopped using (blockrun#119).
3
+ *
4
+ * Franklin 3.35.6 tightened SDK wallet selection: startup now takes
5
+ * `SOLANA_WALLET_KEY`, then `~/.blockrun/.solana-session`, then creates a new
6
+ * wallet. The legacy `~/.blockrun/solana-wallet.json` is no longer selected.
7
+ * That was a deliberate security fix and it stays.
8
+ *
9
+ * What it left behind is a silent address change. The SDK prints a migration
10
+ * notice, but only when it CREATES a wallet — and the install that hurts has a
11
+ * `.solana-session` already, so nothing is created, nothing is printed, and the
12
+ * user is simply on a different address than the one holding their USDC.
13
+ *
14
+ * This module only looks. It derives public addresses (never trusting the
15
+ * `address` field in a file, and never reading a key it does not derive from),
16
+ * and reports a divergence for `franklin doctor` to show. Adopting one is an
17
+ * explicit, separate act — `franklin wallet-adopt <address>` — because the
18
+ * whole complaint is that the active wallet changed without anyone asking.
19
+ */
20
+ export interface SolanaWalletDivergence {
21
+ /** Address Franklin will actually spend from, or null if none is active. */
22
+ active: string | null;
23
+ /** Discovered wallets whose address differs from the active one. */
24
+ alternatives: Array<{
25
+ address: string;
26
+ source: string;
27
+ }>;
28
+ }
29
+ /**
30
+ * The address the SDK will select, derived from the canonical session file.
31
+ *
32
+ * Deliberately does not call `getOrCreateSolanaWallet()`: that CREATES a wallet
33
+ * as a side effect, which is exactly the wrong thing to do inside a diagnostic
34
+ * that is trying to tell the user which wallet they already have. Same
35
+ * primitives the signing path uses.
36
+ */
37
+ export declare function activeSolanaAddress(): string | null;
38
+ /**
39
+ * Wallets on this machine that Franklin can see but is not using.
40
+ *
41
+ * Returns null when there is nothing to say — no active wallet, or every
42
+ * discovered wallet is the active one. `listDiscoveredSolanaWallets()` derives
43
+ * each address from the secret key rather than trusting the file, and returns
44
+ * no secret material.
45
+ */
46
+ export declare function detectSolanaWalletDivergence(): Promise<SolanaWalletDivergence | null>;
47
+ /** One-line-per-wallet report. Public addresses only. */
48
+ export declare function formatDivergence(d: SolanaWalletDivergence): string;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Detect a Solana wallet the upgrade silently stopped using (blockrun#119).
3
+ *
4
+ * Franklin 3.35.6 tightened SDK wallet selection: startup now takes
5
+ * `SOLANA_WALLET_KEY`, then `~/.blockrun/.solana-session`, then creates a new
6
+ * wallet. The legacy `~/.blockrun/solana-wallet.json` is no longer selected.
7
+ * That was a deliberate security fix and it stays.
8
+ *
9
+ * What it left behind is a silent address change. The SDK prints a migration
10
+ * notice, but only when it CREATES a wallet — and the install that hurts has a
11
+ * `.solana-session` already, so nothing is created, nothing is printed, and the
12
+ * user is simply on a different address than the one holding their USDC.
13
+ *
14
+ * This module only looks. It derives public addresses (never trusting the
15
+ * `address` field in a file, and never reading a key it does not derive from),
16
+ * and reports a divergence for `franklin doctor` to show. Adopting one is an
17
+ * explicit, separate act — `franklin wallet-adopt <address>` — because the
18
+ * whole complaint is that the active wallet changed without anyone asking.
19
+ */
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import bs58 from 'bs58';
23
+ import { Keypair } from '@solana/web3.js';
24
+ import { BLOCKRUN_DIR } from '../config.js';
25
+ /**
26
+ * The address the SDK will select, derived from the canonical session file.
27
+ *
28
+ * Deliberately does not call `getOrCreateSolanaWallet()`: that CREATES a wallet
29
+ * as a side effect, which is exactly the wrong thing to do inside a diagnostic
30
+ * that is trying to tell the user which wallet they already have. Same
31
+ * primitives the signing path uses.
32
+ */
33
+ export function activeSolanaAddress() {
34
+ try {
35
+ const key = fs.readFileSync(path.join(BLOCKRUN_DIR, '.solana-session'), 'utf-8').trim();
36
+ if (!key)
37
+ return null;
38
+ return Keypair.fromSecretKey(bs58.decode(key)).publicKey.toBase58();
39
+ }
40
+ catch {
41
+ return null; // absent, unreadable, or not a key we can derive from
42
+ }
43
+ }
44
+ /**
45
+ * Wallets on this machine that Franklin can see but is not using.
46
+ *
47
+ * Returns null when there is nothing to say — no active wallet, or every
48
+ * discovered wallet is the active one. `listDiscoveredSolanaWallets()` derives
49
+ * each address from the secret key rather than trusting the file, and returns
50
+ * no secret material.
51
+ */
52
+ export async function detectSolanaWalletDivergence() {
53
+ const active = activeSolanaAddress();
54
+ if (!active)
55
+ return null;
56
+ let discovered = [];
57
+ try {
58
+ const { listDiscoveredSolanaWallets } = await import('@blockrun/llm');
59
+ discovered = await listDiscoveredSolanaWallets();
60
+ }
61
+ catch {
62
+ return null; // SDK unavailable or scan failed — a diagnostic must not throw
63
+ }
64
+ const alternatives = discovered.filter((w) => w.address !== active);
65
+ if (alternatives.length === 0)
66
+ return null;
67
+ return { active, alternatives };
68
+ }
69
+ /** One-line-per-wallet report. Public addresses only. */
70
+ export function formatDivergence(d) {
71
+ const lines = [
72
+ `Active Solana wallet: ${d.active}`,
73
+ `Franklin can also see ${d.alternatives.length} other wallet(s) on this machine:`,
74
+ ...d.alternatives.map((w) => ` ${w.address} (${w.source})`),
75
+ '',
76
+ 'If your USDC is on one of those, Franklin is not spending from it. Adopt it with:',
77
+ ` franklin wallet-adopt <address>`,
78
+ 'The current session file is backed up before anything is replaced.',
79
+ ];
80
+ return lines.join('\n');
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.44.0",
3
+ "version": "3.46.0",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -38,7 +38,7 @@
38
38
  "desktop:package:win": "npm run dist:win --workspace @blockrun/franklin-desktop",
39
39
  "dev": "tsc --watch",
40
40
  "start": "node dist/index.js",
41
- "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs",
41
+ "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs",
42
42
  "test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
43
43
  "e2e:polymarket:readonly": "npm run build && node scripts/polymarket-e2e-readonly.mjs",
44
44
  "test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",