@blockrun/franklin 3.49.4 → 3.49.6

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.
package/README.md CHANGED
@@ -45,7 +45,7 @@
45
45
 
46
46
  ## The pitch in one paragraph
47
47
 
48
- Franklin Agent is an **autonomous economic agent** — an AI that holds a USDC wallet and spends it to get real work done, with **trading as its flagship arena**. It buys live market data, proposes trade plans you approve before a cent moves, pursues long-running goals across sessions, keeps a wallet-bound trading journal, and picks the best model per task from 55+ providers. You state an outcome and set a budget. Franklin Agent decides what to call, what to pay for, and when to stop. No subscriptions, no seats, no rate limits.
48
+ Franklin Agent is an **autonomous economic agent** — an AI that holds a USDC wallet and spends it to get real work done, with **trading as its flagship arena**. It buys live market data, proposes trade plans you approve before a cent moves, pursues long-running goals across sessions, keeps a wallet-bound trading journal, and picks the best model per task from <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models. You state an outcome and set a budget. Franklin Agent decides what to call, what to pay for, and when to stop. No subscriptions, no seats, no rate limits.
49
49
 
50
50
  Funding it is your choice. Fund a **USDC wallet** and every paid action routes through the [x402](https://x402.org) micropayment protocol, settling on-chain against a wallet only you control — no signup, no account, the wallet is the identity. Or top up a **prepaid balance** at [user.blockrun.ai](https://user.blockrun.ai) and hand Franklin an API key. Same models, same tools, same agent. See [Two ways to pay](#two-ways-to-pay).
51
51
 
@@ -67,7 +67,7 @@ Built by the [BlockRun](https://blockrun.ai) team. Apache-2.0. TypeScript. Ships
67
67
  # 1. Install
68
68
  npm install -g @blockrun/franklin
69
69
 
70
- # 2. Run (free — uses NVIDIA Nemotron & Qwen3 Coder out of the box)
70
+ # 2. Run (free — uses the free models out of the box)
71
71
  franklin
72
72
 
73
73
  # 3. (optional) Unlock Sonnet, Opus, GPT, Gemini, Grok + every paid API.
@@ -113,7 +113,7 @@ npm install -g @blockrun/franklin
113
113
 
114
114
  [![Franklin for VS Code — Beta is here](assets/franklin-vscode-banner.png)](https://marketplace.visualstudio.com/items?itemName=blockrun.franklin-vscode)
115
115
 
116
- The same agent ships as a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=blockrun.franklin-vscode) — chat panel, model picker, wallet balance, image / video generation, inline diff cards — all driven by the wallet you already funded for the CLI.
116
+ The same agent ships as a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=blockrun.franklin-vscode) — chat panel, model picker, wallet balance, image / video generation — all driven by the wallet you already funded for the CLI.
117
117
 
118
118
  ```
119
119
  VS Code → Extensions (Cmd+Shift+X / Ctrl+Shift+X)
@@ -264,13 +264,11 @@ Three consequences fall out of this:
264
264
  2. **No rate limits.** Subscriptions throttle you when you need AI most. YOPO has no artificial caps — if you have USDC, you have access.
265
265
  3. **No overdraft.** The wallet balance IS the hard limit. When it's empty, Franklin stops. No surprise bills, no 3 a.m. rate-limit walls.
266
266
 
267
- Concretely — $1 in USDC gets you roughly:
268
- - ~400K GPT-4o input tokens
269
- - ~7M DeepSeek tokens
270
- - ~13M Gemini Flash tokens
271
- - ~20 DALL-E 3 images
272
- - ~40 Exa neural web searches
273
- - Unlimited agent-tested NVIDIA free tier (Qwen3 Coder + Llama 4 Maverick, no wallet needed)
267
+ Concretely — $1 in USDC buys roughly (input tokens at provider list price, before the $0.001 per-call fee):
268
+ - ~330K Claude Sonnet 4.6 tokens
269
+ - ~750K DeepSeek V4 Pro tokens
270
+ - ~3.3M Gemini 2.5 Flash tokens
271
+ - Unlimited use of the free tier — no wallet needed
274
272
 
275
273
  ---
276
274
 
@@ -282,7 +280,7 @@ Concretely — $1 in USDC gets you roughly:
282
280
 
283
281
  Most AI products fit into one of three buckets: they answer questions, write code, or automate a fixed workflow. None of them can spend money.
284
282
 
285
- Franklin can. It combines **purchasing power** (it pays for models, tools, and APIs), **budget awareness** (cost is part of the loop, not an afterthought), **cross-vertical execution** (code, trading, research, marketing, ops), and **hard stopping conditions** (wallet balance is a real constraint, not a suggestion).
283
+ Franklin can. It combines **purchasing power** (it pays for models, tools, and APIs), **budget awareness** (cost is part of the loop, not an afterthought), **cross-vertical execution** (trading, research, content, operations), and **hard stopping conditions** (wallet balance is a real constraint, not a suggestion).
286
284
 
287
285
  That is why Franklin is an economic agent, not just a task agent.
288
286
 
@@ -353,9 +351,9 @@ Generates images via DALL-E / GPT Image directly from the CLI. Paid from your se
353
351
 
354
352
  ### 📱 Remote control via Telegram
355
353
 
356
- Run `franklin telegram` on an always-on machine (set `TELEGRAM_BOT_TOKEN` + `TELEGRAM_OWNER_ID`) and drive Franklin from your phone. Owner-locked, session-resumable across restarts, slash commands (`/new`, `/balance`, `/status`). Trading, content, dev work — all reachable from a Telegram chat.
354
+ Run `franklin telegram` on an always-on machine (set `TELEGRAM_BOT_TOKEN` + `TELEGRAM_OWNER_ID`) and drive Franklin from your phone. Owner-locked, session-resumable across restarts, slash commands (`/new`, `/balance`, `/status`). Trading, research, content — all reachable from a Telegram chat.
357
355
 
358
- ### 🔎 Research, code, anything with a budget
356
+ ### 🔎 Research, analysis, anything with a budget
359
357
 
360
358
  ```text
361
359
  > compare the top 5 AI agent pricing models, summarize the patterns, and save a note for me
@@ -371,18 +369,17 @@ Run `franklin telegram` on an always-on machine (set `TELEGRAM_BOT_TOKEN` + `TEL
371
369
  ```
372
370
 
373
371
  ```text
374
- > refactor src/auth.ts to use the new jwt helper, then run the tests
372
+ > backtest strategies/sol_breakout.py on the last 90 days and tell me if it beats holding
375
373
 
376
- ✓ Read src/auth.ts $0.002
377
- ✓ Read src/lib/jwt.ts $0.001
378
- ✓ Edit src/auth.ts (-24 +31 lines) $0.008
379
- ✓ Bash npm test $0.000
380
- › 142 passing · 0 failing · 2.4s
374
+ ✓ TradingMarket SOL · 90d daily candles
375
+ ✓ Read strategies/sol_breakout.py
376
+ ✓ Bash python strategies/sol_breakout.py --days 90
377
+ ✓ Write notes/sol-breakout-90d.md
381
378
 
382
- Done in 18s · $0.011
379
+ Strategy +11.4% vs. hold +6.2% · max drawdown −8.9% · 14 trades
383
380
  ```
384
381
 
385
- Code is still first-class. It is just **one workload**, not the category.
382
+ Files and shell are there for the work around a strategy — scripts, data, reports. They are tools, not the category.
386
383
 
387
384
  Every tool call is itemized. Every token is priced. When the wallet hits zero, Franklin stops. No overdraft, no surprise bill, no rate-limit wall at 3 a.m. — this is YOPO in practice.
388
385
 
@@ -390,24 +387,24 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
390
387
 
391
388
  ## Smart Router
392
389
 
393
- **<!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
390
+ **<!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
394
391
 
395
392
  You don't pick models. Franklin picks for you.
396
393
 
397
- The Smart Router classifies every request — coding, trading, reasoning, research — and selects the model with the best quality-to-cost ratio. Trained on **2M+ real requests** from the BlockRun gateway, continuously updated.
394
+ The Smart Router classifies every request — trading, research, reasoning, creative — and selects the model with the best quality-to-cost ratio. Trained on **2M+ real requests** from the BlockRun gateway, continuously updated.
398
395
 
399
396
  ```text
400
- > refactor this auth module to use JWT
397
+ > summarize this week's stablecoin news in five bullets
401
398
 
402
- CODING kimi-k2.5 · 12.4K in / 2.1K out · $0.0023 saved 84%
399
+ RESEARCH deepseek-v4-pro · 9.6K in / 0.8K out
403
400
 
404
401
  > what's the BTC outlook for the week?
405
402
 
406
- TRADING grok-4-1-fast-reasoning · 8.2K in / 1.8K out · $0.0008 saved 95%
403
+ TRADING claude-opus-5 · 8.2K in / 1.8K out
407
404
 
408
- > prove that this algorithm is O(n log n)
405
+ > is this funding-rate arbitrage actually risk-free? walk through the cases
409
406
 
410
- REASONING claude-sonnet-4.6 · 15.1K in / 3.4K out · $0.0312
407
+ REASONING claude-opus-5 · 15.1K in / 3.4K out
411
408
  ```
412
409
 
413
410
  Every response shows which model was chosen, why, and how much you saved vs. always using the most expensive option.
@@ -419,18 +416,18 @@ Every response shows which model was chosen, why, and how much you saved vs. alw
419
416
  | `auto` | Best quality-to-cost ratio | Default — smart spend |
420
417
  | `eco` | Cheapest model with decent quality | Budget-conscious |
421
418
  | `premium` | Highest quality regardless of cost | Mission-critical |
422
- | `free` | Free NVIDIA models only | Zero wallet balance |
419
+ | `free` | Free models only | Zero wallet balance |
423
420
 
424
421
  **Per-session breakdown** — run `/cost` to see exactly where your USDC went:
425
422
 
426
423
  ```text
427
424
  Session Cost: $0.0847 (23 requests)
428
- gemini-2.5-flash $0.0012 14 req CODING
429
- kimi-k2.5 $0.0423 6 req CODING
430
- claude-sonnet-4.6 $0.0412 3 req REASONING
425
+ gemini-2.5-flash $0.0012 14 req CHAT
426
+ deepseek-v4-pro $0.0201 6 req RESEARCH
427
+ claude-opus-5 $0.0634 3 req TRADING
431
428
  ```
432
429
 
433
- The router also learns from **your** usage. If you keep retrying a model for coding tasks, Franklin adapts and picks a better one next time. Your router gets smarter the more you use it.
430
+ The router also learns from **your** usage. If you keep retrying a model for research tasks, Franklin adapts and picks a better one next time. Your router gets smarter the more you use it.
434
431
 
435
432
  ---
436
433
 
@@ -449,7 +446,7 @@ You don't subscribe to electricity, you pay for what you use. Franklin brings th
449
446
 
450
447
  ### 🧠 &nbsp;Multi-model is the future
451
448
 
452
- No single model is best at everything. Sonnet writes better code, Gemini handles longer context, DeepSeek costs 20x less for simple tasks. The Smart Router routes every request to the optimal model in <1ms — <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% cheaper than pinning Claude Opus 5 for every request.
449
+ No single model is best at everything. Opus reasons deeper, Gemini handles longer context, DeepSeek costs 20x less for simple tasks. The Smart Router routes every request to the optimal model in <1ms — <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% cheaper than pinning Claude Opus 5 for every request.
453
450
 
454
451
  </td>
455
452
  <td width="33%" valign="top">
@@ -466,19 +463,17 @@ No email. No phone. No KYC. Your Solana, Base or Arc address is your account —
466
463
 
467
464
  ## The comparison
468
465
 
469
- | | Coding agents | Editor IDEs | Chatbots | **Franklin** |
470
- | -------------------------------------- | ---------------- | ---------------- | ---------------- | ------------------------------- |
471
- | Writes code | ✅ | ✅ | ⚠️ | ✅ |
472
- | **Spends money for you** | ❌ | ❌ | ❌ | ✅ **USDC wallet, x402** |
473
- | **Buys data + APIs + images + search** | ❌ | ❌ | ❌ | ✅ **55+ APIs, one wallet** |
474
- | Picks best model per task | ❌ single-vendor | ❌ plan-tied | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models** |
475
- | Pricing model | Subscription | Subscription | Subscription | **YOPO** — per outcome, USDC |
476
- | Monthly fee | $20–$200 | $20–$40 | $20+ | **$0** |
477
- | Rate-limited | Yes | Yes | Yes | No — limited only by wallet |
478
- | Works when provider goes down | ❌ | ❌ | ❌ | ✅ **routes to another** |
479
- | Identity | Vendor account | Vendor account | Account / email | ✅ **wallet, no signup** |
480
- | Start free, no KYC | ❌ | ❌ | ❌ | ✅ |
481
- | Source | Closed | Closed | Closed | **Apache 2.0, local-first** |
466
+ | | AI chat apps | Agent frameworks | Trading bots | **Franklin** |
467
+ | -------------------------------------- | ---------------- | ----------------------- | -------------------- | ------------------------------- |
468
+ | **Spends money for you** | ❌ | ⚠️ you wire payments | ⚠️ trades only | ✅ **USDC wallet or prepaid key** |
469
+ | **Buys data + APIs + images + search** | ❌ | ⚠️ one key per service | ❌ | ✅ **one wallet pays for all** |
470
+ | Picks best model per task | ❌ single-vendor | ⚠️ you pick | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models** |
471
+ | **Money moves only on your approval** | — | ⚠️ build it yourself | ❌ runs on rules | ✅ **trade plan, every mode** |
472
+ | Spend guardrails | — | ⚠️ build it yourself | ⚠️ per-bot limits | ✅ **budget caps + hooks** |
473
+ | Works when a provider goes down | ❌ | ⚠️ if you code it | ❌ | ✅ **routes to another** |
474
+ | Pricing | Subscription | Your separate API bills | Subscription or fees | **YOPO** — per outcome |
475
+ | Identity | Vendor account | A key per vendor | Exchange account | ✅ **wallet, no signup** |
476
+ | Source | Closed | Mixed | Mostly closed | **Apache 2.0, local-first** |
482
477
 
483
478
  **Franklin is the economic agent category in one sentence:** software with a wallet that can spend toward a result.
484
479
 
@@ -499,20 +494,20 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
499
494
  **🎨 AI image generation**
500
495
  Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
501
496
 
502
- **🧠 <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> models via one wallet**
503
- Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, NVIDIA free tier. One wallet, one interface, automatic fallback.
497
+ **🧠 <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models via one wallet**
498
+ Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, plus a free tier. One wallet, one interface, automatic fallback.
504
499
 
505
500
  **💳 x402 micropayments (YOPO)**
506
501
  HTTP 402 native. Every paid action is a signed USDC micropayment — an EIP-712 authorization on Base and Arc, a signed SPL transfer on Solana. Non-custodial: your keys never leave your machine. YOPO: you pay only for outcomes.
507
502
 
508
503
  **🧠 Learned model router**
509
- 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.
504
+ Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
510
505
 
511
506
  </td>
512
507
  <td width="50%" valign="top">
513
508
 
514
- **🛠 16 built-in tools**
515
- Read, Write, Edit, Bash, Glob, Grep, WebFetch, WebSearch, Task, ImageGen, VideoGen, MemoryRecall, AskUser, SubAgent, TradingSignal, TradingMarket, TradingPortfolio, TradingOpenPosition, TradingClosePosition, TradingHistory.
509
+ **🛠 60+ built-in tools**
510
+ Trading and DeFi (signals, portfolio, trade plans, Jupiter and 0x swaps, Polymarket, DeFiLlama), research (Exa, web search and fetch, X search, on-chain and market data), media (image, video, music), autonomy (goals, scheduler, monitors, sub-agents, mixture of agents), phone and voice calls, cloud sandboxes, and general files and shell.
516
511
 
517
512
  **💾 Persistent sessions**
518
513
  Every turn is streamed to disk with metadata. Resume any session by ID. Survives crashes, reboots, and compaction.
@@ -526,6 +521,9 @@ Every turn is streamed to disk with metadata. Resume any session by ID. Survives
526
521
  **⚡ Anthropic prompt caching**
527
522
  Multi-turn Sonnet/Opus sessions use ephemeral cache breakpoints to reduce input spend on long conversations.
528
523
 
524
+ **🔒 Guarded by default**
525
+ Trades need your approved plan, the wallet key never reaches the model, and every network call the agent makes is checked. See [Safety and security](#safety-and-security).
526
+
529
527
  **🔌 Plugin SDK + MCP**
530
528
  Core is workflow-agnostic. Add new verticals without touching the loop. Discover external tools automatically through MCP.
531
529
 
@@ -540,14 +538,16 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
540
538
  | Command | What it does |
541
539
  | -------------------------------- | ---------------------------------------------------- |
542
540
  | `/model [name]` | Interactive model picker, or switch directly |
541
+ | `/goal <objective>` | Work an objective across turns, verified at the end |
542
+ | `/loop <interval> <prompt>` | Run a prompt on a schedule (`/loop list`, `cancel`) |
543
+ | `/market` | Browse and hire paid skills from the marketplace |
544
+ | `/moa` | Ask several models the same question, compare |
543
545
  | `/plan` / `/execute` | Read-only planning mode / execution mode |
544
546
  | `/ultrathink <q>` | Deep reasoning mode for hard problems |
547
+ | `/remember` / `/flush` / `/dream`| Save a note / capture learnings / consolidate memory |
545
548
  | `/compact` | Structured context compression |
546
- | `/search <q>` | Search the codebase |
547
549
  | `/session-search <q>` | Search past sessions |
548
550
  | `/history` / `/resume [id]` | Inspect or restore conversation state |
549
- | `/commit` / `/push` / `/pr` | Git workflow helpers |
550
- | `/review` / `/fix` / `/test` | One-shot code review, bugfix, or test runs |
551
551
  | `/cost` / `/wallet` | Session cost, wallet address, and balance |
552
552
  | `/insights [--days N]` | Rich usage analytics |
553
553
  | `/help` | Full command list |
@@ -560,6 +560,19 @@ like `opus`, `gpt` and `grok` keep their current targets.
560
560
 
561
561
  ---
562
562
 
563
+ ## Safety and security
564
+
565
+ Franklin holds money, so the defaults assume a model can be steered by what it reads — a fetched page, a search result, an MCP response.
566
+
567
+ - **Money moves only on your approval.** Trades need a trade plan you approve, in every permission mode. `--max-spend` sets a spending ceiling, and [lifecycle hooks](docs/examples/hooks/) can veto any paid action before it runs.
568
+ - **The wallet key never reaches the model.** File, search and browser tools refuse the key store and the machine's own credential stores (`~/.ssh`, `~/.aws`, cloud and Solana CLI keys). The exact key values are also scrubbed from every tool result.
569
+ - **Network calls stay public.** Model-driven requests (web fetch, webhooks, the browser) refuse loopback, private and cloud-metadata addresses, and re-check every redirect.
570
+ - **The local panel answers only you.** It listens on loopback, checks the `Host` header, and its wallet and spend routes require a token that only the page it serves knows.
571
+
572
+ Found a vulnerability? Please report it privately — see [SECURITY.md](SECURITY.md).
573
+
574
+ ---
575
+
563
576
  ## How it works
564
577
 
565
578
  ```text
@@ -568,13 +581,13 @@ like `opus`, `gpt` and `grok` keep their current targets.
568
581
  │ Intent → Smart Router → Tool Use → Spend Control → Result │
569
582
  ├──────────────────────────────────────────────────────────────┤
570
583
  │ Learned Router │
571
- │ 2M+ requests · <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
584
+ │ 2M+ requests · <!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
572
585
  ├──────────────────────────────────────────────────────────────┤
573
586
  │ Agent Loop │
574
- │ 16 tools · Sessions · Compaction · Pricing · Plugin SDK │
587
+ │ 60+ tools · Sessions · Compaction · Pricing · Plugin SDK │
575
588
  ├──────────────────────────────────────────────────────────────┤
576
589
  │ BlockRun Gateway │
577
- │ <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
590
+ │ <!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
578
591
  ├──────────────────────────────────────────────────────────────┤
579
592
  │ x402 Micropayment Protocol │
580
593
  │ HTTP 402 · USDC on Solana, Base & Arc · signed payloads │
@@ -604,10 +617,15 @@ src/
604
617
  ├── index.ts CLI entry (franklin)
605
618
  ├── banner.ts Ben Franklin portrait + FRANKLIN gradient text
606
619
  ├── agent/ Agent loop, LLM client, compaction, commands
607
- ├── tools/ 20+ built-in tools (Read/Write/Edit/Bash/Glob/Grep/
608
- │ WebFetch/WebSearch/Task/ImageGen/VideoGen/
609
- │ MemoryRecall/AskUser/SubAgent/Trading*/Content*)
620
+ ├── tools/ 60+ built-in tools (trading, DeFi, research, media,
621
+ │ phone, sandboxes, files and shell)
610
622
  ├── trading/ Market data (CoinGecko) + technical indicators
623
+ ├── goal/ /goal objectives + adversarial verification
624
+ ├── hooks/ Lifecycle hooks (PreSpend and friends)
625
+ ├── scheduler/ Durable /loop scheduler
626
+ ├── memory/ Wallet-keyed memory and trading journal
627
+ ├── panel/ Local dashboard (franklin panel)
628
+ ├── serve/ Agent host for the panel's Agents tab
611
629
  ├── content/ Content library with budget-bound media generation
612
630
  ├── brain/ Cross-session entity knowledge graph
613
631
  ├── channel/ Non-CLI ingress drivers (Telegram today)
@@ -618,7 +636,7 @@ src/
618
636
  ├── stats/ Usage tracking + insights engine
619
637
  ├── ui/ Ink-based terminal UI
620
638
  ├── proxy/ Payment proxy for external tools
621
- ├── router/ Learned model router (<!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models, Elo scoring)
639
+ ├── router/ Learned model router (<!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> models, Elo scoring)
622
640
  ├── wallet/ Wallet management (Base/Arc + Solana)
623
641
  ├── mcp/ MCP server auto-discovery
624
642
  └── commands/ CLI subcommands
@@ -628,7 +646,7 @@ src/
628
646
 
629
647
  ## Free tier, for real
630
648
 
631
- Start with **zero dollars**. Franklin defaults to free NVIDIA models that need **no wallet and no API key** — nothing to fund, nothing to sign up for.
649
+ Start with **zero dollars**. Franklin defaults to free models that need **no wallet and no API key** — nothing to fund, nothing to sign up for.
632
650
 
633
651
  ```bash
634
652
  franklin --model free
@@ -698,7 +716,7 @@ npm install
698
716
  npm run build
699
717
  npm test # deterministic local tests — no API calls
700
718
  npm run test:e2e # live e2e tests — free smoke works unfunded; paid tools need network + funded wallet
701
- npm run test:free-models # live matrix across current free NVIDIA models
719
+ npm run test:free-models # live matrix across the current free models
702
720
  node dist/index.js --help
703
721
  ```
704
722
 
@@ -720,7 +738,7 @@ npm run desktop:package:win
720
738
  Packaged builds create a private, per-launch credential for the local Franklin
721
739
  service, keep cloud session sync off unless the user explicitly enables it, and
722
740
  use `Documents/Franklin` as the default workspace. Files outside that workspace
723
- remain available after an explicit approval, similar to other coding agents.
741
+ remain available after an explicit approval.
724
742
  Team Mode is being developed separately and is not part of this stable integration.
725
743
 
726
744
  For the recommended live validation order and failure triage, see [docs/live-e2e-checklist.md](docs/live-e2e-checklist.md).
@@ -17,9 +17,11 @@ import { resolveModel } from '../ui/model-picker.js';
17
17
  import { isFreeModelId } from '../free-models.js';
18
18
  import { listSessions, loadSessionHistory, } from '../session/storage.js';
19
19
  import { matchSkill } from '../skills/invoke.js';
20
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
20
21
  // ─── Git helpers ──────────────────────────────────────────────────────────
21
22
  function gitExec(cmd, cwd, timeout = 5000, maxBuffer) {
22
23
  return execSync(cmd, {
24
+ env: sanitizeSubprocessEnv(),
23
25
  cwd,
24
26
  encoding: 'utf-8',
25
27
  timeout,
@@ -11,6 +11,7 @@ import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
12
12
  import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt } from '../learnings/store.js';
13
13
  import { isKeyMode, resolvePayMode } from '../payments/auth-mode.js';
14
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
14
15
  // ─── System Instructions Assembly ──────────────────────────────────────────
15
16
  // Composable prompt sections — each independently maintainable and conditionally includable.
16
17
  function getCoreInstructions() {
@@ -103,7 +104,15 @@ Examples of risky actions that warrant user confirmation:
103
104
 
104
105
  When you encounter an obstacle, do not use destructive actions as a shortcut. Identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting — it may represent the user's in-progress work.
105
106
 
106
- A user approving an action once does NOT mean they approve it in all contexts. Match the scope of your actions to what was actually requested. When in doubt, ask before acting.`;
107
+ A user approving an action once does NOT mean they approve it in all contexts. Match the scope of your actions to what was actually requested. When in doubt, ask before acting.
108
+
109
+ ## Ambiguous payment outcomes
110
+ A payment, transfer, bet, or swap that was signed and sent may have settled even when the response says otherwise. A timeout, a 5xx (502 "upstream response lost" included), a dropped connection, or a missing receipt after a send means the outcome is UNKNOWN, not failed. This holds whichever path sent it: a built-in tool, a Bash script, or an MCP tool.
111
+ - Never send a new payment for the same obligation while an earlier attempt's outcome is unknown. A new nonce or a new signature turns one obligation into two settlements.
112
+ - Reconcile first: look up the earlier attempt by its transaction hash (receipt), the sender's nonce, and the sender/recipient balances or the venue's own status endpoint. If it settled, the obligation is paid. Do not pay again.
113
+ - If it is still pending, wait and check again. If a retry is truly needed, re-broadcast the SAME signed transaction (same nonce), so at most one can ever land. Never sign a fresh one.
114
+ - Only when the attempt has provably not settled (a reverted receipt, or a definite rejection of bytes the network never accepted) may a new payment be sent. If you cannot establish that, stop and tell the user exactly what is unknown.
115
+ - In the final report, account for every attempt and every settlement. Never report one payment when two may have landed.`;
107
116
  }
108
117
  function getOutputEfficiencySection() {
109
118
  return `# Output Efficiency
@@ -725,7 +734,7 @@ function buildEnvironmentSection(workingDir) {
725
734
  catch { /* ignore */ }
726
735
  // Git repo detection
727
736
  try {
728
- execSync('git rev-parse --is-inside-work-tree', { cwd: workingDir, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
737
+ execSync('git rev-parse --is-inside-work-tree', { env: sanitizeSubprocessEnv(), cwd: workingDir, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
729
738
  lines.push('- Is a git repository: true');
730
739
  }
731
740
  catch {
@@ -833,6 +842,7 @@ const GIT_TIMEOUT_MS = 5_000;
833
842
  const MAX_GIT_LOG_CHARS = 800;
834
843
  function getGitContext(workingDir) {
835
844
  const gitCmd = (cmd) => execSync(cmd, {
845
+ env: sanitizeSubprocessEnv(),
836
846
  cwd: workingDir,
837
847
  encoding: 'utf-8',
838
848
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { checkTradePlanGate, recordTradeExecution } from '../trading/trade-plan.js';
3
+ import { checkTradePlanGate, recordTradeExecution, releaseTradeReservation } from '../trading/trade-plan.js';
4
4
  const MAX_WEBSEARCHES_PER_TURN = 8;
5
5
  const MAX_SIMILAR_SEARCHES_PER_TURN = 4;
6
6
  const MAX_NO_SIGNAL_SEARCHES_PER_FAMILY = 2;
@@ -423,6 +423,12 @@ export class SessionToolGuard {
423
423
  this.recentGlobs.set(key, { preview, turn: this.turn });
424
424
  }
425
425
  cancelInvocation(invocationId) {
426
+ // Denied before execution (permission refused, PreSpend veto): nothing
427
+ // was submitted, so a trade-plan reservation made by the gate goes back.
428
+ try {
429
+ releaseTradeReservation(invocationId);
430
+ }
431
+ catch { /* budget accounting must never break tool flow */ }
426
432
  this.pendingSearches.delete(invocationId);
427
433
  this.pendingReads.delete(invocationId);
428
434
  this.pendingFetches.delete(invocationId);
@@ -82,6 +82,13 @@ export interface CapabilityResult {
82
82
  mediaType: string;
83
83
  base64: string;
84
84
  }>;
85
+ /**
86
+ * Set by a money-moving tool only when the call provably never submitted
87
+ * anything (validation failure, user cancel, definite venue rejection). The
88
+ * trade-plan gate reserves budget before execution and releases it only on
89
+ * this signal — an error alone may hide an accepted, unacknowledged order.
90
+ */
91
+ notSubmitted?: boolean;
85
92
  }
86
93
  export interface ExecutionScope {
87
94
  workingDir: string;
@@ -17,6 +17,7 @@ import { logger } from '../logger.js';
17
17
  import { appendApprovalRecord } from '../audit/approvals.js';
18
18
  import { loadHooks } from './loader.js';
19
19
  import { BLOCKING_EVENTS, } from './types.js';
20
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
20
21
  const DEFAULT_TIMEOUT_SECS = 5;
21
22
  const MAX_STDOUT_BYTES = 64 * 1024;
22
23
  export class HookEngine {
@@ -78,13 +79,18 @@ export class HookEngine {
78
79
  if (fs.existsSync(resolved))
79
80
  command = resolved;
80
81
  }
82
+ // Lifecycle hooks are user-authored and keep the full env. Tool and spend
83
+ // hooks receive model-controlled input on stdin and may execute it, so the
84
+ // inherited env drops wallet/account keys; the hook's own configured `env`
85
+ // is an explicit user grant and still applies.
86
+ const inherited = input.toolInput || input.spend ? sanitizeSubprocessEnv() : process.env;
87
+ const env = { ...inherited, ...hook.handler.env };
81
88
  return new Promise(resolve => {
82
89
  const child = execFile('/bin/sh', ['-c', command], {
83
90
  timeout: timeoutMs,
84
91
  maxBuffer: MAX_STDOUT_BYTES,
85
92
  env: {
86
- ...process.env,
87
- ...hook.handler.env,
93
+ ...env,
88
94
  // Reserved vars always win over handler env.
89
95
  FRANKLIN_HOOK_EVENT: input.hookEventName,
90
96
  FRANKLIN_SESSION_ID: input.sessionId,
@@ -21,6 +21,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
21
21
  import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
22
22
  import { logger } from '../logger.js';
23
23
  import { createOAuthProvider } from './oauth.js';
24
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
24
25
  // ─── State ────────────────────────────────────────────────────────────────
25
26
  const connections = new Map();
26
27
  const lastFailures = new Map();
@@ -156,7 +157,9 @@ async function connectStdio(name, config) {
156
157
  const transport = new StdioClientTransport({
157
158
  command: config.command,
158
159
  args: config.args || [],
159
- env: { ...process.env, ...(config.env || {}) },
160
+ // Inherited env drops wallet/account keys; values the user wrote into this
161
+ // server's own `env` config are an explicit grant and pass through.
162
+ env: { ...sanitizeSubprocessEnv(), ...(config.env || {}) },
160
163
  // Capture stderr so we can show it in `/mcp` rather than dumping to the
161
164
  // user's terminal. The previous `'ignore'` mode meant a misconfigured
162
165
  // server (missing env, OAuth failure, missing binary) showed up as a
@@ -20,6 +20,7 @@ import { spawn } from 'node:child_process';
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import { logger } from '../logger.js';
23
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
23
24
  const require = createRequire(import.meta.url);
24
25
  /** True unless the user explicitly disabled CodeGraph via env. */
25
26
  function userEnabled() {
@@ -99,6 +100,7 @@ export function ensureCodegraphIndex(workDir) {
99
100
  try {
100
101
  const child = spawn(process.execPath, [shim, 'init', workDir, '-i'], {
101
102
  cwd: workDir,
103
+ env: sanitizeSubprocessEnv(),
102
104
  // Discard output: this is best-effort background indexing. Failures are
103
105
  // non-fatal — the agent simply keeps using grep/read until (and if) the
104
106
  // index appears. Surfacing a stack trace here would just be noise.
@@ -23,6 +23,7 @@ import path from 'node:path';
23
23
  import crypto from 'node:crypto';
24
24
  import { execFileSync } from 'node:child_process';
25
25
  import { BLOCKRUN_DIR } from '../config.js';
26
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
26
27
  export function memoryEnabled() {
27
28
  return process.env.FRANKLIN_MEMORY !== '0';
28
29
  }
@@ -49,6 +50,7 @@ export function repoIdentity(workDir) {
49
50
  let identity = null;
50
51
  try {
51
52
  const url = execFileSync('git', ['-C', workDir, 'remote', 'get-url', 'origin'], {
53
+ env: sanitizeSubprocessEnv(),
52
54
  encoding: 'utf-8',
53
55
  timeout: 2000,
54
56
  stdio: ['ignore', 'pipe', 'ignore'],
@@ -22,6 +22,7 @@ import { spawn } from 'node:child_process';
22
22
  import fs from 'node:fs';
23
23
  import { readTaskMeta, applyEvent, writeTaskMeta } from './store.js';
24
24
  import { taskLogPath, ensureTaskDir } from './paths.js';
25
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
25
26
  const HEARTBEAT_MS = 5_000;
26
27
  const TAIL_BYTES = 500;
27
28
  function safeCloseFd(fd) {
@@ -129,7 +130,7 @@ export async function runDetachedTask(runId) {
129
130
  const child = spawn('bash', ['-lc', meta.command], {
130
131
  cwd: meta.workingDir,
131
132
  stdio: ['ignore', logFd, logFd],
132
- env: { ...process.env, FRANKLIN_TASK_RUN_ID: runId },
133
+ env: { ...sanitizeSubprocessEnv(), FRANKLIN_TASK_RUN_ID: runId },
133
134
  });
134
135
  // Cancel path: parent CLI sends SIGTERM (or user hits Ctrl-C). We must
135
136
  // (a) flip `finalized` BEFORE the soon-to-fire child.exit handler runs so
@@ -30,6 +30,7 @@ import path from 'node:path';
30
30
  import { randomUUID } from 'node:crypto';
31
31
  import { writeTaskMeta } from './store.js';
32
32
  import { taskLogPath, ensureTaskDir } from './paths.js';
33
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
33
34
  // Captured at module load so it survives later chdir / argv mutation.
34
35
  // `process.argv[1]` may be relative (`dist/index.js` in dev mode); we
35
36
  // resolve against process.cwd() at startup which is when the user's
@@ -83,7 +84,7 @@ export function startDetachedTask(input) {
83
84
  cwd: input.workingDir,
84
85
  detached: true,
85
86
  stdio: ['ignore', logFd, logFd],
86
- env: { ...process.env, FRANKLIN_TASK_RUN_ID: runId },
87
+ env: { ...sanitizeSubprocessEnv(), FRANKLIN_TASK_RUN_ID: runId },
87
88
  });
88
89
  child.unref();
89
90
  // The child has duped the fd; closing ours frees the parent's slot.
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { spawn } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
+ import { sanitizeSubprocessEnv } from './subprocess-env.js';
6
7
  // ─── Smart Output Compression ─────────────────────────────────────────────
7
8
  // Learned from RTK (Rust Token Killer): strip noise before sending to LLM.
8
9
  // Applied after capture, before the 32KB cap — reduces tokens on verbose commands.
@@ -289,22 +290,22 @@ function executeCommand(command, timeoutMs, ctx) {
289
290
  const shell = fs.existsSync('/bin/bash') ? '/bin/bash' : (process.env.SHELL || '/bin/sh');
290
291
  let child;
291
292
  try {
292
- // The account bearer key is deliberately withheld from the subprocess.
293
- // bash-guard auto-approves `printenv` and `echo` as safe, so
294
- // `printenv BLOCKRUN_API_KEY` ran with no confirmation and returned the
295
- // key as tool output — into the model prompt and the saved transcript.
296
- // Wallet private keys are never in the environment at all; this gives
297
- // the key the same treatment. Franklin's own gateway calls read
298
- // process.env in-process and are unaffected, and a user who genuinely
299
- // needs the key in a shell can export it there themselves.
293
+ // Credentials are withheld from the subprocess. bash-guard auto-approves
294
+ // `printenv` and `echo` as safe, so `printenv BLOCKRUN_API_KEY` once ran
295
+ // with no confirmation and returned the key as tool output. The same
296
+ // holds for the wallet keys the SDK reads from BLOCKRUN_WALLET_KEY /
297
+ // BASE_CHAIN_WALLET_KEY / SOLANA_WALLET_KEY: inherited, they let a
298
+ // model-written script sign transfers that no Franklin gate ever sees.
299
+ // Franklin's own gateway calls read process.env in-process and are
300
+ // unaffected, and a user who genuinely needs a key in a shell can
301
+ // export it there themselves.
300
302
  const childEnv = {
301
- ...process.env,
303
+ ...sanitizeSubprocessEnv(),
302
304
  FRANKLIN: '1', // Let scripts detect they're running inside Franklin
303
305
  FRANKLIN_WORKDIR: ctx.workingDir,
304
306
  RUNCODE: '1', // Backwards compat
305
307
  RUNCODE_WORKDIR: ctx.workingDir,
306
308
  };
307
- delete childEnv.BLOCKRUN_API_KEY;
308
309
  child = spawn(shell, ['-c', command], {
309
310
  cwd: ctx.workingDir,
310
311
  env: childEnv,
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { BLOCKRUN_DIR } from '../config.js';
8
8
  import { WALLET_KEY_PATHS, hostCredentialDirPaths, isHostCredentialPath, isWalletKeyPath, secretPathRefusal, } from './sensitive-paths.js';
9
+ import { sanitizeSubprocessEnv } from './subprocess-env.js';
9
10
  const MAX_GREP_OUTPUT_CHARS = 16_000; // ~4,000 tokens — prevents huge grep results
10
11
  let _hasRipgrep = null;
11
12
  function hasRipgrep() {
@@ -123,6 +124,7 @@ function runRipgrep(opts, searchPath, mode, limit, cwd) {
123
124
  args.push(searchPath);
124
125
  try {
125
126
  const result = execFileSync('rg', args, {
127
+ env: sanitizeSubprocessEnv(),
126
128
  encoding: 'utf-8',
127
129
  maxBuffer: 2 * 1024 * 1024,
128
130
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -193,6 +195,7 @@ function runNativeGrep(opts, searchPath, mode, limit, cwd) {
193
195
  args.push('-e', opts.pattern, searchPath);
194
196
  try {
195
197
  const result = execFileSync('grep', args, {
198
+ env: sanitizeSubprocessEnv(),
196
199
  encoding: 'utf-8',
197
200
  maxBuffer: 2 * 1024 * 1024,
198
201
  stdio: ['pipe', 'pipe', 'pipe'],