@blockrun/franklin 3.43.1 → 3.45.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 (59) hide show
  1. package/README.md +105 -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 +57 -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 +148 -0
  26. package/dist/payments/auth-mode.js +225 -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 +132 -0
  30. package/dist/payments/price-catalog.js +457 -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.d.ts +5 -5
  41. package/dist/tools/defillama.js +19 -13
  42. package/dist/tools/exa.d.ts +1 -1
  43. package/dist/tools/exa.js +43 -21
  44. package/dist/tools/imagegen.js +4 -2
  45. package/dist/tools/modal.js +4 -2
  46. package/dist/tools/musicgen.js +4 -2
  47. package/dist/tools/phone.js +4 -2
  48. package/dist/tools/prediction.js +16 -4
  49. package/dist/tools/realface.js +14 -8
  50. package/dist/tools/rpc.d.ts +1 -1
  51. package/dist/tools/rpc.js +12 -5
  52. package/dist/tools/surf.js +42 -6
  53. package/dist/tools/videogen.js +4 -2
  54. package/dist/tools/voice.js +6 -4
  55. package/dist/tools/zerox-base.js +4 -2
  56. package/dist/tools/zerox-gasless.js +6 -4
  57. package/dist/trading/providers/blockrun/client.js +20 -7
  58. package/dist/ui/model-picker.js +1 -1
  59. 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,91 @@ 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 | `franklin balance` + [dashboard](https://user.blockrun.ai/dashboard); exact except chat |
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
+ ### Spend tracking, and the one thing that stays an estimate
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 most calls now report what they cost. The gateway returns an
217
+ `x-blockrun-cost-usd` header on the pre-priced service families — search, images, RPC,
218
+ market data, phone, sandboxes — and Franklin records that figure exactly.
219
+
220
+ **Chat is the exception, permanently.** Chat settles *after* the answer is on the wire, so
221
+ a slow settlement never becomes a slow answer, which means the amount does not exist yet
222
+ when the headers are written. Franklin reconstructs chat spend from token counts and the
223
+ published rate, so chat rows are estimates. `franklin stats` marks estimated totals with
224
+ `~` and reports the estimated portion separately, so you can always see which is which.
225
+
226
+ `franklin balance` reads your real credit standing from the gateway:
227
+
228
+ ```
229
+ Account: acme (gated)
230
+ Remaining: $41.9980 of $50.00 granted
231
+ Spent: $8.0020 (BlockRun, authoritative)
232
+ Local: ~$8.0431 (Franklin's own tally, all time, both pay modes — expected to differ)
233
+ ```
234
+
235
+ The two numbers differ on purpose: Franklin's tally covers both pay modes and estimates
236
+ chat, while BlockRun's is what you were actually billed. For the full per-call history,
237
+ use the [dashboard](https://user.blockrun.ai/dashboard).
238
+
239
+ ---
240
+
147
241
  ## YOPO
148
242
 
149
243
  **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 +446,7 @@ No single model is best at everything. Sonnet writes better code, Gemini handles
352
446
 
353
447
  ### 🔐 &nbsp;Wallet is identity
354
448
 
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.
449
+ 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
450
 
357
451
  </td>
358
452
  </tr>
@@ -458,16 +552,16 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
458
552
  │ Intent → Smart Router → Tool Use → Spend Control → Result │
459
553
  ├──────────────────────────────────────────────────────────────┤
460
554
  │ Learned Router │
461
- │ 2M+ requests · <!-- br:models.chatVisible -->66<!-- /br:models.chatVisible --> models · category detection · Elo scores │
555
+ │ 2M+ requests · <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
462
556
  ├──────────────────────────────────────────────────────────────┤
463
557
  │ Agent Loop │
464
558
  │ 16 tools · Sessions · Compaction · Pricing · Plugin SDK │
465
559
  ├──────────────────────────────────────────────────────────────┤
466
560
  │ BlockRun Gateway │
467
- │ <!-- br:models.chatVisible -->66<!-- /br:models.chatVisible --> LLMs · CoinGecko · Search · Image APIs · paid services │
561
+ │ <!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
468
562
  ├──────────────────────────────────────────────────────────────┤
469
563
  │ x402 Micropayment Protocol │
470
- │ HTTP 402 · USDC on Base & Solana · signed payment payloads │
564
+ │ HTTP 402 · USDC on Solana & Base · signed payment payloads │
471
565
  └──────────────────────────────────────────────────────────────┘
472
566
  │
473
567
  ▼
@@ -508,7 +602,7 @@ src/
508
602
  ├── stats/ Usage tracking + insights engine
509
603
  ├── ui/ Ink-based terminal UI
510
604
  ├── proxy/ Payment proxy for external tools
511
- ├── router/ Learned model router (<!-- br:models.chatVisible -->66<!-- /br:models.chatVisible --> models, Elo scoring)
605
+ ├── router/ Learned model router (<!-- br:models.chatVisible@live -->76<!-- /br:models.chatVisible@live --> models, Elo scoring)
512
606
  ├── wallet/ Wallet management (Base + Solana)
513
607
  ├── mcp/ MCP server auto-discovery
514
608
  └── commands/ CLI subcommands
@@ -518,13 +612,13 @@ src/
518
612
 
519
613
  ## Free tier, for real
520
614
 
521
- Start with **zero dollars**. Franklin defaults to free NVIDIA models that need no wallet funding.
615
+ 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
616
 
523
617
  ```bash
524
618
  franklin --model free
525
619
  ```
526
620
 
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.
621
+ 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
622
 
529
623
  ---
530
624
 
@@ -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,64 @@
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 { fetchCreditBalance, 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
+ 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
+ }
47
+ try {
48
+ const stats = loadStats();
49
+ const spent = stats.totalCostUsd ?? 0;
50
+ const est = stats.totalEstimatedCostUsd ?? 0;
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)"));
53
+ }
54
+ catch { /* stats are best-effort */ }
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`));
59
+ console.log(chalk.dim('To spend from a USDC wallet instead: franklin --wallet, or franklin logout.'));
60
+ return;
61
+ }
6
62
  try {
7
63
  if (chain === 'solana') {
8
64
  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'] ||