@blockrun/franklin 3.43.0 → 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 (58) 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/fallback.d.ts +1 -1
  34. package/dist/proxy/fallback.js +21 -2
  35. package/dist/proxy/server.js +38 -1
  36. package/dist/router/index.js +2 -1
  37. package/dist/serve/cloud-sync.d.ts +1 -0
  38. package/dist/serve/server.js +10 -3
  39. package/dist/stats/tracker.d.ts +15 -1
  40. package/dist/stats/tracker.js +14 -2
  41. package/dist/tools/blockrun.js +10 -3
  42. package/dist/tools/defillama.js +9 -3
  43. package/dist/tools/exa.js +22 -9
  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 +15 -4
  49. package/dist/tools/realface.js +14 -8
  50. package/dist/tools/rpc.js +10 -3
  51. package/dist/tools/surf.js +12 -4
  52. package/dist/tools/videogen.js +4 -2
  53. package/dist/tools/voice.js +6 -4
  54. package/dist/tools/zerox-base.js +4 -2
  55. package/dist/tools/zerox-gasless.js +6 -4
  56. package/dist/trading/providers/blockrun/client.js +20 -7
  57. package/dist/ui/model-picker.js +1 -1
  58. package/package.json +8 -4
@@ -3,6 +3,8 @@
3
3
  * Display usage statistics and cost savings
4
4
  */
5
5
  import chalk from 'chalk';
6
+ import { DASHBOARD_URL } from '../config.js';
7
+ import { isKeyMode } from '../payments/auth-mode.js';
6
8
  import { clearStats, getStatsSummary } from '../stats/tracker.js';
7
9
  import { summarizeSdkSettlements } from '../stats/cost-log.js';
