@blockrun/franklin 3.45.0 → 3.47.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 (57) hide show
  1. package/README.md +32 -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/start.js +4 -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/free-models.js +2 -1
  17. package/dist/gateway-models.js +34 -66
  18. package/dist/index.js +16 -0
  19. package/dist/model-catalog.d.ts +10 -0
  20. package/dist/model-catalog.js +77 -0
  21. package/dist/payments/auth-mode.d.ts +5 -19
  22. package/dist/payments/auth-mode.js +15 -17
  23. package/dist/payments/billing-copy.d.ts +37 -0
  24. package/dist/payments/billing-copy.js +57 -0
  25. package/dist/payments/post-with-payment.js +8 -15
  26. package/dist/payments/price-catalog.d.ts +9 -0
  27. package/dist/payments/price-catalog.js +13 -0
  28. package/dist/payments/usage.d.ts +106 -0
  29. package/dist/payments/usage.js +168 -0
  30. package/dist/pricing.d.ts +2 -6
  31. package/dist/pricing.js +16 -3
  32. package/dist/router/vision.js +9 -1
  33. package/dist/stats/tracker.d.ts +9 -1
  34. package/dist/stats/tracker.js +6 -1
  35. package/dist/tools/bash.js +17 -7
  36. package/dist/tools/blockrun.js +1 -1
  37. package/dist/tools/defillama.js +2 -2
  38. package/dist/tools/imagegen.js +5 -4
  39. package/dist/tools/modal.js +12 -6
  40. package/dist/tools/musicgen.js +4 -3
  41. package/dist/tools/phone.js +16 -15
  42. package/dist/tools/prediction.js +12 -11
  43. package/dist/tools/realface.js +2 -2
  44. package/dist/tools/rpc.js +2 -2
  45. package/dist/tools/sensitive-paths.d.ts +1 -1
  46. package/dist/tools/sensitive-paths.js +13 -4
  47. package/dist/tools/surf.js +2 -2
  48. package/dist/tools/videogen.js +6 -5
  49. package/dist/tools/voice.d.ts +1 -1
  50. package/dist/tools/voice.js +5 -4
  51. package/dist/ui/model-picker.d.ts +1 -2
  52. package/dist/ui/model-picker.js +34 -117
  53. package/dist/wallet/reservation.d.ts +24 -0
  54. package/dist/wallet/reservation.js +50 -4
  55. package/dist/wallet/solana-migration.d.ts +48 -0
  56. package/dist/wallet/solana-migration.js +81 -0
  57. package/package.json +6 -4
package/README.md CHANGED
@@ -121,7 +121,7 @@ VS Code → Extensions (Cmd+Shift+X / Ctrl+Shift+X)
121
121
  → click the Franklin icon in the Activity Bar
122
122
  ```
123
123
 
124
- Free models work immediately. Paid models, image gen, and video gen activate the moment your wallet has USDC. The CLI and the extension share the same `~/.blockrun/` config and session history, so jumping between terminal and VS Code is seamless.
124
+ Free models work immediately. Paid models, image gen, and video gen use your selected payment method: funded API account credit or a USDC wallet. The CLI and the extension share the same `~/.blockrun/` config and session history, so jumping between terminal and VS Code is seamless.
125
125
 
126
126
  ### Franklin Desktop (Beta)
127
127
 
@@ -205,8 +205,10 @@ franklin balance --wallet # show the wallet balance, not the key status
205
205
  ```
206
206
 
207
207
  If the key is rejected, or a tool needs an endpoint the key gateway does not serve,
208
- Franklin falls back to the wallet for that call and tells you. It never falls back on a
209
- malformed request — a bad call is never retried with your USDC.
208
+ Franklin returns that API error without charging a wallet. Correct the key or explicitly
209
+ retry with `--wallet`. An empty or malformed configured key is an error; remove it to
210
+ return to the wallet default. `franklin logout` removes the saved key; if
211
+ `BLOCKRUN_API_KEY` is exported, unset it too.
210
212
 
211
213
  ### Spend tracking, and the one thing that stays an estimate
212
214
 
@@ -339,7 +341,7 @@ Every trade journals itself: thesis on open, P&L on close, written to a **wallet
339
341
  Saved: generated-logo-1713052800.png (1024x1024)
