@blockrun/franklin 3.43.1 → 3.44.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 (56) hide show
  1. package/README.md +95 -11
  2. package/dist/agent/intent-prefetch.js +4 -3
  3. package/dist/agent/llm.js +5 -0
  4. package/dist/agent/loop.js +7 -4
  5. package/dist/agent/secret-redact.js +11 -0
  6. package/dist/commands/balance.js +25 -1
  7. package/dist/commands/doctor.js +48 -2
  8. package/dist/commands/login.d.ts +14 -0
  9. package/dist/commands/login.js +97 -0
  10. package/dist/commands/models.js +3 -2
  11. package/dist/commands/plugin.js +3 -2
  12. package/dist/commands/predict.js +3 -2
  13. package/dist/commands/proxy.js +3 -2
  14. package/dist/commands/setup.js +15 -1
  15. package/dist/commands/slack.js +3 -2
  16. package/dist/commands/social.js +3 -2
  17. package/dist/commands/start.js +3 -2
  18. package/dist/commands/stats.js +18 -1
  19. package/dist/commands/telegram.js +3 -2
  20. package/dist/config.d.ts +5 -0
  21. package/dist/config.js +17 -0
  22. package/dist/gateway-models.js +9 -4
  23. package/dist/index.js +26 -3
  24. package/dist/onramp/client.js +3 -2
  25. package/dist/payments/auth-mode.d.ts +114 -0
  26. package/dist/payments/auth-mode.js +186 -0
  27. package/dist/payments/post-with-payment.d.ts +6 -0
  28. package/dist/payments/post-with-payment.js +40 -6
  29. package/dist/payments/price-catalog.d.ts +71 -0
  30. package/dist/payments/price-catalog.js +322 -0
  31. package/dist/phone/client.js +6 -2
  32. package/dist/pricing.js +3 -3
  33. package/dist/proxy/server.js +11 -0
  34. package/dist/router/index.js +2 -1
  35. package/dist/serve/cloud-sync.d.ts +1 -0
  36. package/dist/serve/server.js +10 -3
  37. package/dist/stats/tracker.d.ts +15 -1
  38. package/dist/stats/tracker.js +14 -2
  39. package/dist/tools/blockrun.js +10 -3
  40. package/dist/tools/defillama.js +9 -3
  41. package/dist/tools/exa.js +22 -9
  42. package/dist/tools/imagegen.js +4 -2
  43. package/dist/tools/modal.js +4 -2
  44. package/dist/tools/musicgen.js +4 -2
  45. package/dist/tools/phone.js +4 -2
  46. package/dist/tools/prediction.js +15 -4
  47. package/dist/tools/realface.js +14 -8
  48. package/dist/tools/rpc.js +10 -3
  49. package/dist/tools/surf.js +12 -4
  50. package/dist/tools/videogen.js +4 -2
  51. package/dist/tools/voice.js +6 -4
  52. package/dist/tools/zerox-base.js +4 -2
  53. package/dist/tools/zerox-gasless.js +6 -4
  54. package/dist/trading/providers/blockrun/client.js +20 -7
  55. package/dist/ui/model-picker.js +1 -1
  56. package/package.json +8 -4
package/README.md CHANGED
@@ -28,6 +28,7 @@
28
28
 
29
29
  <p>
30
30
  <a href="#quick-start">Quick&nbsp;start</a> ·
31
+ <a href="#two-ways-to-pay">Two&nbsp;ways&nbsp;to&nbsp;pay</a> ·
31
32
  <a href="#franklin-desktop-beta">Desktop</a> ·
32
33
  <a href="#yopo">YOPO</a> ·
33
34
  <a href="#a-new-category">Category</a> ·
@@ -44,7 +45,9 @@
44
45
 
45
46
  ## The pitch in one paragraph
46
47
 
47
- 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. Every paid action routes through the [x402](https://x402.org) micropayment protocol and settles against your own wallet. No subscriptions. No API keys. No account. The wallet is the identity.
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.
49
+
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).
48
51
 
