@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/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
 
@@ -167,7 +167,7 @@ interchangeable. Everything else about the agent is identical.
167
167
  | Settlement | On-chain, per call, via [x402](https://x402.org) | Against a prepaid balance |
168
168
  | Gateway | `sol.blockrun.ai` / `blockrun.ai` | `api.blockrun.ai` |
169
169
  | Where the money lives | A wallet only you hold the key to | Your BlockRun account |
170
- | Spend visibility | `franklin stats` — exact settled amounts | [Dashboard](https://user.blockrun.ai/dashboard) — see the note below |
170
+ | Spend visibility | `franklin stats` — exact settled amounts | `franklin balance` + [dashboard](https://user.blockrun.ai/dashboard); exact except chat |
171
171
 
172
172
  **The wallet is still Franklin's identity.** Memory, the trading journal and goals are
173
173
  keyed to it, and the wallet route is the one that needs nothing from us — no signup, no
@@ -205,26 +205,38 @@ 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
- ### One honest caveat about spend tracking
213
+ ### Spend tracking, and the one thing that stays an estimate
212
214
 
213
215
  In wallet mode every charge is exact: the gateway states the price in the x402 handshake
214
216
  and Franklin records the amount that actually settled.
215
217
 
216
- In API-key mode the gateway settles silently against your balance and **returns no charge
217
- amount**. Franklin prices those calls locally from BlockRun's published x402 rate card, so
218
- `--max-spend`, `PreSpend` hooks and budgets all keep working — but the figures are
219
- estimates, and they lean high. The x402 rate card includes a 5% margin and a $0.001
220
- per-transaction fee that key mode does not charge (key mode bills provider list price;
221
- the fee is taken when you top up). Expect Franklin's local tally to read a few percent
222
- above what the dashboard shows.
218
+ In API-key mode most calls now report what they cost. The gateway returns an
219
+ `x-blockrun-cost-usd` header on the pre-priced service families — search, images, RPC,
220
+ market data, phone, sandboxes — and Franklin records that figure exactly.
223
221
 
224
- Over-counting is the safe direction for a spend ceiling, and Franklin is explicit about
225
- it: `franklin stats` marks estimated totals with `~` and reports the estimated portion
226
- separately, and `franklin balance` will not invent a credit balance it cannot read. For
227
- the authoritative number, use the [dashboard](https://user.blockrun.ai/dashboard).
222
+ **Chat is the exception, permanently.** Chat settles *after* the answer is on the wire, so
223
+ a slow settlement never becomes a slow answer, which means the amount does not exist yet
224
+ when the headers are written. Franklin reconstructs chat spend from token counts and the
225
+ published rate, so chat rows are estimates. `franklin stats` marks estimated totals with
226
+ `~` and reports the estimated portion separately, so you can always see which is which.
227
+
228
+ `franklin balance` reads your real credit standing from the gateway:
229
+
230
+ ```
231
+ Account: acme (gated)
232
+ Remaining: $41.9980 of $50.00 granted
233
+ Spent: $8.0020 (BlockRun, authoritative)
234
+ Local: ~$8.0431 (Franklin's own tally, all time, both pay modes — expected to differ)
235
+ ```
236
+
237
+ The two numbers differ on purpose: Franklin's tally covers both pay modes and estimates
238
+ chat, while BlockRun's is what you were actually billed. For the full per-call history,
239
+ use the [dashboard](https://user.blockrun.ai/dashboard).
228
240
 
229
241
  ---
230
242
 
@@ -329,7 +341,7 @@ Every trade journals itself: thesis on open, P&L on close, written to a **wallet
329
341
  Saved: generated-logo-1713052800.png (1024x1024)
330
342
  ```
331
343
 
332
- 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.
333
345
 
334
346
  ### 📱 Remote control via Telegram
335
347
 
@@ -370,7 +382,7 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
370
382
 
371
383
  ## Smart Router
372
384
 
373
- **<!-- br:models.chatVisible -->76<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
385
+ **<!-- br:models.chatVisible -->78<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
374
386
 
375
387
  You don't pick models. Franklin picks for you.
376
388
 
@@ -451,7 +463,7 @@ No email. No phone. No KYC. Your Solana or Base address is your account — port
451
463
  | Writes code | ✅ | ✅ | ⚠️ | ✅ |
452
464
  | **Spends money for you** | ❌ | ❌ | ❌ | ✅ **USDC wallet, x402** |
453
465
  | **Buys data + APIs + images + search** | ❌ | ❌ | ❌ | ✅ **55+ APIs, one wallet** |
454
- | 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 -->78<!-- /br:models.chatVisible --> models** |
455
467
  | Pricing model | Subscription | Subscription | Subscription | **YOPO** — per outcome, USDC |
456
468
  | Monthly fee | $20–$200 | $20–$40 | $20+ | **$0** |
457
469
  | Rate-limited | Yes | Yes | Yes | No — limited only by wallet |
@@ -479,14 +491,14 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
479
491
  **🎨 AI image generation**
480
492
  Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
481
493
 
482
- **🧠 <!-- br:models.chatVisible -->76<!-- /br:models.chatVisible --> models via one wallet**
494
+ **🧠 <!-- br:models.chatVisible -->78<!-- /br:models.chatVisible --> models via one wallet**
483
495
  Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, NVIDIA free tier. One wallet, one interface, automatic fallback.
484
496
 
485
497
  **💳 x402 micropayments (YOPO)**
486
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.
487
499
 
488
500
  **🧠 Learned model router**
489
- 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 -->78<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
490
502
 
491
503
  </td>
492
504
  <td width="50%" valign="top">
@@ -542,13 +554,13 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
542
554
  │ Intent → Smart Router → Tool Use → Spend Control → Result │
543
555
  ├──────────────────────────────────────────────────────────────┤
544
556
  │ Learned Router │
545
- │ 2M+ requests · <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
557
+ │ 2M+ requests · <!-- br:models.chatVisible@live -->78<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
546
558
  ├──────────────────────────────────────────────────────────────┤
547
559
  │ Agent Loop │
548
560
  │ 16 tools · Sessions · Compaction · Pricing · Plugin SDK │
549
561
  ├──────────────────────────────────────────────────────────────┤
550
562
  │ BlockRun Gateway │
551
- │ <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
563
+ │ <!-- br:models.chatVisible@live -->78<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
552
564
  ├──────────────────────────────────────────────────────────────┤
553
565
  │ x402 Micropayment Protocol │
554
566
  │ HTTP 402 · USDC on Solana & Base · signed payment payloads │
@@ -592,7 +604,7 @@ src/
592
604
  ├── stats/ Usage tracking + insights engine
593
605
  ├── ui/ Ink-based terminal UI
594
606
  ├── proxy/ Payment proxy for external tools
595
- ├── 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 -->78<!-- /br:models.chatVisible@live --> models, Elo scoring)
596
608
  ├── wallet/ Wallet management (Base + Solana)
597
609
  ├── mcp/ MCP server auto-discovery
598
610
  └── commands/ CLI subcommands
@@ -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) {
@@ -1,7 +1,7 @@
1
1
  import chalk from 'chalk';
2
2
  import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
3
3
  import { loadChain, DASHBOARD_URL } from '../config.js';
4
- import { isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
4
+ import { fetchCreditBalance, isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
5
5
  import { loadStats } from '../stats/tracker.js';
6
6
  export async function balanceCommand() {
7
7
  const chain = loadChain();
@@ -14,16 +14,48 @@ export async function balanceCommand() {
14
14
  const key = loadApiKey();
15
15
  console.log(`Pay mode: ${chalk.green('api-key')}`);
16
16
  console.log(`Key: ${chalk.cyan(key ? maskApiKey(key) : 'unknown')}`);
17
+ const credit = await fetchCreditBalance();
18
+ if (credit) {
19
+ console.log(`Account: ${chalk.dim(credit.accountId)} (${chalk.dim(credit.billingMode)})`);
20
+ // `ungated` means no ceiling, and remaining_usd is legitimately null.
21
+ // Coalescing that to 0 would tell a paying customer they are broke, so
22
+ // branch on the mode rather than on the number.
23
+ if (credit.remainingUsd !== null) {
24
+ const low = credit.remainingUsd < 1;
25
+ console.log(`Remaining: ${(low ? chalk.yellow : chalk.green)('$' + credit.remainingUsd.toFixed(4))}` +
26
+ chalk.dim(` of $${credit.grantedUsd.toFixed(2)} granted`));
27
+ }
28
+ else {
29
+ console.log(`Remaining: ${chalk.dim('no prepaid limit on this account')}`);
30
+ }
31
+ console.log(`Spent: ${chalk.cyan('$' + credit.spentUsd.toFixed(4))}` + chalk.dim(' (BlockRun, authoritative)'));
32
+ if (credit.blocked) {
33
+ // An append-only code set — show the raw code when it is one we do not
34
+ // know rather than swallowing it.
35
+ const explain = {
36
+ ACCOUNT_SUSPENDED: 'this account is suspended',
37
+ CREDIT_LIMIT_REACHED: 'the credit limit has been reached',
38
+ BALANCE_EXHAUSTED: 'the prepaid balance is exhausted',
39
+ };
40
+ const reason = credit.blockedReason
41
+ ? explain[credit.blockedReason] ?? `blocked (${credit.blockedReason})`
42
+ : 'blocked';
43
+ console.log(chalk.red(`\nYour next paid call will be refused — ${reason}.`));
44
+ console.log(chalk.dim(`Top up at ${DASHBOARD_URL}/dashboard.`));
45
+ }
46
+ }
17
47
  try {
18
48
  const stats = loadStats();
19
49
  const spent = stats.totalCostUsd ?? 0;
20
50
  const est = stats.totalEstimatedCostUsd ?? 0;
21
- console.log(`Spent: ${chalk.yellow((est > 0 ? '~$' : '$') + spent.toFixed(4))}` +
22
- chalk.dim(' (Franklin\'s local tally, all time)'));
51
+ console.log(`Local: ${chalk.dim((est > 0 ? '~$' : '$') + spent.toFixed(4))}` +
52
+ chalk.dim(" (Franklin's own tally, all time, both pay modes — expected to differ)"));
23
53
  }
24
54
  catch { /* stats are best-effort */ }
25
- console.log(chalk.dim(`\nCredit balance and full activity: ${DASHBOARD_URL}/dashboard`));
26
- console.log(chalk.dim('Franklin cannot read the credit balance — the gateway exposes no endpoint for it.'));
55
+ if (!credit) {
56
+ console.log(chalk.dim(`\nCould not read the credit balance from the gateway.`));
57
+ }
58
+ console.log(chalk.dim(`\nFull activity: ${DASHBOARD_URL}/dashboard`));
27
59
  console.log(chalk.dim('To spend from a USDC wallet instead: franklin --wallet, or franklin logout.'));
28
60
  return;
29
61
  }