@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
@@ -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 { chargeFromResponse, 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;
@@ -131,7 +132,7 @@ async function getWithPayment(path, query, ctx) {
131
132
  // restart). Without this, Predexon spend is absent from `franklin stats`
132
133
  // and invisible to the --max-spend ceiling (parity with surf.ts).
133
134
  try {
134
- 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));
135
136
  }
136
137
  catch { /* best-effort */ }
137
138
  return (await response.json());
@@ -409,7 +410,7 @@ async function execute(input, ctx) {
409
410
  lines.push(`${i + 1}. **[${platform}]** ${title}`);
410
411
  });
411
412
  }
412
- lines.push(`_$0.005 paid via x402._`);
413
+ lines.push(receiptLine(0.005));
413
414
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
414
415
  }
415
416
  case 'leaderboard': {
@@ -457,7 +458,7 @@ async function execute(input, ctx) {
457
458
  parts.push(`win ${formatPct(winRate, 0)}`);
458
459
  lines.push(`${i + 1}. \`${w}\`${handle}` + (parts.length > 0 ? ` — ${parts.join(' · ')}` : ''));
459
460
  });
460
- lines.push('', `_$0.001 paid via x402._`);
461
+ lines.push('', receiptLine(0.001));
461
462
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
462
463
  }
463
464
  case 'walletProfile': {
@@ -572,7 +573,7 @@ async function execute(input, ctx) {
572
573
  if (recent.length > 0)
573
574
  lines.push(` ${recent.join(' · ')}`);
574
575
  });
575
- lines.push('', `_$0.005 paid via x402._`);
576
+ lines.push('', receiptLine(0.005));
576
577
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
577
578
  }
578
579
  case 'walletPnl': {
@@ -648,7 +649,7 @@ async function execute(input, ctx) {
648
649
  });
649
650
  }
650
651
  }
651
- lines.push('', `_$0.005 paid via x402._`);
652
+ lines.push('', receiptLine(0.005));
652
653
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
653
654
  }
654
655
  case 'walletPositions': {
@@ -714,7 +715,7 @@ async function execute(input, ctx) {
714
715
  }
715
716
  lines.push(`${i + 1}. **${title}** — ${parts.join(' · ')}`);
716
717
  });
717
- lines.push('', `_$0.005 paid via x402._`);
718
+ lines.push('', receiptLine(0.005));
718
719
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
719
720
  }
720
721
  case 'smartActivity': {
@@ -755,7 +756,7 @@ async function execute(input, ctx) {
755
756
  stats.push(`${formatPct(netBuyersPct, 0)} net buyers`);
756
757
  lines.push(`${i + 1}. **${title}**${cidTag}` + (stats.length > 0 ? `\n ${stats.join(' · ')}` : ''));
757
758
  });
758
- lines.push('', `_$0.005 paid via x402._`);
759
+ lines.push('', receiptLine(0.005));
759
760
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
760
761
  }
761
762
  case 'smartMoney': {
@@ -810,7 +811,7 @@ async function execute(input, ctx) {
810
811
  perf.push(`win ${formatPct(pos.avg_smart_win_rate, 0)}`);
811
812
  lines.push(`**Smart performance:** ${perf.join(' · ')}`);
812
813
  }
813
- lines.push('', `_$0.005 paid via x402._`);
814
+ lines.push('', receiptLine(0.005));
814
815
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
815
816
  }
816
817
  case 'searchPolymarket': {
@@ -857,7 +858,7 @@ async function execute(input, ctx) {
857
858
  ` prices: ${yesPx} · vol: ${formatUsd(vol)} · liq: ${formatUsd(liq)}` +
858
859
  (end ? ` · ends ${String(end).slice(0, 10)}` : ''));
859
860
  });
860
- lines.push('', `_$0.001 paid via x402._`);
861
+ lines.push('', receiptLine(0.001));
861
862
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
862
863
  }
863
864
  case 'searchKalshi': {
@@ -893,7 +894,7 @@ async function execute(input, ctx) {
893
894
  ` yes ${yes} · vol: ${m.volume?.toLocaleString() ?? 'n/a'} · OI: ${m.open_interest?.toLocaleString() ?? 'n/a'}` +
894
895
  (m.close_time ? ` · closes ${String(m.close_time).slice(0, 10)}` : ''));
895
896
  });
896
- lines.push('', `_$0.001 paid via x402._`);
897
+ lines.push('', receiptLine(0.001));
897
898
  return { output: frameUntrusted('Prediction-market data (untrusted)', lines.join('\n')) };
898
899
  }
899
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 { chargeFromResponse, 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';
@@ -194,7 +194,7 @@ async function actionEnroll(base, chain, input, ctx) {
194
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) {
package/dist/tools/rpc.js CHANGED
@@ -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 { chargeFromResponse, 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';
@@ -94,7 +94,7 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
94
94
  // call from the published catalog instead of recording a free call.
95
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 {
@@ -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,7 @@
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 { basePriceForPath, chargeFromResponse, resolveCharge } from '../payments/price-catalog.js';
20
+ import { basePriceForPath, chargeFromResponse, requestIdFromResponse, resolveCharge } from '../payments/price-catalog.js';
21
21
  import { GATEWAY_TRANSACTION_FEE_USD } from '../gateway-models.js';
22
22
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
23
23
  import { frameUntrusted } from './untrusted.js';
@@ -218,7 +218,7 @@ async function callSurf(toolName, table, input, ctx) {
218
218
  ? resolveCharge({ apiPath: url, chargedUsd: chargeFromResponse(response), settledUsd: paidUsd })
219
219
  : { usd: 0, estimated: false };
220
220
  try {
221
- 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));
222
222
  }
223
223
  catch { /* best-effort */ }
224
224
  if (!response.ok) {
@@ -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.45.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",