49
52
  Built by the [BlockRun](https://blockrun.ai) team. Apache-2.0. TypeScript. Ships as one npm package.
50
53
 
@@ -67,12 +70,18 @@ npm install -g @blockrun/franklin
67
70
  # 2. Run (free — uses NVIDIA Nemotron & Qwen3 Coder out of the box)
68
71
  franklin
69
72
 
70
- # 3. (optional) Fund a wallet to unlock Sonnet, Opus, GPT, Gemini, Grok, + paid APIs
71
- franklin setup base # or: franklin setup solana
73
+ # 3. (optional) Unlock Sonnet, Opus, GPT, Gemini, Grok + every paid API.
74
+ # Pick ONE — a USDC wallet, or a prepaid API key.
75
+
76
+ # a) Wallet — no signup, no account
77
+ franklin setup solana # or: franklin setup base
72
78
  franklin balance # show address + USDC balance
79
+
80
+ # b) API key — sign up and top up at https://user.blockrun.ai
81
+ franklin login brk_live_...
73
82
  ```
74
83
 
75
- That's it. Zero signup, zero credit card, zero phone verification. Send **$5 of USDC** to the wallet and you've unlocked every frontier model and every paid tool in the BlockRun gateway.
84
+ Either route unlocks the same thing: **$5** buys you every frontier model and every paid tool in the BlockRun gateway. The wallet route needs zero signup, zero credit card, zero phone verification. The key route needs an account but no crypto.
76
85
 
77
86
  **No global install? Just run it directly** — no permissions, no `-g`:
78
87
 
@@ -144,6 +153,81 @@ packaging instructions.
144
153
 
145
154
  ---
146
155
 
156
+ ## Two ways to pay
157
+
158
+ Franklin needs money to work — it buys model calls, market data, search and media
159
+ generation on your behalf. There are two ways to give it that money, and they are
160
+ interchangeable. Everything else about the agent is identical.
161
+
162
+ | | **USDC wallet** (x402) | **API key** (prepaid credit) |
163
+ | --- | --- | --- |
164
+ | Setup | `franklin setup solana` | Sign up, top up, `franklin login brk_...` |
165
+ | Account required | No | Yes |
166
+ | Crypto required | Yes — USDC on Solana or Base | No — top up with a card |
167
+ | Settlement | On-chain, per call, via [x402](https://x402.org) | Against a prepaid balance |
168
+ | Gateway | `sol.blockrun.ai` / `blockrun.ai` | `api.blockrun.ai` |
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 |
171
+
172
+ **The wallet is still Franklin's identity.** Memory, the trading journal and goals are
173
+ keyed to it, and the wallet route is the one that needs nothing from us — no signup, no
174
+ KYC, no account to suspend. The API key exists because not everyone wants to hold crypto
175
+ to try an agent.
176
+
177
+ ### Getting an API key
178
+
179
+ 1. Sign up at **[user.blockrun.ai](https://user.blockrun.ai)**.
180
+ 2. Top up your balance from the dashboard.
181
+ 3. Create a key — it looks like `brk_live_...`.
182
+ 4. Give it to Franklin:
183
+
184
+ ```bash
185
+ franklin login brk_live_... # verifies the key, then stores it at ~/.blockrun/api-key (0600)
186
+ franklin login # show the active pay mode without changing it
187
+ franklin logout # remove the key and fall back to the wallet
188
+ ```
189
+
190
+ Or set it in the environment instead, which takes precedence over the stored key and is
191
+ the right choice for CI and servers:
192
+
193
+ ```bash
194
+ export BLOCKRUN_API_KEY=brk_live_...
195
+ ```
196
+
197
+ ### Running both
198
+
199
+ You can have a wallet **and** a key configured at once. The key wins by default. To spend
200
+ from the wallet for a single run, add `--wallet` to any command:
201
+
202
+ ```bash
203
+ franklin --wallet # this session pays from the wallet
204
+ franklin balance --wallet # show the wallet balance, not the key status
205
+ ```
206
+
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.
210
+
211
+ ### One honest caveat about spend tracking
212
+
213
+ In wallet mode every charge is exact: the gateway states the price in the x402 handshake
214
+ and Franklin records the amount that actually settled.
215
+
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.
223
+
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).
228
+
229
+ ---
230
+
147
231
  ## YOPO
148
232
 
149
233
  **You Only Pay Outcome.** This is Franklin Agent's pricing model, and it is the opposite of almost every other AI product you use.
@@ -352,7 +436,7 @@ No single model is best at everything. Sonnet writes better code, Gemini handles
352
436
 
353
437
  ### 🔐 &nbsp;Wallet is identity
354
438
 
355
- No email. No phone. No KYC. Your Base or Solana address is your account — portable, permissionless, global. API keys require US banking and account approval. A wallet requires only USDC.
439
+ No email. No phone. No KYC. Your Solana or Base address is your account — portable, permissionless, global. A wallet requires only USDC. (Prefer an account and a card? [Two ways to pay](#two-ways-to-pay) — the key route exists, it just is not the one that makes the agent sovereign.)
356
440
 
357
441
  </td>
358
442
  </tr>
@@ -458,16 +542,16 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
458
542
  │ Intent → Smart Router → Tool Use → Spend Control → Result │
459
543
  ├──────────────────────────────────────────────────────────────┤
460
544
  │ Learned Router │
461
- │ 2M+ requests · <!-- br:models.chatVisible -->66<!-- /br:models.chatVisible --> models · category detection · Elo scores │
545
+ │ 2M+ requests · <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
462
546
  ├──────────────────────────────────────────────────────────────┤
463
547
  │ Agent Loop │
464
548
  │ 16 tools · Sessions · Compaction · Pricing · Plugin SDK │
465
549
  ├──────────────────────────────────────────────────────────────┤
466
550
  │ BlockRun Gateway │
467
- │ <!-- br:models.chatVisible -->66<!-- /br:models.chatVisible --> LLMs · CoinGecko · Search · Image APIs · paid services │
551
+ │ <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
468
552
  ├──────────────────────────────────────────────────────────────┤
469
553
  │ x402 Micropayment Protocol │
470
- │ HTTP 402 · USDC on Base & Solana · signed payment payloads │
554
+ │ HTTP 402 · USDC on Solana & Base · signed payment payloads │
471
555
  └──────────────────────────────────────────────────────────────┘
472
556
  │
473
557
  ▼
@@ -508,7 +592,7 @@ src/
508
592
  ├── stats/ Usage tracking + insights engine
509
593
  ├── ui/ Ink-based terminal UI
510
594
  ├── proxy/ Payment proxy for external tools
511
- ├── router/ Learned model router (<!-- br:models.chatVisible -->66<!-- /br:models.chatVisible --> models, Elo scoring)
595
+ ├── router/ Learned model router (<!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models, Elo scoring)
512
596
  ├── wallet/ Wallet management (Base + Solana)
513
597
  ├── mcp/ MCP server auto-discovery
514
598
  └── commands/ CLI subcommands
@@ -518,13 +602,13 @@ src/
518
602
 
519
603
  ## Free tier, for real
520
604
 
521
- Start with **zero dollars**. Franklin defaults to free NVIDIA models that need no wallet funding.
605
+ 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.
522
606
 
523
607
  ```bash
524
608
  franklin --model free
525
609
  ```
526
610
 
527
- When you fund the wallet, Franklin gets more purchasing power: Sonnet, Opus, GPT, Gemini, Grok, and paid tools like Exa, DALL-E, and CoinGecko Pro.
611
+ Once you fund it — [either way](#two-ways-to-pay) — Franklin gets more purchasing power: Sonnet, Opus, GPT, Gemini, Grok, and paid tools like Exa, image generation, and live market data.
528
612
 
529
613
  ---
530
614
 
@@ -157,13 +157,14 @@ async function exaAnswerTry(query, client) {
157
157
  // We inline the request rather than invoke the capability through the full
158
158
  // tool framework because prefetch runs outside the agent loop — no
159
159
  // permission prompt, no streaming.
160
- const { loadChain, API_URLS } = await import('../config.js');
160
+ const { loadChain } = await import('../config.js');
161
+ const { gatewayBase, gatewayHeaders } = await import('../payments/auth-mode.js');
161
162
  const chain = loadChain();
162
- const apiUrl = API_URLS[chain];
163
+ const apiUrl = gatewayBase();
163
164
  void client; // (future: unify the paid-endpoint client so we reuse wallet caching)
164
165
  const res = await fetch(`${apiUrl}/v1/exa/answer`, {
165
166
  method: 'POST',
166
- headers: { 'Content-Type': 'application/json' },
167
+ headers: { 'Content-Type': 'application/json', ...gatewayHeaders() },
167
168
  body: JSON.stringify({ query }),
168
169
  });
169
170
  if (res.status === 402) {
package/dist/agent/llm.js CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
7
7
  import { USER_AGENT } from '../config.js';
8
+ import { gatewayHeaders } from '../payments/auth-mode.js';
8
9
  import { appendSettlementRow } from '../stats/cost-log.js';
9
10
  import { routeRequest, parseRoutingProfile } from '../router/index.js';
10
11
  import { ThinkTagStripper } from './think-tag-stripper.js';
@@ -631,8 +632,12 @@ export class ModelClient {
631
632
  const headers = {
632
633
  'Content-Type': 'application/json',
633
634
  'anthropic-version': '2023-06-01',
635
+ // Placeholder for Anthropic-shaped clients — the real credential is
636
+ // either the x402 signature added on the 402 retry, or the bearer key
637
+ // that gatewayHeaders() contributes in API-key mode.
634
638
  'x-api-key': 'x402-agent-handles-auth',
635
639
  'User-Agent': USER_AGENT,
640
+ ...gatewayHeaders(),
636
641
  };
637
642
  // Enable prompt caching + extended thinking betas for Anthropic models
638
643
  if (isAnthropic) {
@@ -2067,9 +2067,12 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2067
2067
  // promo pricing, prompt-cache discounts, or per-call flat fees
2068
2068
  // (verified 2026-05-09 against cost_log.jsonl: token-based
2069
2069
  // estimate said $34.79 across the same calls the wallet only
2070
- // paid $2.24 for — a 15× drift). estimateCost only fills in
2071
- // when no payment was made (free model / cached / pre-stream
2072
- // failure), where the gateway charge is genuinely 0.
2070
+ // paid $2.24 for — a 15× drift). estimateCost fills in when no x402
2071
+ // payment was made: a free model / cached / pre-stream failure, where
2072
+ // the gateway charge is genuinely 0 — and every call in API-key mode,
2073
+ // where the gateway settles against the prepaid balance and returns no
2074
+ // charge amount at all. The estimate is flagged as such so `franklin
2075
+ // stats` does not present it as a settled figure.
2073
2076
  //
2074
2077
  // Pass the fallback flag so franklin-stats.json's totalFallbacks +
2075
2078
  // per-model fallbackCount stay in sync with the audit log a few
@@ -2080,7 +2083,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2080
2083
  ? paidUsd
2081
2084
  : estimateCost(resolvedModel, inputTokens, usage.outputTokens, 1);
2082
2085
  const llmLatencyMs = Date.now() - llmCallStartedAt;
2083
- recordUsage(resolvedModel, inputTokens, usage.outputTokens, callCost, llmLatencyMs, turnFailedModels.size > 0);
2086
+ recordUsage(resolvedModel, inputTokens, usage.outputTokens, callCost, llmLatencyMs, turnFailedModels.size > 0, paidUsd <= 0);
2084
2087
  // ── Circuit breakers: prevent infinite-loop wallet drain ──
2085
2088
  // Per-turn $-cap was removed in v3.11.0 — runaway loops are caught by
2086
2089
  // MAX_TOOL_CALLS_PER_TURN (25) and MAX_TINY_RESPONSES (2) above; the
@@ -106,6 +106,17 @@ const SECRET_PATTERNS = [
106
106
  envVar: 'SLACK_TOKEN',
107
107
  },
108
108
  // ── Stripe ──
109
+ // ── BlockRun ──
110
+ // Prepaid API keys for the api.blockrun.ai gateway. Franklin reads these
111
+ // from BLOCKRUN_API_KEY / ~/.blockrun/api-key, so without this pattern a
112
+ // key can reach transcripts, `franklin logs`, and any model prompt that
113
+ // echoes the environment.
114
+ {
115
+ label: 'blockrun_api_key',
116
+ pattern: /\bbrk_(?:live|test)_[A-Za-z0-9]{20,}\b/g,
117
+ description: 'BlockRun gateway API key',
118
+ envVar: 'BLOCKRUN_API_KEY',
119
+ },
109
120
  {
110
121
  label: 'stripe_live',
111
122
  pattern: /\bsk_live_[A-Za-z0-9]{20,}\b/g,
@@ -1,8 +1,32 @@
1
1
  import chalk from 'chalk';
2
2
  import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
3
- import { loadChain } from '../config.js';
3
+ import { loadChain, DASHBOARD_URL } from '../config.js';
4
+ import { isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
5
+ import { loadStats } from '../stats/tracker.js';
4
6
  export async function balanceCommand() {
5
7
  const chain = loadChain();
8
+ // API-key mode settles against a prepaid credit balance. The gateway exposes
9
+ // no key-scoped balance or usage endpoint, so there is no number to print
10
+ // that would be true — report what is known (the key works, what Franklin
11
+ // has spent locally) and send the user to the authority for the rest, rather
12
+ // than inventing a figure.
13
+ if (isKeyMode()) {
14
+ const key = loadApiKey();
15
+ console.log(`Pay mode: ${chalk.green('api-key')}`);
16
+ console.log(`Key: ${chalk.cyan(key ? maskApiKey(key) : 'unknown')}`);
17
+ try {
18
+ const stats = loadStats();
19
+ const spent = stats.totalCostUsd ?? 0;
20
+ 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)'));
23
+ }
24
+ 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.'));
27
+ console.log(chalk.dim('To spend from a USDC wallet instead: franklin --wallet, or franklin logout.'));
28
+ return;
29
+ }
6
30
  try {
7
31
  if (chain === 'solana') {
8
32
  const client = await setupAgentSolanaWallet({ silent: true });
@@ -15,9 +15,30 @@ import fs from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import os from 'node:os';
17
17
  import { setupAgentWallet, setupAgentSolanaWallet, } from '@blockrun/llm';
18
- import { loadChain, API_URLS, VERSION, BLOCKRUN_DIR } from '../config.js';
18
+ import { loadChain, VERSION, BLOCKRUN_DIR, DASHBOARD_URL, KEY_API_URL, USER_AGENT } from '../config.js';
19
+ import { gatewayBase, isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
19
20
  import { isTelemetryEnabled, readAllRecords } from '../telemetry/store.js';
20
21
  import { getAvailableUpdateFresh, kickoffVersionCheck } from '../version-check.js';
22
+ /** Free, auth-gated probe — proves the key works without spending credit. */
23
+ async function verifyKeyReachable() {
24
+ const key = loadApiKey();
25
+ if (!key)
26
+ return { ok: false, detail: 'no key resolved' };
27
+ try {
28
+ const res = await fetch(`${KEY_API_URL}/v1/models`, {
29
+ headers: { Authorization: `Bearer ${key}`, 'User-Agent': USER_AGENT },
30
+ signal: AbortSignal.timeout(8_000),
31
+ });
32
+ if (res.status === 401)
33
+ return { ok: false, detail: 'gateway returned 401' };
34
+ if (!res.ok)
35
+ return { ok: false, detail: `gateway returned HTTP ${res.status}` };
36
+ return { ok: true, detail: 'authenticated' };
37
+ }
38
+ catch (err) {
39
+ return { ok: false, detail: err instanceof Error ? err.message : 'unreachable' };
40
+ }
41
+ }
21
42
  async function runChecks() {
22
43
  const out = [];
23
44
  // Kick off the authoritative version fetch FIRST, in parallel with the
@@ -90,6 +111,31 @@ async function runChecks() {
90
111
  }
91
112
  // ── 5. Wallet ─────────────────────────────────────────────────────
92
113
  let walletBalance = null;
114
+ // ── Pay mode ──────────────────────────────────────────────────────
115
+ // Which credential will actually be spent matters more than any single
116
+ // check below — a user with a key set but an unfunded wallet is healthy,
117
+ // and vice versa, so name the mode before reporting on either.
118
+ if (isKeyMode()) {
119
+ const key = loadApiKey();
120
+ const verdict = await verifyKeyReachable();
121
+ out.push({
122
+ name: 'Pay mode',
123
+ status: verdict.ok ? 'ok' : 'fail',
124
+ detail: verdict.ok
125
+ ? `api-key ${key ? maskApiKey(key) : ''} → ${gatewayBase()}`
126
+ : `api-key rejected — ${verdict.detail}`,
127
+ remedy: verdict.ok
128
+ ? undefined
129
+ : `Check the key at ${DASHBOARD_URL}/dashboard, or run \`franklin logout\` to fall back to the wallet`,
130
+ });
131
+ }
132
+ else {
133
+ out.push({
134
+ name: 'Pay mode',
135
+ status: 'ok',
136
+ detail: `wallet (${chain ?? 'unset'}) → ${gatewayBase()}`,
137
+ });
138
+ }
93
139
  let walletAddress = '';
94
140
  if (chain) {
95
141
  try {
@@ -145,7 +191,7 @@ async function runChecks() {
145
191
  }
146
192
  // ── 6. Gateway reachability ───────────────────────────────────────
147
193
  if (chain) {
148
- const apiUrl = API_URLS[chain];
194
+ const apiUrl = gatewayBase();
149
195
  try {
150
196
  const ctl = new AbortController();
151
197
  const t = setTimeout(() => ctl.abort(), 5000);
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `franklin login` — hand Franklin a prepaid BlockRun API key.
3
+ *
4
+ * The wallet remains Franklin's identity; a key is the second on-ramp for
5
+ * people who would rather top up a balance at user.blockrun.ai than fund a
6
+ * USDC wallet. Both can be configured at once — the key wins, and `--wallet`
7
+ * on any run forces the wallet back for that invocation.
8
+ *
9
+ * The key is verified against the gateway before it is written, so a
10
+ * truncated paste or a revoked key fails here rather than as a confusing 401
11
+ * partway through a session.
12
+ */
13
+ export declare function loginCommand(key?: string): Promise<void>;
14
+ export declare function logoutCommand(): Promise<void>;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `franklin login` — hand Franklin a prepaid BlockRun API key.
3
+ *
4
+ * The wallet remains Franklin's identity; a key is the second on-ramp for
5
+ * people who would rather top up a balance at user.blockrun.ai than fund a
6
+ * USDC wallet. Both can be configured at once — the key wins, and `--wallet`
7
+ * on any run forces the wallet back for that invocation.
8
+ *
9
+ * The key is verified against the gateway before it is written, so a
10
+ * truncated paste or a revoked key fails here rather than as a confusing 401
11
+ * partway through a session.
12
+ */
13
+ import chalk from 'chalk';
14
+ import { KEY_API_URL, API_KEY_FILE, DASHBOARD_URL, USER_AGENT, loadChain } from '../config.js';
15
+ import { clearApiKey, isApiKeyShaped, loadApiKey, maskApiKey, saveApiKey, } from '../payments/auth-mode.js';
16
+ /**
17
+ * GET /v1/models is free and auth-gated on the key host — 401 without a valid
18
+ * key, 200 with one. That makes it the right probe: it proves the key works
19
+ * without spending any of the balance it is checking.
20
+ */
21
+ async function verifyKey(key) {
22
+ try {
23
+ const res = await fetch(`${KEY_API_URL}/v1/models`, {
24
+ headers: { Authorization: `Bearer ${key}`, 'User-Agent': USER_AGENT },
25
+ signal: AbortSignal.timeout(20_000),
26
+ });
27
+ if (res.status === 401)
28
+ return { ok: false, detail: 'gateway rejected the key (401)' };
29
+ if (!res.ok)
30
+ return { ok: false, detail: `gateway returned HTTP ${res.status}` };
31
+ const body = (await res.json());
32
+ const count = Array.isArray(body.data) ? body.data.length : 0;
33
+ return { ok: true, detail: `${count} models available` };
34
+ }
35
+ catch (err) {
36
+ const msg = err instanceof Error ? err.message : 'unknown error';
37
+ return { ok: false, detail: `could not reach ${KEY_API_URL} — ${msg}` };
38
+ }
39
+ }
40
+ function printStatus() {
41
+ const key = loadApiKey();
42
+ const fromEnv = Boolean(process.env.BLOCKRUN_API_KEY?.trim());
43
+ if (!key) {
44
+ console.log(`Pay mode: ${chalk.magenta('wallet')} (${chalk.magenta(loadChain())})`);
45
+ console.log(chalk.dim('\nNo API key configured. Franklin pays with the USDC wallet.'));
46
+ console.log(chalk.dim(`Want a prepaid key instead? Sign up at ${DASHBOARD_URL}, then:`));
47
+ console.log(chalk.dim(' franklin login brk_live_...'));
48
+ return;
49
+ }
50
+ console.log(`Pay mode: ${chalk.green('api-key')}`);
51
+ console.log(`Key: ${chalk.cyan(maskApiKey(key))}`);
52
+ console.log(`Source: ${chalk.dim(fromEnv ? 'BLOCKRUN_API_KEY (env)' : API_KEY_FILE)}`);
53
+ console.log(`Gateway: ${chalk.dim(KEY_API_URL)}`);
54
+ console.log(chalk.dim(`\nBalance and activity: ${DASHBOARD_URL}/dashboard`));
55
+ console.log(chalk.dim('Force the wallet for one run with `franklin --wallet`.'));
56
+ }
57
+ export async function loginCommand(key) {
58
+ if (!key) {
59
+ printStatus();
60
+ return;
61
+ }
62
+ const trimmed = key.trim();
63
+ if (!isApiKeyShaped(trimmed)) {
64
+ console.log(chalk.red('That does not look like a BlockRun API key.'));
65
+ console.log(chalk.dim('Expected `brk_live_...` or `brk_test_...`.'));
66
+ console.log(chalk.dim(`Create one at ${DASHBOARD_URL}/dashboard.`));
67
+ process.exit(1);
68
+ }
69
+ process.stdout.write(chalk.dim('Verifying key… '));
70
+ const { ok, detail } = await verifyKey(trimmed);
71
+ if (!ok) {
72
+ console.log(chalk.red('failed'));
73
+ console.log(chalk.red(` ${detail}`));
74
+ console.log(chalk.dim(`\nNothing was saved. Check the key at ${DASHBOARD_URL}/dashboard.`));
75
+ process.exit(1);
76
+ }
77
+ console.log(chalk.green('ok') + chalk.dim(` — ${detail}`));
78
+ saveApiKey(trimmed);
79
+ console.log(`\nSaved ${chalk.cyan(maskApiKey(trimmed))} to ${chalk.dim(API_KEY_FILE)}`);
80
+ console.log(chalk.dim('Franklin now pays from your prepaid balance instead of the wallet.'));
81
+ console.log(chalk.dim(`Top up and watch spend at ${DASHBOARD_URL}/dashboard.`));
82
+ console.log(chalk.dim('Your wallet is untouched — `franklin --wallet` still spends from it.'));
83
+ }
84
+ export async function logoutCommand() {
85
+ const removed = clearApiKey();
86
+ if (!removed) {
87
+ console.log(chalk.dim('No stored API key to remove.'));
88
+ }
89
+ else {
90
+ console.log(`Removed ${chalk.dim(API_KEY_FILE)}.`);
91
+ }
92
+ if (process.env.BLOCKRUN_API_KEY?.trim()) {
93
+ console.log(chalk.yellow('BLOCKRUN_API_KEY is still set in your environment — unset it to fall back to the wallet.'));
94
+ return;
95
+ }
96
+ console.log(`Pay mode is now ${chalk.magenta('wallet')} (${chalk.magenta(loadChain())}).`);
97
+ }
@@ -1,5 +1,6 @@
1
1
  import chalk from 'chalk';
2
- import { loadChain, API_URLS } from '../config.js';
2
+ import { loadChain } from '../config.js';
3
+ import { gatewayBase } from '../payments/auth-mode.js';
3
4
  import { getGatewayModels, GATEWAY_MARGIN, } from '../gateway-models.js';
4
5
  /**
5
6
  * `franklin models` — the live catalog.
@@ -105,7 +106,7 @@ function printSection(heading, models, render) {
105
106
  }
106
107
  export async function modelsCommand() {
107
108
  const chain = loadChain();
108
- const apiUrl = API_URLS[chain];
109
+ const apiUrl = gatewayBase();
109
110
  console.log(chalk.bold('Available Models\n'));
110
111
  console.log(`Chain: ${chalk.magenta(chain)} — ${chalk.dim(apiUrl)}\n`);
111
112
  let models;
@@ -7,7 +7,8 @@
7
7
  import chalk from 'chalk';
8
8
  import readline from 'node:readline';
9
9
  import { ModelClient } from '../agent/llm.js';
10
- import { loadChain, API_URLS } from '../config.js';
10
+ import { loadChain } from '../config.js';
11
+ import { gatewayBase } from '../payments/auth-mode.js';
11
12
  import { loadAllPlugins, getPlugin, listWorkflowPlugins } from '../plugins/registry.js';
12
13
  import { loadWorkflowConfig, saveWorkflowConfig, runWorkflow, getStats, getByAction, formatWorkflowResult, formatWorkflowStats, } from '../plugins/runner.js';
13
14
  import { DEFAULT_MODEL_TIERS } from '../plugin-sdk/workflow.js';
@@ -29,7 +30,7 @@ export async function pluginCommand(pluginId, action, options) {
29
30
  }
30
31
  const workflow = workflowFactory();
31
32
  const chain = loadChain();
32
- const apiUrl = API_URLS[chain];
33
+ const apiUrl = gatewayBase();
33
34
  const client = new ModelClient({ apiUrl, chain, debug: options.debug });
34
35
  const existingConfig = loadWorkflowConfig(workflow.id);
35
36
  switch (action) {
@@ -16,7 +16,8 @@
16
16
  */
17
17
  import { interactiveSession } from '../agent/loop.js';
18
18
  import { predictionCapabilities, resetToolSessionState } from '../tools/index.js';
19
- import { loadChain, API_URLS } from '../config.js';
19
+ import { loadChain } from '../config.js';
20
+ import { gatewayBase } from '../payments/auth-mode.js';
20
21
  import { resolveModel } from '../ui/model-picker.js';
21
22
  const PREDICTION_SYSTEM = [
22
23
  'You are a sharp, disciplined forecasting analyst — think like a professional who is about to put real money on this question.',
@@ -47,7 +48,7 @@ export async function predictCommand(options) {
47
48
  return;
48
49
  }
49
50
  const chain = loadChain();
50
- const apiUrl = API_URLS[chain];
51
+ const apiUrl = gatewayBase();
51
52
  const model = resolveModel(options.model);
52
53
  const asJson = options.json !== false;
53
54
  resetToolSessionState();
@@ -5,13 +5,14 @@
5
5
  import chalk from 'chalk';
6
6
  import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
7
7
  import { createProxy } from '../proxy/server.js';
8
- import { loadChain, API_URLS, DEFAULT_PROXY_PORT } from '../config.js';
8
+ import { loadChain, DEFAULT_PROXY_PORT } from '../config.js';
9
+ import { gatewayBase } from '../payments/auth-mode.js';
9
10
  import { loadConfig } from './config.js';
10
11
  import { printBanner } from '../banner.js';
11
12
  export async function proxyCommand(options) {
12
13
  const version = options.version ?? '1.0.0';
13
14
  const chain = loadChain();
14
- const apiUrl = API_URLS[chain];
15
+ const apiUrl = gatewayBase();
15
16
  const fallbackEnabled = options.fallback !== false;
16
17
  const config = loadConfig();
17
18
  const port = parseInt(options.port || String(DEFAULT_PROXY_PORT));
@@ -1,9 +1,21 @@
1
1
  import chalk from 'chalk';
2
2
  import { getOrCreateWallet, scanWallets, getOrCreateSolanaWallet, scanSolanaWallets, } from '@blockrun/llm';
3
- import { saveChain } from '../config.js';
3
+ import { saveChain, DASHBOARD_URL } from '../config.js';
4
+ import { isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
4
5
  export async function setupCommand(chainArg) {
5
6
  // Solana is the default chain; `franklin setup base` opts into Base.
6
7
  const chain = chainArg === 'base' ? 'base' : 'solana';
8
+ // A configured key already pays for everything, so creating a wallet here
9
+ // would be busywork the user did not ask for. Say so and stop, rather than
10
+ // silently making a second credential they will never fund.
11
+ if (isKeyMode()) {
12
+ const key = loadApiKey();
13
+ console.log(chalk.green('Already set up with an API key.'));
14
+ console.log(`Key: ${chalk.cyan(key ? maskApiKey(key) : 'unknown')}`);
15
+ console.log(chalk.dim(`\nTop up at ${DASHBOARD_URL}/dashboard, then run \`franklin start\`.`));
16
+ console.log(chalk.dim('Want a USDC wallet as well? Run `franklin logout` first, then `franklin setup`.'));
17
+ return;
18
+ }
7
19
  if (chain === 'solana') {
8
20
  const wallets = scanSolanaWallets();
9
21
  if (wallets.length > 0) {
@@ -47,4 +59,6 @@ export async function setupCommand(chainArg) {
47
59
  saveChain(chain);
48
60
  console.log(`Then run ${chalk.bold('franklin start')} to begin.\n`);
49
61
  console.log(chalk.dim(`Chain: ${chain} — saved to ~/.blockrun/`));
62
+ console.log(chalk.dim(`\nPrefer a prepaid balance to a wallet? Sign up at ${DASHBOARD_URL},`));
63
+ console.log(chalk.dim('then run `franklin login brk_live_...` — no crypto required.'));
50
64
  }
@@ -8,7 +8,8 @@
8
8
  * `runSlackBot` is the real security boundary, mirroring Telegram's owner lock.
9
9
  */
10
10
  import chalk from 'chalk';
11
- import { loadChain, API_URLS } from '../config.js';
11
+ import { loadChain } from '../config.js';
12
+ import { gatewayBase } from '../payments/auth-mode.js';
12
13
  import { assembleInstructions } from '../agent/context.js';
13
14
  import { allCapabilities } from '../tools/index.js';
14
15
  import { loadMcpConfig } from '../mcp/config.js';
@@ -38,7 +39,7 @@ export async function slackCommand(opts) {
38
39
  process.exit(1);
39
40
  }
40
41
  const chain = loadChain();
41
- const apiUrl = API_URLS[chain];
42
+ const apiUrl = gatewayBase();
42
43
  const config = loadConfig();
43
44
  const model = opts.model ||
44
45
  config['default-model'] ||
@@ -19,7 +19,8 @@ import { loadConfig as loadSocialConfig, saveConfig as saveSocialConfig, isConfi
19
19
  import { SocialBrowser, SOCIAL_PROFILE_DIR } from '../social/browser.js';
20
20
  import { runX } from '../social/x.js';
21
21
  import { getStats } from '../social/db.js';
22
- import { loadChain, API_URLS } from '../config.js';
22
+ import { loadChain } from '../config.js';
23
+ import { gatewayBase } from '../payments/auth-mode.js';
23
24
  import { loadConfig as loadAppConfig } from './config.js';
24
25
  import { FREE_DEFAULT_MODEL } from '../free-models.js';
25
26
  /**
@@ -158,7 +159,7 @@ async function runCommand(options) {
158
159
  console.log(` Daily: ${config.x.daily_target} posts`);
159
160
  console.log('');
160
161
  const chain = loadChain();
161
- const apiUrl = API_URLS[chain];
162
+ const apiUrl = gatewayBase();
162
163
  const appConfig = loadAppConfig();
163
164
  const model = options.model || appConfig['default-model'] || FREE_DEFAULT_MODEL;
164
165
  console.log(chalk.dim(` Model: ${model}`));
@@ -2,7 +2,8 @@ import chalk from 'chalk';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
5
- import { BLOCKRUN_DIR, loadChain, API_URLS } from '../config.js';
5
+ import { BLOCKRUN_DIR, loadChain } from '../config.js';
6
+ import { gatewayBase } from '../payments/auth-mode.js';
6
7
  import { retryFetchBalance } from './balance-retry.js';
7
8
  import { flushStats, loadStats, getLiveSpendUsd } from '../stats/tracker.js';
8
9
  import { OPUS_PRICING } from '../pricing.js';
@@ -71,7 +72,7 @@ export async function startCommand(options) {
71
72
  chain = sessMeta.chain;
72
73
  }
73
74
  }
74
- const apiUrl = API_URLS[chain];
75
+ const apiUrl = gatewayBase();
75
76
  const config = loadConfig();
76
77
  // Resolve model. Priority: explicit --model > resumed session's model > user
77
78
  // config default > FREE default. Resuming restores the same model the user was