8
10
  export function statsCommand(options) {
@@ -78,8 +80,17 @@ export function statsCommand(options) {
78
80
  // Overview
79
81
  console.log(chalk.bold('\n Overview') + chalk.gray(` (${period})\n`));
80
82
  console.log(` Requests: ${chalk.cyan(stats.totalRequests.toLocaleString())}`);
81
- console.log(` Recorded Cost: ${chalk.green('$' + stats.totalCostUsd.toFixed(4))}` +
83
+ // In API-key mode the gateway settles against a prepaid balance and returns
84
+ // no per-call charge, so spend is priced locally from the published catalog.
85
+ // Mark that plainly rather than presenting an estimate as a settled figure.
86
+ const estimatedUsd = stats.totalEstimatedCostUsd ?? 0;
87
+ const mostlyEstimated = estimatedUsd > 0 && estimatedUsd >= stats.totalCostUsd * 0.5;
88
+ console.log(` Recorded Cost: ${chalk.green((mostlyEstimated ? '~$' : '$') + stats.totalCostUsd.toFixed(4))}` +
82
89
  chalk.gray(' (franklin-stats.json — main loop + proxy + tools that call recordUsage)'));
90
+ if (estimatedUsd > 0) {
91
+ console.log(` of which est.: ${chalk.yellow('$' + estimatedUsd.toFixed(4))}` +
92
+ chalk.gray(' (priced from the published catalog, not a settled x402 amount)'));
93
+ }
83
94
  if (sdkTotal > 0) {
84
95
  const ledgerColor = significantGap ? chalk.yellow : chalk.green;
85
96
  console.log(` SDK Ledger: ${ledgerColor('$' + sdkTotal.toFixed(4))}` +
@@ -159,5 +170,11 @@ export function statsCommand(options) {
159
170
  }
160
171
  }
161
172
  console.log('\n' + '─'.repeat(55));
173
+ if (isKeyMode()) {
174
+ // The key gateway reports no per-call charge, so nothing Franklin prints
175
+ // here can be authoritative. Say where the real number lives.
176
+ console.log(chalk.gray(` Paying by API key — the authoritative balance and activity log live at\n`) +
177
+ chalk.gray(` ${DASHBOARD_URL}/dashboard\n`));
178
+ }
162
179
  console.log(chalk.gray(' Run `franklin stats --clear` to reset statistics\n'));
163
180
  }
@@ -8,7 +8,8 @@
8
8
  * real security boundary.
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 { loadConfig } from './config.js';
@@ -40,7 +41,7 @@ export async function telegramCommand(opts) {
40
41
  allowedUsers.add(id);
41
42
  }
42
43
  const chain = loadChain();
43
- const apiUrl = API_URLS[chain];
44
+ const apiUrl = gatewayBase();
44
45
  const config = loadConfig();
45
46
  // Model: --model flag > config default > free default.
46
47
  const model = opts.model ||
package/dist/config.d.ts CHANGED
@@ -8,3 +8,8 @@ export declare const DEFAULT_PROXY_PORT = 8402;
8
8
  export declare const MARKET_URL: string;
9
9
  export declare function saveChain(chain: Chain): void;
10
10
  export declare function loadChain(): Chain;
11
+ export declare const KEY_API_URL = "https://api.blockrun.ai";
12
+ /** Where `franklin login` persists the key (0600). */
13
+ export declare const API_KEY_FILE: string;
14
+ /** Dashboard host — signup, top-up, activity. Not an API surface. */
15
+ export declare const DASHBOARD_URL = "https://user.blockrun.ai";
package/dist/config.js CHANGED
@@ -54,3 +54,20 @@ export function loadChain() {
54
54
  const hasSolanaWallet = fs.existsSync(path.join(BLOCKRUN_DIR, '.solana-session'));
55
55
  return hasBaseWallet && !hasSolanaWallet ? 'base' : 'solana';
56
56
  }
57
+ // ── API-key mode ──────────────────────────────────────────────────────────
58
+ // BlockRun runs a second, prepaid-credit gateway that authenticates with a
59
+ // bearer key instead of an x402 signature. It shares no auth with the x402
60
+ // hosts above: a bearer key sent to blockrun.ai/api is ignored (still 402),
61
+ // and this host 401s when the key is missing or bad — there is no x402
62
+ // fallback on it. That isolation is what lets key mode ship without touching
63
+ // wallet users.
64
+ //
65
+ // Note the path shape differs: API_URLS entries end in `/api`, this one does
66
+ // not — api.blockrun.ai serves `/v1/...` at the root and returns a
67
+ // `wrong_host` 404 for `/api/v1/...`. Callers that build `${base}/v1/...`
68
+ // work unchanged in both modes; callers that assume the `/api` suffix do not.
69
+ export const KEY_API_URL = 'https://api.blockrun.ai';
70
+ /** Where `franklin login` persists the key (0600). */
71
+ export const API_KEY_FILE = path.join(BLOCKRUN_DIR, 'api-key');
72
+ /** Dashboard host — signup, top-up, activity. Not an API surface. */
73
+ export const DASHBOARD_URL = 'https://user.blockrun.ai';
@@ -15,7 +15,8 @@
15
15
  * service fee — the flat-fee estimate over-counts there by ≤$0.001, which
16
16
  * is the safe direction for budget tracking).
17
17
  */
18
- import { loadChain, API_URLS, USER_AGENT } from './config.js';
18
+ import { loadChain, USER_AGENT } from './config.js';
19
+ import { gatewayBase, gatewayHeaders } from './payments/auth-mode.js';
19
20
  // ─── Cache ──────────────────────────────────────────────────────────────
20
21
  const CACHE_TTL_MS = 5 * 60_000; // 5 min — gateway rotates models, but not often
21
22
  const FETCH_TIMEOUT_MS = 4_000; // one-shot on init; don't let a slow gateway hang startup
@@ -81,17 +82,21 @@ export function warmGatewayModelsCache() {
81
82
  // ─── Fetch ──────────────────────────────────────────────────────────────
82
83
  async function doFetch() {
83
84
  const chain = loadChain();
84
- const base = API_URLS[chain].replace(/\/api$/, '');
85
+ // `gatewayBase()` already carries the `/api` segment on the x402 hosts and
86
+ // deliberately omits it on the API-key host, so append `/v1/...` to it
87
+ // directly rather than stripping and re-adding a prefix that only one of the
88
+ // two hosts has.
89
+ //
85
90
  // The schema/JSON gate: without ?format=json the gateway returns a
86
91
  // typed schema placeholder instead of the data envelope. Documented
87
92
  // quirk across other endpoints too.
88
- const url = `${base}/api/v1/models?format=json`;
93
+ const url = `${gatewayBase()}/v1/models?format=json`;
89
94
  const ctrl = new AbortController();
90
95
  const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
91
96
  try {
92
97
  const res = await fetch(url, {
93
98
  signal: ctrl.signal,
94
- headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
99
+ headers: { ...gatewayHeaders(), 'User-Agent': USER_AGENT, Accept: 'application/json' },
95
100
  });
96
101
  if (!res.ok)
97
102
  throw new Error(`Gateway models list returned HTTP ${res.status}`);
package/dist/index.js CHANGED
@@ -29,17 +29,32 @@ import { proxyCommand } from './commands/proxy.js';
29
29
  import { buildTaskCommand } from './commands/task.js';
30
30
  import { buildContentCommand } from './commands/content.js';
31
31
  import { predictCommand } from './commands/predict.js';
32
+ import { loginCommand, logoutCommand } from './commands/login.js';
33
+ import { useWalletMode } from './payments/auth-mode.js';
32
34
  import { VERSION as version } from './config.js';
35
+ // `--wallet` is process-global rather than a per-command option: it has to take
36
+ // effect before anything resolves a pay mode, and it belongs on `balance`,
37
+ // `doctor` and `models` too, not just `start`. Applying it straight from argv
38
+ // is the only way to get it in ahead of commander's dispatch; it is then
39
+ // removed so per-command parsers do not reject it as unknown. Stripping it also
40
+ // leaves a bare `franklin --wallet` with no args, which falls through to the
41
+ // default `start` action exactly as a bare `franklin` does.
42
+ if (process.argv.includes('--wallet')) {
43
+ useWalletMode();
44
+ process.argv = process.argv.filter((a) => a !== '--wallet');
45
+ }
33
46
  const program = new Command();
34
47
  program
35
48
  .name('franklin')
36
49
  .description('Franklin Agent — The AI agent with a wallet.\n\n' +
37
50
  'While others chat, Franklin Agent spends — turning your USDC into real work.\n\n' +
38
- 'Pay per action in USDC on Base or Solana. No subscriptions. No accounts.')
51
+ 'Pay per action — a USDC wallet on Solana or Base, or a prepaid API key\n' +
52
+ 'from user.blockrun.ai. No subscriptions.')
53
+ .option('--wallet', 'Pay from the USDC wallet even when an API key is configured')
39
54
  .version(version);
40
55
  program
41
56
  .command('setup [chain]')
42
- .description('Create a new wallet for payments (base or solana)')
57
+ .description('Create a new wallet for payments (solana or base)')
43
58
  .action((chain) => setupCommand(chain));
44
59
  program
45
60
  .command('start')
@@ -125,8 +140,16 @@ program
125
140
  .action(modelsCommand);
126
141
  program
127
142
  .command('balance')
128
- .description('Check wallet USDC balance')
143
+ .description('Check wallet USDC balance, or API-key status in key mode')
129
144
  .action(balanceCommand);
145
+ program
146
+ .command('login [key]')
147
+ .description('Store a BlockRun API key (brk_live_...) — omit the key to show current pay mode')
148
+ .action((key) => loginCommand(key));
149
+ program
150
+ .command('logout')
151
+ .description('Remove the stored BlockRun API key and fall back to the wallet')
152
+ .action(logoutCommand);
130
153
  program
131
154
  .command('config <action> [key] [value]')
132
155
  .description('Manage franklin config (set, get, unset, list)\n' +
@@ -15,7 +15,8 @@
15
15
  * gateway-call pattern in src/phone/client.ts and reuses the shared x402 POST
16
16
  * helper.
17
17
  */
18
- import { API_URLS, loadChain } from '../config.js';
18
+ import { loadChain } from '../config.js';
19
+ import { gatewayBase } from '../payments/auth-mode.js';
19
20
  import { postWithPayment } from '../payments/post-with-payment.js';
20
21
  /**
21
22
  * Mint a one-time Coinbase Onramp link that funds `address` with USDC on the
@@ -24,7 +25,7 @@ import { postWithPayment } from '../payments/post-with-payment.js';
24
25
  */
25
26
  export async function getOnrampUrl(address) {
26
27
  const chain = loadChain();
27
- const endpoint = `${API_URLS[chain]}/v1/onramp/token`;
28
+ const endpoint = `${gatewayBase()}/v1/onramp/token`;
28
29
  const result = await postWithPayment(endpoint, { address, network: chain, asset: 'USDC' }, 'Mint a Coinbase Onramp session link to fund this wallet');
29
30
  if (!result.ok) {
30
31
  // A 404 means this gateway has not shipped the onramp route yet (gateway
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Which gateway pays for this process — the x402 wallet or a prepaid API key.
3
+ *
4
+ * Franklin can reach the BlockRun gateway two ways:
5
+ *
6
+ * wallet — blockrun.ai/api (Base) or sol.blockrun.ai/api (Solana). Every
7
+ * paid call answers a 402 by signing USDC from the local wallet.
8
+ * key — api.blockrun.ai with `Authorization: Bearer brk_...`, settled
9
+ * against a prepaid credit balance. No chain involved.
10
+ *
11
+ * The two hosts share no auth: a bearer key on blockrun.ai/api is ignored and
12
+ * still 402s, and api.blockrun.ai 401s when the key is absent or bad rather
13
+ * than falling back to x402. That isolation is the backward-compatibility
14
+ * guarantee — with no key configured this module returns exactly the host and
15
+ * headers Franklin used before key mode existed.
16
+ *
17
+ * Every gateway caller in src/ already funnels through `API_URLS[loadChain()]`
18
+ * + `/v1/...`, so swapping in `resolvePayMode().apiBase` and merging
19
+ * `gatewayHeaders()` is enough; the `/v1/...` concatenation is correct in both
20
+ * modes because the key host serves those paths at its root.
21
+ */
22
+ import { type Chain } from '../config.js';
23
+ export type PayMode = {
24
+ kind: 'key';
25
+ apiBase: string;
26
+ key: string;
27
+ } | {
28
+ kind: 'wallet';
29
+ apiBase: string;
30
+ chain: Chain;
31
+ };
32
+ /**
33
+ * Keys are `brk_live_` / `brk_test_` + an opaque alphanumeric tail. Validated
34
+ * on the way in so a truncated paste fails at `franklin login` rather than as
35
+ * a confusing 401 twenty calls later.
36
+ */
37
+ export declare const API_KEY_PATTERN: RegExp;
38
+ export declare function isApiKeyShaped(value: string): boolean;
39
+ /** Mask for display/logs: `brk_live_H4Oz…QBW5`. Never print a whole key. */
40
+ export declare function maskApiKey(key: string): string;
41
+ /**
42
+ * Force wallet mode for the rest of the process, regardless of any key that is
43
+ * set. Backs the `--wallet` flag so a user with a key on file can still spend
44
+ * from the wallet for one run.
45
+ */
46
+ export declare function useWalletMode(): void;
47
+ /**
48
+ * Demote to wallet mode after the gateway rejected the key (401). Called once
49
+ * per process — a key that does not authenticate will not authenticate on the
50
+ * next call either, and retrying it on every request would double the latency
51
+ * of an entire session.
52
+ */
53
+ export declare function invalidateKey(): void;
54
+ /** Test seam — drop the memoised mode so env/file changes are re-read. */
55
+ export declare function resetPayModeCache(): void;
56
+ /** The key Franklin would use, from env first then disk. Null when unset. */
57
+ export declare function loadApiKey(): string | null;
58
+ export declare function saveApiKey(key: string): void;
59
+ export declare function clearApiKey(): boolean;
60
+ /**
61
+ * Resolve the active payment mode. Memoised per process — the resolution reads
62
+ * the filesystem and is hit on every gateway call.
63
+ *
64
+ * Precedence: `--wallet` / a rejected key > BLOCKRUN_API_KEY > ~/.blockrun/api-key
65
+ * > wallet on the active chain.
66
+ */
67
+ export declare function resolvePayMode(): PayMode;
68
+ /** True when the next gateway call will authenticate with a key. */
69
+ export declare function isKeyMode(): boolean;
70
+ /**
71
+ * The gateway base URL for the active mode. Drop-in replacement for the
72
+ * `API_URLS[loadChain()]` that call sites used before key mode.
73
+ */
74
+ export declare function gatewayBase(): string;
75
+ /** The x402 base to retry against when a key-mode call has to fall back. */
76
+ export declare function walletBase(chain?: Chain): string;
77
+ /**
78
+ * Auth + identity headers for the active mode. Empty of auth in wallet mode,
79
+ * where payment rides on the PAYMENT-SIGNATURE header instead.
80
+ */
81
+ export declare function gatewayHeaders(mode?: PayMode): Record<string, string>;
82
+ /**
83
+ * Merge this mode's auth into a header bag that may already carry a client's
84
+ * own credential, in place.
85
+ *
86
+ * Node lowercases inbound header names while `gatewayHeaders()` returns the
87
+ * canonical `Authorization`, so a plain object happily holds both — and
88
+ * `fetch` then sends two Authorization headers. The gateway reads the client's
89
+ * and answers 401. Every case variant is dropped before ours goes in, so
90
+ * exactly one survives.
91
+ *
92
+ * Only used where Franklin forwards someone else's request (the payment
93
+ * proxy). Direct callers build their headers from scratch and can spread
94
+ * `gatewayHeaders()` instead.
95
+ */
96
+ export declare function applyGatewayAuth(headers: Record<string, string>, mode?: PayMode): Record<string, string>;
97
+ /**
98
+ * Classify a key-mode failure so callers know whether falling back to the
99
+ * wallet is safe.
100
+ *
101
+ * Only two statuses are worth retrying elsewhere. A 401 means the key itself
102
+ * is bad, so the whole process demotes. A 404 `unsupported_endpoint` means
103
+ * this one path is not served on the key host, so only that call falls back.
104
+ * Everything else — 400, 402, 5xx — surfaces as-is, so a malformed request
105
+ * never silently drains wallet USDC on a second attempt.
106
+ */
107
+ export type KeyFailure = 'invalid-key' | 'unsupported-endpoint' | null;
108
+ export declare function classifyKeyFailure(status: number, body: string): KeyFailure;
109
+ /**
110
+ * Rewrite a key-host URL onto the wallet host for a fallback retry. The two
111
+ * differ by the `/api` segment the wallet hosts carry, so this swaps the
112
+ * origin and re-adds it rather than a plain string replace.
113
+ */
114
+ export declare function toWalletUrl(url: string, chain?: Chain): string;
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Which gateway pays for this process — the x402 wallet or a prepaid API key.
3
+ *
4
+ * Franklin can reach the BlockRun gateway two ways:
5
+ *
6
+ * wallet — blockrun.ai/api (Base) or sol.blockrun.ai/api (Solana). Every
7
+ * paid call answers a 402 by signing USDC from the local wallet.
8
+ * key — api.blockrun.ai with `Authorization: Bearer brk_...`, settled
9
+ * against a prepaid credit balance. No chain involved.
10
+ *
11
+ * The two hosts share no auth: a bearer key on blockrun.ai/api is ignored and
12
+ * still 402s, and api.blockrun.ai 401s when the key is absent or bad rather
13
+ * than falling back to x402. That isolation is the backward-compatibility
14
+ * guarantee — with no key configured this module returns exactly the host and
15
+ * headers Franklin used before key mode existed.
16
+ *
17
+ * Every gateway caller in src/ already funnels through `API_URLS[loadChain()]`
18
+ * + `/v1/...`, so swapping in `resolvePayMode().apiBase` and merging
19
+ * `gatewayHeaders()` is enough; the `/v1/...` concatenation is correct in both
20
+ * modes because the key host serves those paths at its root.
21
+ */
22
+ import fs from 'node:fs';
23
+ import { API_URLS, API_KEY_FILE, BLOCKRUN_DIR, KEY_API_URL, USER_AGENT, loadChain, } from '../config.js';
24
+ /**
25
+ * Keys are `brk_live_` / `brk_test_` + an opaque alphanumeric tail. Validated
26
+ * on the way in so a truncated paste fails at `franklin login` rather than as
27
+ * a confusing 401 twenty calls later.
28
+ */
29
+ export const API_KEY_PATTERN = /^brk_(?:live|test)_[A-Za-z0-9]{20,}$/;
30
+ export function isApiKeyShaped(value) {
31
+ return API_KEY_PATTERN.test(value.trim());
32
+ }
33
+ /** Mask for display/logs: `brk_live_H4Oz…QBW5`. Never print a whole key. */
34
+ export function maskApiKey(key) {
35
+ const trimmed = key.trim();
36
+ if (trimmed.length <= 18)
37
+ return 'brk_***';
38
+ return `${trimmed.slice(0, 13)}…${trimmed.slice(-4)}`;
39
+ }
40
+ let cached = null;
41
+ let forceWallet = false;
42
+ /**
43
+ * Force wallet mode for the rest of the process, regardless of any key that is
44
+ * set. Backs the `--wallet` flag so a user with a key on file can still spend
45
+ * from the wallet for one run.
46
+ */
47
+ export function useWalletMode() {
48
+ forceWallet = true;
49
+ cached = null;
50
+ }
51
+ /**
52
+ * Demote to wallet mode after the gateway rejected the key (401). Called once
53
+ * per process — a key that does not authenticate will not authenticate on the
54
+ * next call either, and retrying it on every request would double the latency
55
+ * of an entire session.
56
+ */
57
+ export function invalidateKey() {
58
+ if (cached?.kind === 'key')
59
+ cached = null;
60
+ forceWallet = true;
61
+ }
62
+ /** Test seam — drop the memoised mode so env/file changes are re-read. */
63
+ export function resetPayModeCache() {
64
+ cached = null;
65
+ forceWallet = false;
66
+ }
67
+ function readKeyFile() {
68
+ try {
69
+ const raw = fs.readFileSync(API_KEY_FILE, 'utf-8').trim();
70
+ return raw || null;
71
+ }
72
+ catch {
73
+ return null; // no key on disk — wallet mode
74
+ }
75
+ }
76
+ /** The key Franklin would use, from env first then disk. Null when unset. */
77
+ export function loadApiKey() {
78
+ const fromEnv = process.env.BLOCKRUN_API_KEY?.trim();
79
+ if (fromEnv)
80
+ return fromEnv;
81
+ return readKeyFile();
82
+ }
83
+ export function saveApiKey(key) {
84
+ const trimmed = key.trim();
85
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
86
+ fs.writeFileSync(API_KEY_FILE, trimmed + '\n', { mode: 0o600 });
87
+ cached = null;
88
+ }
89
+ export function clearApiKey() {
90
+ try {
91
+ fs.unlinkSync(API_KEY_FILE);
92
+ cached = null;
93
+ return true;
94
+ }
95
+ catch {
96
+ return false;
97
+ }
98
+ }
99
+ /**
100
+ * Resolve the active payment mode. Memoised per process — the resolution reads
101
+ * the filesystem and is hit on every gateway call.
102
+ *
103
+ * Precedence: `--wallet` / a rejected key > BLOCKRUN_API_KEY > ~/.blockrun/api-key
104
+ * > wallet on the active chain.
105
+ */
106
+ export function resolvePayMode() {
107
+ if (cached)
108
+ return cached;
109
+ if (!forceWallet) {
110
+ const key = loadApiKey();
111
+ if (key && isApiKeyShaped(key)) {
112
+ cached = { kind: 'key', apiBase: KEY_API_URL, key };
113
+ return cached;
114
+ }
115
+ }
116
+ const chain = loadChain();
117
+ cached = { kind: 'wallet', apiBase: API_URLS[chain], chain };
118
+ return cached;
119
+ }
120
+ /** True when the next gateway call will authenticate with a key. */
121
+ export function isKeyMode() {
122
+ return resolvePayMode().kind === 'key';
123
+ }
124
+ /**
125
+ * The gateway base URL for the active mode. Drop-in replacement for the
126
+ * `API_URLS[loadChain()]` that call sites used before key mode.
127
+ */
128
+ export function gatewayBase() {
129
+ return resolvePayMode().apiBase;
130
+ }
131
+ /** The x402 base to retry against when a key-mode call has to fall back. */
132
+ export function walletBase(chain = loadChain()) {
133
+ return API_URLS[chain];
134
+ }
135
+ /**
136
+ * Auth + identity headers for the active mode. Empty of auth in wallet mode,
137
+ * where payment rides on the PAYMENT-SIGNATURE header instead.
138
+ */
139
+ export function gatewayHeaders(mode = resolvePayMode()) {
140
+ const headers = { 'User-Agent': USER_AGENT };
141
+ if (mode.kind === 'key')
142
+ headers['Authorization'] = `Bearer ${mode.key}`;
143
+ return headers;
144
+ }
145
+ /**
146
+ * Merge this mode's auth into a header bag that may already carry a client's
147
+ * own credential, in place.
148
+ *
149
+ * Node lowercases inbound header names while `gatewayHeaders()` returns the
150
+ * canonical `Authorization`, so a plain object happily holds both — and
151
+ * `fetch` then sends two Authorization headers. The gateway reads the client's
152
+ * and answers 401. Every case variant is dropped before ours goes in, so
153
+ * exactly one survives.
154
+ *
155
+ * Only used where Franklin forwards someone else's request (the payment
156
+ * proxy). Direct callers build their headers from scratch and can spread
157
+ * `gatewayHeaders()` instead.
158
+ */
159
+ export function applyGatewayAuth(headers, mode = resolvePayMode()) {
160
+ const auth = gatewayHeaders(mode);
161
+ if (auth.Authorization) {
162
+ for (const key of Object.keys(headers)) {
163
+ if (key.toLowerCase() === 'authorization')
164
+ delete headers[key];
165
+ }
166
+ }
167
+ Object.assign(headers, auth);
168
+ return headers;
169
+ }
170
+ export function classifyKeyFailure(status, body) {
171
+ if (status === 401)
172
+ return 'invalid-key';
173
+ if (status === 404 && body.includes('unsupported_endpoint'))
174
+ return 'unsupported-endpoint';
175
+ return null;
176
+ }
177
+ /**
178
+ * Rewrite a key-host URL onto the wallet host for a fallback retry. The two
179
+ * differ by the `/api` segment the wallet hosts carry, so this swaps the
180
+ * origin and re-adds it rather than a plain string replace.
181
+ */
182
+ export function toWalletUrl(url, chain = loadChain()) {
183
+ if (!url.startsWith(KEY_API_URL))
184
+ return url;
185
+ return API_URLS[chain] + url.slice(KEY_API_URL.length);
186
+ }
@@ -16,6 +16,12 @@ export interface PostResult {
16
16
  status: number;
17
17
  body: Record<string, unknown>;
18
18
  raw: string;
19
+ /**
20
+ * True only when this call completed an x402 handshake, i.e. a wallet
21
+ * signature actually moved USDC. False in key mode and on free endpoints —
22
+ * callers must price those locally rather than recording zero spend.
23
+ */
24
+ settled: boolean;
19
25
  }
20
26
  /**
21
27
  * POST JSON to a gateway endpoint, completing the x402 handshake if the
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
15
15
  import { loadChain, USER_AGENT } from '../config.js';
16
+ import { classifyKeyFailure, gatewayHeaders, invalidateKey, resolvePayMode, toWalletUrl, } from './auth-mode.js';
16
17
  async function extractPaymentReq(response) {
17
18
  let header = response.headers.get('payment-required');
18
19
  if (!header) {
@@ -63,24 +64,56 @@ async function signPayment(response, chain, endpoint, resourceDescription) {
63
64
  */
64
65
  export async function postWithPayment(endpoint, body, resourceDescription, timeoutMs = 30_000) {
65
66
  const chain = loadChain();
66
- const headers = {
67
- 'Content-Type': 'application/json',
68
- 'User-Agent': USER_AGENT,
69
- };
70
67
  const ctrl = new AbortController();
71
68
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
72
69
  try {
73
70
  const payload = JSON.stringify(body);
71
+ const mode = resolvePayMode();
72
+ // Key mode: one authenticated POST, no 402 dance. The gateway settles
73
+ // against the prepaid balance and answers 200 directly.
74
+ if (mode.kind === 'key') {
75
+ const keyHeaders = {
76
+ 'Content-Type': 'application/json',
77
+ ...gatewayHeaders(mode),
78
+ };
79
+ const keyResponse = await fetch(endpoint, {
80
+ method: 'POST',
81
+ signal: ctrl.signal,
82
+ headers: keyHeaders,
83
+ body: payload,
84
+ });
85
+ const keyRaw = await keyResponse.text().catch(() => '');
86
+ const failure = classifyKeyFailure(keyResponse.status, keyRaw);
87
+ // Only a bad key or a path the key host does not serve is worth retrying
88
+ // on the wallet. Anything else (400, 402, 5xx) is returned as-is so a
89
+ // malformed request never silently spends wallet USDC on a second try.
90
+ if (!failure) {
91
+ let parsedKey = {};
92
+ try {
93
+ parsedKey = keyRaw ? JSON.parse(keyRaw) : {};
94
+ }
95
+ catch { /* leave as {} */ }
96
+ return { ok: keyResponse.ok, status: keyResponse.status, body: parsedKey, raw: keyRaw, settled: false };
97
+ }
98
+ if (failure === 'invalid-key')
99
+ invalidateKey();
100
+ endpoint = toWalletUrl(endpoint, chain);
101
+ }
102
+ const headers = {
103
+ 'Content-Type': 'application/json',
104
+ 'User-Agent': USER_AGENT,
105
+ };
74
106
  let response = await fetch(endpoint, {
75
107
  method: 'POST',
76
108
  signal: ctrl.signal,
77
109
  headers,
78
110
  body: payload,
79
111
  });
112
+ let settled = false;
80
113
  if (response.status === 402) {
81
114
  const paymentHeaders = await signPayment(response, chain, endpoint, resourceDescription);
82
115
  if (!paymentHeaders) {
83
- return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '' };
116
+ return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '', settled: false };
84
117
  }
85
118
  response = await fetch(endpoint, {
86
119
  method: 'POST',
@@ -88,6 +121,7 @@ export async function postWithPayment(endpoint, body, resourceDescription, timeo
88
121
  headers: { ...headers, ...paymentHeaders },
89
122
  body: payload,
90
123
  });
124
+ settled = response.ok;
91
125
  }
92
126
  const raw = await response.text().catch(() => '');
93
127
  let parsed = {};
@@ -95,7 +129,7 @@ export async function postWithPayment(endpoint, body, resourceDescription, timeo
95
129
  parsed = raw ? JSON.parse(raw) : {};
96
130
  }
97
131
  catch { /* leave as {} */ }
98
- return { ok: response.ok, status: response.status, body: parsed, raw };
132
+ return { ok: response.ok, status: response.status, body: parsed, raw, settled };
99
133
  }
100
134
  finally {
101
135
  clearTimeout(timer);