340
342
  ```
341
343
 
342
- Generates images via DALL-E / GPT Image directly from the CLI. Paid from your wallet — no OpenAI API key needed.
344
+ Generates images via DALL-E / GPT Image directly from the CLI. Paid from your selected BlockRun API account or wallet — no OpenAI API key needed.
343
345
 
344
346
  ### 📱 Remote control via Telegram
345
347
 
@@ -380,7 +382,7 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
380
382
 
381
383
  ## Smart Router
382
384
 
383
- **<!-- br:models.chatVisible -->76<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
385
+ **<!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
384
386
 
385
387
  You don't pick models. Franklin picks for you.
386
388
 
@@ -461,7 +463,7 @@ No email. No phone. No KYC. Your Solana or Base address is your account — port
461
463
  | Writes code | ✅ | ✅ | ⚠️ | ✅ |
462
464
  | **Spends money for you** | ❌ | ❌ | ❌ | ✅ **USDC wallet, x402** |
463
465
  | **Buys data + APIs + images + search** | ❌ | ❌ | ❌ | ✅ **55+ APIs, one wallet** |
464
- | Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->76<!-- /br:models.chatVisible --> models** |
466
+ | Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models** |
465
467
  | Pricing model | Subscription | Subscription | Subscription | **YOPO** — per outcome, USDC |
466
468
  | Monthly fee | $20–$200 | $20–$40 | $20+ | **$0** |
467
469
  | Rate-limited | Yes | Yes | Yes | No — limited only by wallet |
@@ -489,14 +491,14 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
489
491
  **🎨 AI image generation**
490
492
  Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
491
493
 
492
- **🧠 <!-- br:models.chatVisible -->76<!-- /br:models.chatVisible --> models via one wallet**
494
+ **🧠 <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models via one wallet**
493
495
  Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, NVIDIA free tier. One wallet, one interface, automatic fallback.
494
496
 
495
497
  **💳 x402 micropayments (YOPO)**
496
498
  HTTP 402 native. Every paid action is a signed USDC micropayment via EIP-712 — non-custodial, your keys never leave your machine. YOPO: you pay only for outcomes.
497
499
 
498
500
  **🧠 Learned model router**
499
- Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->76<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
501
+ Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
500
502
 
501
503
  </td>
502
504
  <td width="50%" valign="top">
@@ -552,13 +554,13 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
552
554
  │ Intent → Smart Router → Tool Use → Spend Control → Result │
553
555
  ├──────────────────────────────────────────────────────────────┤
554
556
  │ Learned Router │
555
- │ 2M+ requests · <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
557
+ │ 2M+ requests · <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
556
558
  ├──────────────────────────────────────────────────────────────┤
557
559
  │ Agent Loop │
558
560
  │ 16 tools · Sessions · Compaction · Pricing · Plugin SDK │
559
561
  ├──────────────────────────────────────────────────────────────┤
560
562
  │ BlockRun Gateway │
561
- │ <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
563
+ │ <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
562
564
  ├──────────────────────────────────────────────────────────────┤
563
565
  │ x402 Micropayment Protocol │
564
566
  │ HTTP 402 · USDC on Solana & Base · signed payment payloads │
@@ -602,7 +604,7 @@ src/
602
604
  ├── stats/ Usage tracking + insights engine
603
605
  ├── ui/ Ink-based terminal UI
604
606
  ├── proxy/ Payment proxy for external tools
605
- ├── router/ Learned model router (<!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models, Elo scoring)
607
+ ├── router/ Learned model router (<!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models, Elo scoring)
606
608
  ├── wallet/ Wallet management (Base + Solana)
607
609
  ├── mcp/ MCP server auto-discovery
608
610
  └── commands/ CLI subcommands
@@ -713,6 +715,25 @@ For the recommended live validation order and failure triage, see [docs/live-e2e
713
715
 
714
716
  ---
715
717
 
718
+ ## Shared model catalog
719
+
720
+ Franklin uses [BlockRun Model Core](https://github.com/BlockRunAI/model-catalog)
721
+ for model metadata, picker policy and price estimates. The runtime dependency
722
+ is pinned to an immutable commit. On refresh, Franklin reads the public current
723
+ snapshot and the active gateway's catalog, so new models and prices can appear
724
+ without a Franklin release. Base, Solana and API accounts have separate caches.
725
+
726
+ Updates are validated before use. Requests have a four-second deadline each,
727
+ refreshes are cached for five minutes, and failures retain the last valid data
728
+ (or the bundled snapshot on first launch). `BLOCKRUN_MODEL_CATALOG_URL` can
729
+ override the public snapshot URL; an empty value disables remote policy updates.
730
+ `FRANKLIN_CATALOG_OFFLINE=1` uses bundled data without catalog network requests.
731
+
732
+ Existing free shortcuts remain free. Historical explicit IDs and cost records
733
+ remain usable; rolling aliases may select newer models at different prices.
734
+ Payment signing and settlement remain in Franklin and its payment SDK. Auto
735
+ routing's candidate policy remains separate from the shared catalog pilot.
736
+
716
737
  ## License
717
738
 
718
739
  Apache-2.0. See [LICENSE](LICENSE).
@@ -10,21 +10,41 @@ import { getWalletAddress as getBaseWalletAddress } from '@blockrun/llm';
10
10
  import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
12
12
  import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt } from '../learnings/store.js';
13
+ import { isKeyMode, resolvePayMode } from '../payments/auth-mode.js';
13
14
  // ─── System Instructions Assembly ──────────────────────────────────────────
14
15
  // Composable prompt sections — each independently maintainable and conditionally includable.
15
16
  function getCoreInstructions() {
16
- return `You are Franklin, an autonomous AI agent with a wallet. You help users with software engineering, marketing campaigns, trading signals, and any task that benefits from an agent that can reason, act, and spend.
17
+ // Key mode has no wallet. getWalletKnowledgeSection() below already branches
18
+ // on this; these lines did not, so every key-mode turn briefed the model on
19
+ // a wallet it cannot read and a USDC balance it cannot spend — then pointed
20
+ // the Wallet tool at it, which returns a portal link instead. Keep the
21
+ // spend-without-hesitating posture either way; only the funding source
22
+ // changes.
23
+ const keyMode = isKeyMode();
24
+ const identity = keyMode
25
+ ? 'an autonomous AI agent that pays its own way with prepaid BlockRun account credits'
26
+ : 'an autonomous AI agent with a wallet';
27
+ const walletTool = keyMode
28
+ ? '- **Wallet** — reports that this session bills prepaid account credits and where to manage them. Use it for any "what\'s my balance / how much money / billing status" question instead of running \`franklin balance\` via Bash. Free, one call.'
29
+ : '- **Wallet** — read your own chain, address, and USDC balance. Use this for any "what\'s my balance / how much money / wallet status" question instead of running \`franklin balance\` via Bash. Free, one call, never costs USDC.';
30
+ const tradingMarket = keyMode
31
+ ? '- **TradingMarket** — current stock / FX / crypto / commodity prices (BlockRun Gateway / Pyth; billed to account credits, $0.001/stock call, free for everything else).'
32
+ : '- **TradingMarket** — current stock / FX / crypto / commodity prices (BlockRun Gateway / Pyth; wallet pays automatically, $0.001/stock call, free for everything else).';
33
+ const spendPosture = keyMode
34
+ ? 'Your brand is spending real money to get real answers; $0.001 for a stock quote is exactly what the account credits are for. Don\'t hesitate on cents.'
35
+ : 'Your brand is spending USDC to get real answers; $0.001 for a stock quote is exactly what the wallet is for. Don\'t hesitate on cents.';
36
+ return `You are Franklin, ${identity}. You help users with software engineering, marketing campaigns, trading signals, and any task that benefits from an agent that can reason, act, and spend.
17
37
 
18
38
  You are an interactive agent — not a chatbot. Use the tools available to you to accomplish tasks. Your job is to be a highly capable collaborator who takes initiative, makes progress, and delivers results.
19
39
 
20
40
  # Franklin has hands
21
41
  You run with live tools by default:
22
- - **Wallet** — read your own chain, address, and USDC balance. Use this for any "what's my balance / how much money / wallet status" question instead of running \`franklin balance\` via Bash. Free, one call, never costs USDC.
23
- - **TradingMarket** — current stock / FX / crypto / commodity prices (BlockRun Gateway / Pyth; wallet pays automatically, $0.001/stock call, free for everything else).
42
+ ${walletTool}
43
+ ${tradingMarket}
24
44
  - **ExaAnswer / ExaSearch / ExaReadUrls** — cited current-events answers, semantic web search, clean URL content.
25
45
  - **WebSearch / WebFetch** — live web.
26
46
 
27
- When a user asks for a current price, today's news, or any live-world state, **call the tool**. Refusal phrases like "I can't provide real-time data" or "check Yahoo Finance" are a bug — they belong to systems without tools. Your brand is spending USDC to get real answers; $0.001 for a stock quote is exactly what the wallet is for. Don't hesitate on cents.
47
+ When a user asks for a current price, today's news, or any live-world state, **call the tool**. Refusal phrases like "I can't provide real-time data" or "check Yahoo Finance" are a bug — they belong to systems without tools. ${spendPosture}
28
48
 
29
49
  # System
30
50
  - All text you output outside of tool use is displayed to the user. Use markdown for formatting.
@@ -230,22 +250,39 @@ Hard rules:
230
250
  - If \`open\` fails (e.g. no GUI on a remote box), fall back to giving them the URL as plain text and tell them to paste it into a browser.`;
231
251
  }
232
252
  function getBlockRunApiSection() {
253
+ // Which host answers depends on how this session pays, and the three are not
254
+ // interchangeable: api.blockrun.ai authenticates a bearer key and 401s
255
+ // without one, while blockrun.ai / sol.blockrun.ai answer a 402 challenge and
256
+ // ignore a bearer key entirely. This section used to call api.blockrun.ai an
257
+ // "alias" of the Base gateway, which invited the model to send a wallet-signed
258
+ // request to a host that cannot settle it, or a key to a host that cannot read
259
+ // it. Name the one host this session actually uses.
260
+ //
261
+ // assembleInstructions() keys its cache on the pay mode, so this is safe to
262
+ // vary and cannot be served stale after a switch.
263
+ const mode = resolvePayMode();
264
+ const chargedBy = mode.kind === 'key' ? 'account credits' : 'x402 wallet payment';
265
+ const hosts = mode.kind === 'key'
266
+ ? `- **Your host: \`https://api.blockrun.ai\`** — the account API. Requests carry your configured key; the built-in tools attach it. It is a SEPARATE service, not an alias of the Base gateway.
267
+ - Not yours: \`https://blockrun.ai/api\` (Base x402 wallet) and \`https://sol.blockrun.ai/api\` (Solana x402 wallet). They ignore an account key and answer 402. Never send one there, and never attach a wallet payment proof to an account request.`
268
+ : `- **Your host: \`${mode.apiBase}\`** — the ${mode.chain === 'solana' ? 'Solana' : 'Base'} x402 wallet gateway. Paid calls answer 402 and the tools sign from your ${mode.chain === 'solana' ? 'Solana' : 'Base'} wallet.
269
+ - Not yours: \`${mode.chain === 'solana' ? 'https://blockrun.ai/api' : 'https://sol.blockrun.ai/api'}\` (the other chain's wallet gateway) and \`https://api.blockrun.ai\` (the account API, which needs a key and 401s without one — it is not an alias of either wallet host).`;
233
270
  return `# BlockRun Gateway API (the network you live on)
234
271
  You run on the BlockRun AI Gateway. When the user asks you to "test the BlockRun API", "check all endpoints", or call the gateway directly, use ONLY the paths below. **Never invent, pluralize, or singularize an endpoint** — \`/v1/image/generate\` (singular) is wrong, \`/v1/images/generations\` (plural) is correct. If a path you have in mind isn't in this list, fetch the canonical discovery endpoints before calling it.
235
272
 
236
273
  **Base URLs**
237
- - Base chain: \`https://blockrun.ai/api\` (alias: \`https://api.blockrun.ai\`)
238
- - Solana chain: \`https://sol.blockrun.ai/api\`
274
+ ${hosts}
275
+ Use the built-in tools so the right host and credential are applied. Never switch billing modes to work around an API error.
239
276
 
240
277
  **Discovery (always free, GET) — fetch these BEFORE guessing a path**
241
278
  - \`GET /openapi.json\` (or \`/.well-known/openapi.json\`) — full OpenAPI 3.1 contract, every route + request schema
242
279
  - \`GET /.well-known/x402\` — x402 resource list with prices
243
280
 
244
- **LLM (POST, x402-paid)**
281
+ **LLM (POST, billed to ${chargedBy})**
245
282
  - \`POST /v1/chat/completions\` — OpenAI-compatible. Body: \`{ model, messages, stream?, tools?, max_tokens?, temperature? }\`. \`model\` MUST come from \`GET /v1/models\` (real frontier examples on the gateway, verified live 2026-08-30: \`anthropic/claude-sonnet-5\`, \`anthropic/claude-opus-5\`, \`openai/gpt-5.6-sol\`, \`deepseek/deepseek-v4-pro\`, \`zai/glm-5.3\`, \`zai/glm-5.3-flash\`, \`xai/grok-4.5\`, \`qwen/qwen3.7-flash\`, \`nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\` (free, the only free id on BOTH the Base and Solana gateways — the other free models are Base-only)). Do NOT invent versions like \`openai/gpt-5.1\` or \`xai/grok-5\` — those don't exist; the gateway 400s with the valid list in the error body, so when in doubt fetch \`GET /v1/models\` first.
246
283
  - \`POST /v1/messages\` — Anthropic-compatible. Body: \`{ model, messages, max_tokens, system?, tools? }\`.
247
284
 
248
- **Media (POST, x402-paid; GET to poll async jobs)**
285
+ **Media (POST, billed to ${chargedBy}; GET to poll async jobs)**
249
286
  - \`POST /v1/images/generations\` — text-to-image. Body: \`{ model, prompt, size?, n?, response_format? }\`.
250
287
  - \`POST /v1/images/image2image\` — image-to-image. Body: \`{ model, prompt, image, ... }\`.
251
288
  - \`GET /v1/images/generations/{id}\` — fetch a generated image by id.
@@ -253,7 +290,7 @@ You run on the BlockRun AI Gateway. When the user asks you to "test the BlockRun
253
290
  - \`GET /v1/videos/generations/{id}\` — poll video job (settles payment when complete).
254
291
  - \`POST /v1/audio/generations\` — music/audio. Body: \`{ model, prompt, ... }\`. Default \`model\`: \`minimax/music-2.5+\`.
255
292
 
256
- **Search (POST, x402-paid)**
293
+ **Search (POST, billed to ${chargedBy})**
257
294
  - \`POST /v1/search\` — Exa-backed web search. Body: \`{ query }\` (1–1000 chars).
258
295
  - \`/v1/exa/{...path}\` — Exa passthrough (answer / search / contents).
259
296
 
@@ -452,7 +489,18 @@ const _instructionCache = new Map();
452
489
  * Result is memoized per workingDir for the process lifetime.
453
490
  */
454
491
  export function assembleInstructions(workingDir, model) {
455
- const cacheKey = model ? `${workingDir}::${model}` : workingDir;
492
+ // The pay mode is part of the key because getCoreInstructions() and
493
+ // getWalletKnowledgeSection() both branch on it. invalidateKey() can demote
494
+ // a session from key mode to wallet mode mid-process after a 401, and
495
+ // without this the model would keep being told it bills account credits
496
+ // long after Franklin went back to signing from the wallet.
497
+ // Keyed on the full billing identity, not just key-vs-wallet: the gateway
498
+ // host and the wallet guidance both name the active CHAIN, so a
499
+ // base -> solana switch inside one process must not be served the previous
500
+ // chain's instructions. resolvePayMode() is memoised, so this is cheap.
501
+ const payMode = resolvePayMode();
502
+ const billing = payMode.kind === 'key' ? 'key' : `wallet:${payMode.chain}`;
503
+ const cacheKey = model ? `${workingDir}::${model}::${billing}` : `${workingDir}::${billing}`;
456
504
  const cached = _instructionCache.get(cacheKey);
457
505
  if (cached)
458
506
  return cached;
package/dist/agent/llm.js CHANGED
@@ -658,7 +658,9 @@ export class ModelClient {
658
658
  signal: requestController.signal,
659
659
  }), requestController, createModelTimeoutError('request', request.model, requestTimeoutMs), requestTimeoutMs);
660
660
  // Handle x402 payment
661
- if (response.status === 402) {
661
+ // Account 402 is a credit refusal. Only a request that started on
662
+ // the wallet rail may initiate a signing handshake.
663
+ if (response.status === 402 && !headers.Authorization) {
662
664
  if (this.debug)
663
665
  console.error('[franklin] Payment required — signing...');
664
666
  const signedPayment = await this.signPayment(response, request.model);
@@ -1012,11 +1014,17 @@ export class ModelClient {
1012
1014
  currentToolInput = '';
1013
1015
  }
1014
1016
  else if (currentThinking) {
1015
- collected.push({
1016
- type: 'thinking',
1017
- thinking: currentThinking,
1018
- ...(currentThinkingSignature ? { signature: currentThinkingSignature } : {}),
1019
- });
1017
+ if (currentThinkingSignature) {
1018
+ collected.push({
1019
+ type: 'thinking',
1020
+ thinking: currentThinking,
1021
+ signature: currentThinkingSignature,
1022
+ });
1023
+ }
1024
+ else if (this.debug) {
1025
+ console.error(`[franklin] Dropped unsigned native thinking block from ${request.model}; ` +
1026
+ 'provider requires thinking.signature on replay.');
1027
+ }
1020
1028
  currentThinking = '';
1021
1029
  currentThinkingSignature = '';
1022
1030
  }
@@ -1494,6 +1494,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1494
1494
  let callToolDefs = buildCallToolDefs();
1495
1495
  let callMaxTokens = maxTokens;
1496
1496
  let callSystemPrompt = systemPrompt;
1497
+ const toolCapFinalRound = toolCapWarned && turnToolCalls >= MAX_TOOL_CALLS_PER_TURN;
1497
1498
  if (planActive && loopCount === 1) {
1498
1499
  callToolDefs = []; // No tools during planning
1499
1500
  callMaxTokens = 2048; // Short plan output
@@ -1526,6 +1527,13 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1526
1527
  '\n\nThe image is already included above. Answer the question about it ' +
1527
1528
  'directly. Do not call any tools.';
1528
1529
  }
1530
+ if (toolCapFinalRound && callToolDefs.length > 0) {
1531
+ callToolDefs = [];
1532
+ callSystemPrompt = callSystemPrompt + '\n\n# Tool budget exhausted\n' +
1533
+ `You already used ${turnToolCalls} tool calls this turn and received a system stop signal. ` +
1534
+ 'No more tools are available. Based only on the results already in the conversation, ' +
1535
+ 'give the user a concise status/update now. If the work is incomplete, say exactly what remains.';
1536
+ }
1529
1537
  const onFinalTurn = config.forceAnswerOnFinalTurn && loopCount === maxTurns;
1530
1538
  const toolBudgetSpent = config.maxToolCalls != null && turnToolCalls >= config.maxToolCalls;
1531
1539
  if ((onFinalTurn || toolBudgetSpent) && callToolDefs.length > 0) {
@@ -1568,7 +1576,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1568
1576
  // Consume any pending forced tool_choice from the previous round's
1569
1577
  // grounding-retry decision. `tool_choice` is dropped automatically in
1570
1578
  // llm.ts if `tools` ended up empty, so it's safe to attach here.
1571
- const callToolChoice = forceToolChoiceNextRound;
1579
+ const callToolChoice = toolCapFinalRound ? null : forceToolChoiceNextRound;
1572
1580
  forceToolChoiceNextRound = null;
1573
1581
  // Wall-clock start of the model call. Used by the recordUsage call
1574
1582
  // a few hundred lines below so franklin-stats.json captures real
@@ -1627,11 +1635,16 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1627
1635
  .filter((p) => p.type === 'text')
1628
1636
  .map(p => p.text)
1629
1637
  .join('\n');
1630
- const repaired = callRepair.process(declaredCalls, reasoningText || null, contentText || null);
1631
- if (repaired.report.scavenged > 0) {
1632
- const novelCalls = repaired.calls.slice(declaredCalls.length);
1633
- responseParts = [...responseParts, ...novelCalls];
1634
- logger.warn(`[franklin] scavenged ${repaired.report.scavenged} leaked tool call(s) from ${config.model}: ${repaired.report.notes.join('; ')}`);
1638
+ if (callToolDefs.length > 0) {
1639
+ const repaired = callRepair.process(declaredCalls, reasoningText || null, contentText || null);
1640
+ if (repaired.report.scavenged > 0) {
1641
+ const novelCalls = repaired.calls.slice(declaredCalls.length);
1642
+ responseParts = [...responseParts, ...novelCalls];
1643
+ logger.warn(`[franklin] scavenged ${repaired.report.scavenged} leaked tool call(s) from ${config.model}: ${repaired.report.notes.join('; ')}`);
1644
+ }
1645
+ }
1646
+ else if (declaredCalls.length > 0) {
1647
+ logger.warn(`[franklin] Dropping ${declaredCalls.length} tool call(s) because tools are disabled for this round`);
1635
1648
  }
1636
1649
  // Strip pure roleplayed-JSON tool-call text parts. The LLM client
1637
1650
  // holds these out of the live stream (never shown) but keeps them
@@ -1641,6 +1654,9 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1641
1654
  // also empties the turn, so the empty-response recovery below can
1642
1655
  // switch models, preserving the prior behavior.
1643
1656
  responseParts = responseParts.filter(p => !(p.type === 'text' && isRoleplayedJsonToolCallText(p.text)));
1657
+ if (callToolDefs.length === 0) {
1658
+ responseParts = responseParts.filter(p => p.type !== 'tool_use');
1659
+ }
1644
1660
  }
1645
1661
  // ── Empty response recovery ──
1646
1662
  // If the model returns nothing, DON'T just retry the same model with the same input.
@@ -1648,6 +1664,18 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1648
1664
  const hasText = responseParts.some(p => p.type === 'text' && p.text?.trim());
1649
1665
  const hasTools = responseParts.some(p => p.type === 'tool_use');
1650
1666
  const hasThinking = responseParts.some(p => p.type === 'thinking');
1667
+ if (toolCapFinalRound && !hasText) {
1668
+ const spendNote = turnCostUsd > 0
1669
+ ? `${turnToolCalls} tool calls, $${turnCostUsd.toFixed(4)} spent this turn`
1670
+ : `${turnToolCalls} tool calls this turn`;
1671
+ logger.error(`[franklin] Tool cap final-answer round produced no text after tools were disabled — ending turn`);
1672
+ onEvent({
1673
+ kind: 'text_delta',
1674
+ text: `\n\n⚠️ Tool loop stopped: ${spendNote}. Franklin disabled tools after the cap warning, but the model did not produce a final status. Try rephrasing or use \`/model\` to switch.\n`,
1675
+ });
1676
+ onEvent({ kind: 'turn_done', reason: 'cap_exceeded' });
1677
+ break;
1678
+ }
1651
1679
  if (!hasText && !hasTools && !hasThinking) {
1652
1680
  // Free-only recovery chain — a free/empty-response session must NEVER
1653
1681
  // fall back to a paid model (would silently charge the wallet). Both
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Five layers of optimization to minimize token usage:
5
5
  * 1. Tool result size budgeting — cap large outputs, keep preview
6
- * 2. Thinking block stripping — remove old thinking from history
6
+ * 2. Thinking block stripping — remove old/invalid thinking from history
7
7
  * 3. Time-based cleanup — clear stale tool results after idle gap
8
8
  * 4. Adaptive max_tokens — start low (8K), escalate on hit
9
9
  * 5. Pre-compact stripping — remove images/docs before summarization
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Five layers of optimization to minimize token usage:
5
5
  * 1. Tool result size budgeting — cap large outputs, keep preview
6
- * 2. Thinking block stripping — remove old thinking from history
6
+ * 2. Thinking block stripping — remove old/invalid thinking from history
7
7
  * 3. Time-based cleanup — clear stale tool results after idle gap
8
8
  * 4. Adaptive max_tokens — start low (8K), escalate on hit
9
9
  * 5. Pre-compact stripping — remove images/docs before summarization
@@ -204,9 +204,14 @@ export function budgetToolResults(history) {
204
204
  }
205
205
  // ─── 2. Thinking Block Stripping ───────────────────────────────────────────
206
206
  /**
207
- * Remove thinking blocks from older assistant messages.
208
- * Keeps thinking only in the most recent N assistant messages (default: last 2 turns).
209
- * Older thinking blocks are large and not needed after the decision is made.
207
+ * Remove thinking blocks from older assistant messages and any unsigned native
208
+ * thinking blocks. Anthropic-compatible APIs require `thinking.signature` when
209
+ * a prior assistant thinking block is replayed; an unsigned block poisons the
210
+ * next request with a 400, so it must never survive into outbound history.
211
+ *
212
+ * Keeps only signed thinking in the most recent N assistant messages (default:
213
+ * last 2 turns). Older thinking blocks are large and not needed after the
214
+ * decision is made.
210
215
  */
211
216
  const KEEP_THINKING_TURNS = 2;
212
217
  export function stripOldThinking(history) {
@@ -226,9 +231,14 @@ export function stripOldThinking(history) {
226
231
  let modified = false;
227
232
  for (let i = 0; i < history.length; i++) {
228
233
  const msg = history[i];
229
- // Strip thinking from assistant messages NOT in the keep set
230
- if (msg.role === 'assistant' && !keepSet.has(i) && Array.isArray(msg.content)) {
231
- const filtered = msg.content.filter((part) => part.type !== 'thinking');
234
+ // Strip old thinking, plus unsigned thinking even on recent turns.
235
+ if (msg.role === 'assistant' && Array.isArray(msg.content)) {
236
+ const filtered = msg.content.filter((part) => {
237
+ if (part.type !== 'thinking')
238
+ return true;
239
+ const signature = part.signature;
240
+ return keepSet.has(i) && typeof signature === 'string' && signature.trim().length > 0;
241
+ });
232
242
  if (filtered.length < msg.content.length) {
233
243
  modified = true;
234
244
  result.push({
@@ -62,6 +62,32 @@ export declare function redactSecrets(input: string): RedactionResult;
62
62
  * Returns the names of env vars that were set, deduped, in stash order.
63
63
  * Safe to call on an empty match list (no-op).
64
64
  */
65
+ /**
66
+ * Redact secrets from text Franklin did not author — tool output, not user
67
+ * input.
68
+ *
69
+ * `redactSecrets` above is the INPUT path: it scrubs what a user pastes into
70
+ * chat and hands the caller the raw values to stash on process.env. That is
71
+ * the wrong contract here. Tool output flows straight into the model prompt
72
+ * (over the network, to whichever gateway model serves the turn) and into the
73
+ * persisted session transcript on disk, so the value must not survive at all
74
+ * and there is nothing to stash.
75
+ *
76
+ * The case that forced this: `printenv` and `echo` are auto-approved by
77
+ * bash-guard as safe commands, so `printenv BLOCKRUN_API_KEY` needed no
78
+ * confirmation and returned the account bearer key as tool output. Stripping
79
+ * the variable from the Bash subprocess env (tools/bash.ts) closes that exact
80
+ * command; this closes the class — a key can still reach output via a config
81
+ * file, a `curl -v` trace, an MCP result, or a shell history dump.
82
+ *
83
+ * `extraLiterals` carries values known only at runtime, e.g. the configured
84
+ * API key when it does not match a published prefix shape. Empty and very
85
+ * short entries are ignored so a blank env var cannot blank out the text.
86
+ */
87
+ export declare function redactSecretsInOutput(input: string, extraLiterals?: readonly string[]): {
88
+ text: string;
89
+ labels: string[];
90
+ };
65
91
  export declare function stashSecretsToEnv(matches: RedactionMatch[]): string[];
66
92
  /**
67
93
  * Build a one-paragraph warning + usage hint to surface to the user when
@@ -216,6 +216,54 @@ export function redactSecrets(input) {
216
216
  * Returns the names of env vars that were set, deduped, in stash order.
217
217
  * Safe to call on an empty match list (no-op).
218
218
  */
219
+ /**
220
+ * Redact secrets from text Franklin did not author — tool output, not user
221
+ * input.
222
+ *
223
+ * `redactSecrets` above is the INPUT path: it scrubs what a user pastes into
224
+ * chat and hands the caller the raw values to stash on process.env. That is
225
+ * the wrong contract here. Tool output flows straight into the model prompt
226
+ * (over the network, to whichever gateway model serves the turn) and into the
227
+ * persisted session transcript on disk, so the value must not survive at all
228
+ * and there is nothing to stash.
229
+ *
230
+ * The case that forced this: `printenv` and `echo` are auto-approved by
231
+ * bash-guard as safe commands, so `printenv BLOCKRUN_API_KEY` needed no
232
+ * confirmation and returned the account bearer key as tool output. Stripping
233
+ * the variable from the Bash subprocess env (tools/bash.ts) closes that exact
234
+ * command; this closes the class — a key can still reach output via a config
235
+ * file, a `curl -v` trace, an MCP result, or a shell history dump.
236
+ *
237
+ * `extraLiterals` carries values known only at runtime, e.g. the configured
238
+ * API key when it does not match a published prefix shape. Empty and very
239
+ * short entries are ignored so a blank env var cannot blank out the text.
240
+ */
241
+ export function redactSecretsInOutput(input, extraLiterals = []) {
242
+ if (!input)
243
+ return { text: input, labels: [] };
244
+ let text = input;
245
+ const labels = [];
246
+ for (const literal of extraLiterals) {
247
+ const value = literal?.trim();
248
+ // 8 is below any credential this guards and above the length at which a
249
+ // stray value would collide with ordinary output.
250
+ if (!value || value.length < 8)
251
+ continue;
252
+ if (!text.includes(value))
253
+ continue;
254
+ text = text.split(value).join('[REDACTED:configured_credential]');
255
+ labels.push('configured_credential');
256
+ }
257
+ for (const { label, pattern } of SECRET_PATTERNS) {
258
+ pattern.lastIndex = 0;
259
+ if (!pattern.test(text))
260
+ continue;
261
+ pattern.lastIndex = 0;
262
+ text = text.replace(pattern, `[REDACTED:${label}]`);
263
+ labels.push(label);
264
+ }
265
+ return { text, labels: [...new Set(labels)] };
266
+ }
219
267
  export function stashSecretsToEnv(matches) {
220
268
  const set = [];
221
269
  for (const m of matches) {
@@ -8,6 +8,8 @@ import { join } from 'node:path';
8
8
  import { recordFailure } from '../stats/failures.js';
9
9
  import { estimateSpendUsd, isSpendTool } from '../tools/spend-tools.js';
10
10
  import { BLOCKRUN_DIR } from '../config.js';
11
+ import { redactSecretsInOutput } from './secret-redact.js';
12
+ import { resolvePayMode } from '../payments/auth-mode.js';
11
13
  import { logger } from '../logger.js';
12
14
  /** Persist a large tool result to disk and return a preview string. */
13
15
  const PERSIST_THRESHOLD = 50_000;
@@ -287,6 +289,19 @@ export class StreamingExecutor {
287
289
  const preview = (this.inputPreview(invocation) || '').replace(/[\r\n]+/g, ' ');
288
290
  logger.info(`[franklin] Slow tool: ${invocation.name} ${status} after ${(execElapsed / 1000).toFixed(1)}s${preview ? ` — ${preview.slice(0, 80)}` : ''}`);
289
291
  }
292
+ // Scrub credentials before the output goes anywhere. This is the one
293
+ // funnel every tool result passes through, and it runs BEFORE the
294
+ // persist-to-disk branch below so a redacted body is what reaches the
295
+ // model, the transcript, and the on-disk overflow file alike.
296
+ //
297
+ // resolvePayMode() is memoised per process, so reading the configured
298
+ // key here costs nothing per tool call.
299
+ const payMode = resolvePayMode();
300
+ const redacted = redactSecretsInOutput(result.output, payMode.kind === 'key' ? [payMode.key] : []);
301
+ if (redacted.labels.length > 0) {
302
+ logger.warn(`[franklin] Redacted ${redacted.labels.join(', ')} from ${invocation.name} output`);
303
+ result = { ...result, output: redacted.text };
304
+ }
290
305
  // Persist large results to disk with preview.
291
306
  // Instead of just truncating, save the full result to disk so it can be re-read later.
292
307
  if (result.output.length > PERSIST_THRESHOLD) {
@@ -287,6 +287,24 @@ async function runChecks() {
287
287
  remedy: 'Add /opt/homebrew/bin to PATH in ~/.zshrc',
288
288
  });
289
289
  }
290
+ // ── Solana wallet divergence (blockrun#119) ───────────────────────
291
+ // A tightened SDK selection can leave a user spending from a different
292
+ // address than the one holding their USDC, with nothing printed. Report it
293
+ // where they already look when money seems missing.
294
+ try {
295
+ const { detectSolanaWalletDivergence } = await import('../wallet/solana-migration.js');
296
+ const divergence = await detectSolanaWalletDivergence();
297
+ if (divergence) {
298
+ out.push({
299
+ name: 'Solana wallet',
300
+ status: 'warn',
301
+ detail: `active ${divergence.active}; ${divergence.alternatives.length} other wallet(s) found: ` +
302
+ divergence.alternatives.map((w) => w.address).join(', '),
303
+ remedy: 'If your USDC is on one of those: franklin wallet-adopt <address>',
304
+ });
305
+ }
306
+ }
307
+ catch { /* a diagnostic must never take down `franklin doctor` */ }
290
308
  return out;
291
309
  }
292
310
  function printHuman(checks) {
@@ -1,4 +1,5 @@
1
1
  import chalk from 'chalk';
2
+ import { refreshModelCatalog } from '../model-catalog.js';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
@@ -72,6 +73,9 @@ export async function startCommand(options) {
72
73
  chain = sessMeta.chain;
73
74
  }
74
75
  }
76
+ // Warm in the background: bundled data already covers startup, and the picker
77
+ // and pricing tables update in place when the refresh lands.
78
+ refreshModelCatalog({ network: chain }).catch(() => { });
75
79
  const apiUrl = gatewayBase();
76
80
  const config = loadConfig();
77
81
  // Resolve model. Priority: explicit --model > resumed session's model > user
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `franklin usage` — what the account actually charged, joined to what
3
+ * Franklin recorded.
4
+ *
5
+ * `franklin stats` reports Franklin's own tally, which in key mode is built
6
+ * from catalog prices because the account gateway settles without returning a
7
+ * charge. This command reports the gateway's ledger, which is authoritative,
8
+ * and lines the two up per request rather than comparing totals — a total that
9
+ * matches can still be two errors cancelling out.
10
+ */
11
+ export declare function usageCommand(opts?: {
12
+ days?: string;
13
+ json?: boolean;
14
+ }): Promise<void>;