@blockrun/franklin 3.45.0 → 3.47.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 (57) hide show
  1. package/README.md +32 -11
  2. package/dist/agent/context.js +58 -10
  3. package/dist/agent/llm.js +14 -6
  4. package/dist/agent/loop.js +34 -6
  5. package/dist/agent/optimize.d.ts +1 -1
  6. package/dist/agent/optimize.js +17 -7
  7. package/dist/agent/secret-redact.d.ts +26 -0
  8. package/dist/agent/secret-redact.js +48 -0
  9. package/dist/agent/streaming-executor.js +15 -0
  10. package/dist/commands/doctor.js +18 -0
  11. package/dist/commands/start.js +4 -0
  12. package/dist/commands/usage.d.ts +14 -0
  13. package/dist/commands/usage.js +86 -0
  14. package/dist/commands/wallet-adopt.d.ts +12 -0
  15. package/dist/commands/wallet-adopt.js +49 -0
  16. package/dist/free-models.js +2 -1
  17. package/dist/gateway-models.js +34 -66
  18. package/dist/index.js +16 -0
  19. package/dist/model-catalog.d.ts +10 -0
  20. package/dist/model-catalog.js +77 -0
  21. package/dist/payments/auth-mode.d.ts +5 -19
  22. package/dist/payments/auth-mode.js +15 -17
  23. package/dist/payments/billing-copy.d.ts +37 -0
  24. package/dist/payments/billing-copy.js +57 -0
  25. package/dist/payments/post-with-payment.js +8 -15
  26. package/dist/payments/price-catalog.d.ts +9 -0
  27. package/dist/payments/price-catalog.js +13 -0
  28. package/dist/payments/usage.d.ts +106 -0
  29. package/dist/payments/usage.js +168 -0
  30. package/dist/pricing.d.ts +2 -6
  31. package/dist/pricing.js +16 -3
  32. package/dist/router/vision.js +9 -1
  33. package/dist/stats/tracker.d.ts +9 -1
  34. package/dist/stats/tracker.js +6 -1
  35. package/dist/tools/bash.js +17 -7
  36. package/dist/tools/blockrun.js +1 -1
  37. package/dist/tools/defillama.js +2 -2
  38. package/dist/tools/imagegen.js +5 -4
  39. package/dist/tools/modal.js +12 -6
  40. package/dist/tools/musicgen.js +4 -3
  41. package/dist/tools/phone.js +16 -15
  42. package/dist/tools/prediction.js +12 -11
  43. package/dist/tools/realface.js +2 -2
  44. package/dist/tools/rpc.js +2 -2
  45. package/dist/tools/sensitive-paths.d.ts +1 -1
  46. package/dist/tools/sensitive-paths.js +13 -4
  47. package/dist/tools/surf.js +2 -2
  48. package/dist/tools/videogen.js +6 -5
  49. package/dist/tools/voice.d.ts +1 -1
  50. package/dist/tools/voice.js +5 -4
  51. package/dist/ui/model-picker.d.ts +1 -2
  52. package/dist/ui/model-picker.js +34 -117
  53. package/dist/wallet/reservation.d.ts +24 -0
  54. package/dist/wallet/reservation.js +50 -4
  55. package/dist/wallet/solana-migration.d.ts +48 -0
  56. package/dist/wallet/solana-migration.js +81 -0
  57. package/package.json +6 -4
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `franklin usage` — what the account actually charged, joined to what
3
+ * Franklin recorded.
4
+ *
5
+ * `franklin stats` reports Franklin's own tally, which in key mode is built
6
+ * from catalog prices because the account gateway settles without returning a
7
+ * charge. This command reports the gateway's ledger, which is authoritative,
8
+ * and lines the two up per request rather than comparing totals — a total that
9
+ * matches can still be two errors cancelling out.
10
+ */
11
+ import chalk from 'chalk';
12
+ import { isKeyMode } from '../payments/auth-mode.js';
13
+ import { fetchUsage, reconcile } from '../payments/usage.js';
14
+ import { loadStats } from '../stats/tracker.js';
15
+ import { DASHBOARD_URL } from '../config.js';
16
+ function usd(n) {
17
+ return `$${n.toFixed(n < 0.01 && n > 0 ? 4 : 2)}`;
18
+ }
19
+ export async function usageCommand(opts = {}) {
20
+ if (!isKeyMode()) {
21
+ console.log('Account usage is a key-mode ledger. This session pays from a wallet —');
22
+ console.log('its settled amounts are already exact, and `franklin stats` reports them.');
23
+ return;
24
+ }
25
+ const days = Math.max(1, Math.min(Number(opts.days) || 30, 365));
26
+ const from = new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);
27
+ const ledger = await fetchUsage({ from });
28
+ if (!ledger) {
29
+ console.log(chalk.yellow('Could not read the account ledger.'));
30
+ console.log(`Check your key, or view it at ${DASHBOARD_URL}/dashboard.`);
31
+ process.exitCode = 1;
32
+ return;
33
+ }
34
+ const local = loadStats().history.map((h) => ({ requestId: h.requestId, costUsd: h.costUsd }));
35
+ const r = reconcile(ledger, local);
36
+ if (opts.json) {
37
+ console.log(JSON.stringify(r, null, 2));
38
+ return;
39
+ }
40
+ const t = r.totals;
41
+ console.log(chalk.bold(`\nAccount ledger — last ${days} day(s)\n`));
42
+ console.log(` Charged: ${chalk.green(usd(t.pricedUsd))} across ${t.pricedCount} request(s) ${chalk.dim('(BlockRun, authoritative)')}`);
43
+ if (t.pendingCount > 0) {
44
+ // Not settled zeros — these can still be priced.
45
+ console.log(` Pending: ${chalk.yellow(String(t.pendingCount))} request(s) with no charge yet ${chalk.dim('— not free, not final')}`);
46
+ }
47
+ if (t.freeCount > 0)
48
+ console.log(` Free: ${t.freeCount} request(s) ${chalk.dim('(explicitly not charged)')}`);
49
+ console.log(chalk.dim(` Mix: ${t.chatCount} chat, ${t.serviceCount} service`));
50
+ if (r.unavailableDays.length > 0) {
51
+ // A hidden gap makes two correct ledgers look like they disagree.
52
+ console.log(chalk.yellow(`\n ${r.unavailableDays.length} day(s) could not be listed: ${r.unavailableDays.join(', ')}`));
53
+ console.log(chalk.dim(' Totals above exclude them — this is a short read, not a quiet period.'));
54
+ }
55
+ console.log(chalk.bold('\nAgainst Franklin\'s own journal\n'));
56
+ if (r.matched.length === 0 && r.missingLocally.length === 0) {
57
+ console.log(chalk.dim(' No ledger row could be joined yet. Request ids are recorded from now on,'));
58
+ console.log(chalk.dim(' so calls made before this version have nothing to match against.'));
59
+ }
60
+ const off = r.matched
61
+ .filter((m) => Math.abs(m.deltaUsd) > 0.000_05)
62
+ .sort((a, b) => Math.abs(b.deltaUsd) - Math.abs(a.deltaUsd));
63
+ if (r.matched.length > 0) {
64
+ console.log(` Joined: ${r.matched.length} request(s); ${off.length} where Franklin's estimate differs`);
65
+ }
66
+ for (const m of off.slice(0, 10)) {
67
+ const sign = m.deltaUsd > 0 ? '+' : '';
68
+ // A service charge is a per-call figure only the gateway holds, so a local
69
+ // estimate for one is a guess by construction — say so rather than letting
70
+ // it read as a defect.
71
+ const note = m.row.kind === 'service' ? chalk.dim(' (service — locally an estimate by construction)') : '';
72
+ console.log(` ${m.row.endpoint.padEnd(30)} gateway ${usd(m.row.costUsd)} local ${usd(m.localUsd)} ${sign}${m.deltaUsd.toFixed(4)}${note}`);
73
+ }
74
+ if (r.missingLocally.length > 0) {
75
+ const sum = r.missingLocally.reduce((a, b) => a + b.costUsd, 0);
76
+ console.log(chalk.yellow(`\n ${r.missingLocally.length} charged request(s) have no local row (${usd(sum)}).`));
77
+ console.log(chalk.dim(' Franklin never counted these, so they never reached --max-spend either.'));
78
+ for (const row of r.missingLocally.slice(0, 5)) {
79
+ console.log(chalk.dim(` ${row.timestamp} ${row.endpoint} ${usd(row.costUsd)}`));
80
+ }
81
+ }
82
+ if (r.unjoinable > 0) {
83
+ console.log(chalk.dim(`\n ${r.unjoinable} local row(s) carry no request id and were not compared.`));
84
+ }
85
+ console.log(chalk.dim(`\n Full activity: ${DASHBOARD_URL}/dashboard\n`));
86
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `franklin wallet-adopt <address>` — switch to a Solana wallet Franklin can
3
+ * see but is not using (blockrun#119).
4
+ *
5
+ * Explicit by design. The complaint behind #119 is that an upgrade changed the
6
+ * active address without asking, so the remedy must not do the same thing in
7
+ * the other direction: the user names the address, and only then does anything
8
+ * move. `importSolanaWallet` matches against the address DERIVED from each
9
+ * discovered key (never the file's own `address` field) and backs up the
10
+ * current `~/.blockrun/.solana-session` before replacing it.
11
+ */
12
+ export declare function walletAdoptCommand(address: string): Promise<void>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `franklin wallet-adopt <address>` — switch to a Solana wallet Franklin can
3
+ * see but is not using (blockrun#119).
4
+ *
5
+ * Explicit by design. The complaint behind #119 is that an upgrade changed the
6
+ * active address without asking, so the remedy must not do the same thing in
7
+ * the other direction: the user names the address, and only then does anything
8
+ * move. `importSolanaWallet` matches against the address DERIVED from each
9
+ * discovered key (never the file's own `address` field) and backs up the
10
+ * current `~/.blockrun/.solana-session` before replacing it.
11
+ */
12
+ import chalk from 'chalk';
13
+ import { detectSolanaWalletDivergence, activeSolanaAddress } from '../wallet/solana-migration.js';
14
+ export async function walletAdoptCommand(address) {
15
+ const wanted = address.trim();
16
+ const current = activeSolanaAddress();
17
+ if (current === wanted) {
18
+ console.log(`Already active: ${wanted}`);
19
+ return;
20
+ }
21
+ const divergence = await detectSolanaWalletDivergence();
22
+ const candidates = divergence?.alternatives ?? [];
23
+ const match = candidates.find((w) => w.address === wanted);
24
+ if (!match) {
25
+ console.log(chalk.red(`No discovered wallet derives to ${wanted}.`));
26
+ if (candidates.length > 0) {
27
+ console.log('\nFound on this machine:');
28
+ for (const w of candidates)
29
+ console.log(` ${w.address} (${w.source})`);
30
+ }
31
+ else {
32
+ console.log('Franklin found no other Solana wallets on this machine.');
33
+ }
34
+ process.exitCode = 1;
35
+ return;
36
+ }
37
+ try {
38
+ const { importSolanaWallet } = await import('@blockrun/llm');
39
+ const adopted = await importSolanaWallet(wanted);
40
+ console.log(chalk.green(`Active Solana wallet is now ${adopted}`));
41
+ console.log(chalk.dim(` was: ${current ?? 'none'}`));
42
+ console.log(chalk.dim(` source: ${match.source}`));
43
+ console.log(chalk.dim(' the previous session file was backed up before it was replaced'));
44
+ }
45
+ catch (err) {
46
+ console.log(chalk.red(`Could not adopt ${wanted}: ${err.message}`));
47
+ process.exitCode = 1;
48
+ }
49
+ }
@@ -59,6 +59,7 @@
59
59
  * (FREE_POOL_CONTEXT_FLOOR).
60
60
  * 4. No free vision — see freeVisionModel().
61
61
  */
62
+ import { getModelCatalog } from './model-catalog.js';
62
63
  import { peekGatewayModel } from './gateway-models.js';
63
64
  import { FREE_DEFAULT_MODEL, FREE_POOL_CONTEXT_FLOOR, FREE_PREFERENCE_ORDER, } from './free-models.constants.js';
64
65
  // Re-exported so every consumer keeps importing from ONE place. The constants
@@ -356,7 +357,7 @@ export function isFreeModelId(id) {
356
357
  return true;
357
358
  if (!id)
358
359
  return false;
359
- const entry = peekGatewayModel(id);
360
+ const entry = peekGatewayModel(id) ?? getModelCatalog().models.find(model => model.id === id);
360
361
  if (entry)
361
362
  return entry.billing_mode === 'free';
362
363
  if (id in FREE_MODEL_CONTEXT_WINDOWS)
@@ -15,17 +15,16 @@
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, USER_AGENT } from './config.js';
19
- import { gatewayBase, gatewayHeaders } from './payments/auth-mode.js';
18
+ import { refreshModelCatalog, clearModelCatalogCache, getModelCatalogIdentity } from './model-catalog.js';
20
19
  // ─── Cache ──────────────────────────────────────────────────────────────
21
20
  const CACHE_TTL_MS = 5 * 60_000; // 5 min — gateway rotates models, but not often
22
- const FETCH_TIMEOUT_MS = 4_000; // one-shot on init; don't let a slow gateway hang startup
23
- let cache = null;
24
- let inflight = null;
21
+ const cache = new Map();
22
+ const inflight = new Map();
25
23
  /** Test / reset helper. */
26
24
  export function clearGatewayModelsCache() {
27
- cache = null;
28
- inflight = null;
25
+ cache.clear();
26
+ inflight.clear();
27
+ clearModelCatalogCache();
29
28
  }
30
29
  /**
31
30
  * Synchronous, cache-only lookup. Returns null when the catalog has never been
@@ -52,25 +51,11 @@ export function clearGatewayModelsCache() {
52
51
  * Treat this as "better than a blind default", nothing more.
53
52
  */
54
53
  export function peekGatewayModel(id) {
55
- if (!cache)
56
- return null;
57
- // A catalog fetched for a different chain is not evidence about this one.
58
- if (cache.chain !== currentChain())
59
- return null;
60
- return cache.models.find(m => m.id === id) ?? null;
61
- }
62
- /** loadChain() with the throw swallowed — this is a hot, sync path. */
63
- function currentChain() {
64
- try {
65
- return loadChain();
66
- }
67
- catch {
68
- return 'base';
69
- }
54
+ return cache.get(getModelCatalogIdentity())?.models.find(m => m.id === id) ?? null;
70
55
  }
71
56
  /** Test helper — seed the cache without a network call. */
72
57
  export function __primeGatewayModelsCache(models) {
73
- cache = { models, expiresAt: Date.now() + CACHE_TTL_MS, chain: currentChain() };
58
+ cache.set(getModelCatalogIdentity(), { models, expiresAt: Date.now() + CACHE_TTL_MS });
74
59
  }
75
60
  /**
76
61
  * Fire-and-forget catalog warm. Populates the cache so the sync peek above has
@@ -81,33 +66,13 @@ export function warmGatewayModelsCache() {
81
66
  }
82
67
  // ─── Fetch ──────────────────────────────────────────────────────────────
83
68
  async function doFetch() {
84
- const chain = loadChain();
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
- //
90
- // The schema/JSON gate: without ?format=json the gateway returns a
91
- // typed schema placeholder instead of the data envelope. Documented
92
- // quirk across other endpoints too.
93
- const url = `${gatewayBase()}/v1/models?format=json`;
94
- const ctrl = new AbortController();
95
- const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
96
- try {
97
- const res = await fetch(url, {
98
- signal: ctrl.signal,
99
- headers: { ...gatewayHeaders(), 'User-Agent': USER_AGENT, Accept: 'application/json' },
100
- });
101
- if (!res.ok)
102
- throw new Error(`Gateway models list returned HTTP ${res.status}`);
103
- const body = (await res.json());
104
- if (!Array.isArray(body.data))
105
- throw new Error('Gateway models list missing data[]');
106
- return body.data;
107
- }
108
- finally {
109
- clearTimeout(timer);
110
- }
69
+ const state = await refreshModelCatalog();
70
+ // Bundled rows are not gateway evidence. Surface the failure so callers keep
71
+ // their existing fallbacks (stale cache, static picker) instead of treating
72
+ // the packaged snapshot as a live catalog for five minutes.
73
+ if (state.source !== 'live')
74
+ throw new Error(state.lastError ?? 'Gateway model catalog unavailable');
75
+ return state.models;
111
76
  }
112
77
  /**
113
78
  * Fetch the model catalog, honoring the 5-minute cache. Concurrent callers
@@ -115,24 +80,27 @@ async function doFetch() {
115
80
  * the gateway at process start.
116
81
  */
117
82
  export async function getGatewayModels() {
118
- if (cache && cache.chain === currentChain() && cache.expiresAt > Date.now())
119
- return cache.models;
120
- if (inflight)
121
- return inflight;
122
- inflight = doFetch()
123
- .then(models => {
124
- cache = { models, expiresAt: Date.now() + CACHE_TTL_MS, chain: currentChain() };
83
+ const identity = getModelCatalogIdentity();
84
+ const previous = cache.get(identity);
85
+ if (previous && previous.expiresAt > Date.now())
86
+ return previous.models;
87
+ const pending = inflight.get(identity);
88
+ if (pending)
89
+ return pending;
90
+ const request = doFetch().then(models => {
91
+ // A request completing after an account/chain switch only updates its own cache.
92
+ cache.set(identity, { models, expiresAt: Date.now() + CACHE_TTL_MS });
125
93
  return models;
126
- })
127
- .catch(err => {
128
- // On failure, keep the last good cache if we have one (serve stale
129
- // rather than break the agent). Only hard-fail cold start.
130
- if (cache)
131
- return cache.models;
94
+ }).catch(err => {
95
+ if (previous)
96
+ return previous.models;
132
97
  throw err;
133
- })
134
- .finally(() => { inflight = null; });
135
- return inflight;
98
+ }).finally(() => {
99
+ if (inflight.get(identity) === request)
100
+ inflight.delete(identity);
101
+ });
102
+ inflight.set(identity, request);
103
+ return request;
136
104
  }
137
105
  /** Return models filtered to a specific category (e.g. 'image', 'video', 'music'). */
138
106
  export async function getModelsByCategory(category) {
package/dist/index.js CHANGED
@@ -246,6 +246,22 @@ program
246
246
  const { doctorCommand } = await import('./commands/doctor.js');
247
247
  await doctorCommand(opts);
248
248
  });
249
+ program
250
+ .command('usage')
251
+ .description('Account ledger from the gateway, reconciled against the local journal')
252
+ .option('--days <n>', 'Days to read (default 30, max 365)')
253
+ .option('--json', 'Machine-readable output')
254
+ .action(async (opts) => {
255
+ const { usageCommand } = await import('./commands/usage.js');
256
+ await usageCommand(opts);
257
+ });
258
+ program
259
+ .command('wallet-adopt <address>')
260
+ .description('Make a discovered Solana wallet the active one (backs up the current session)')
261
+ .action(async (address) => {
262
+ const { walletAdoptCommand } = await import('./commands/wallet-adopt.js');
263
+ await walletAdoptCommand(address);
264
+ });
249
265
  program
250
266
  .command('telemetry [action]')
251
267
  .description('Manage opt-in local telemetry (status|enable|disable|view|summary)')
@@ -0,0 +1,10 @@
1
+ /** Shared model facts and policy; payment credentials stay in Franklin. */
2
+ import { type CatalogState, type Network } from '@blockrun/model-catalog';
3
+ export declare function getModelCatalogIdentity(): string;
4
+ export declare function getModelCatalog(): CatalogState;
5
+ export declare function onModelCatalogChange(listener: (state: CatalogState) => void): () => void;
6
+ export declare function refreshModelCatalog(options?: {
7
+ network?: Network;
8
+ force?: boolean;
9
+ }): Promise<CatalogState>;
10
+ export declare function clearModelCatalogCache(): void;
@@ -0,0 +1,77 @@
1
+ /** Shared model facts and policy; payment credentials stay in Franklin. */
2
+ import { createCatalogClient } from '@blockrun/model-catalog';
3
+ import { API_URLS, loadChain, USER_AGENT } from './config.js';
4
+ import { gatewayHeaders, resolvePayMode } from './payments/auth-mode.js';
5
+ const clients = new Map();
6
+ const bundled = new Map();
7
+ function bundledState() {
8
+ const network = sessionNetwork ?? loadChain();
9
+ let state = bundled.get(network);
10
+ if (!state) {
11
+ state = createCatalogClient({ network }).current();
12
+ bundled.set(network, state);
13
+ }
14
+ return state;
15
+ }
16
+ const listeners = new Set();
17
+ let sessionNetwork;
18
+ function activeClient() {
19
+ const mode = resolvePayMode();
20
+ const network = sessionNetwork ?? loadChain();
21
+ const gatewayUrl = `${mode.kind === 'key' ? mode.apiBase : API_URLS[network]}/v1/models?format=json`;
22
+ const catalogUrl = process.env.BLOCKRUN_MODEL_CATALOG_URL
23
+ ?? 'https://raw.githubusercontent.com/BlockRunAI/model-catalog/main/dist/snapshot.v1.json';
24
+ // Separate caches for each chain, endpoint and API account; keys never leave memory.
25
+ const identity = JSON.stringify([network, gatewayUrl, catalogUrl, mode.kind === 'key' ? mode.key : '']);
26
+ let client = clients.get(identity);
27
+ if (!client) {
28
+ const headers = { ...gatewayHeaders(mode), 'User-Agent': USER_AGENT };
29
+ client = createCatalogClient({
30
+ network, gatewayUrl, catalogUrl,
31
+ fetch: (url, init) => globalThis.fetch(url, {
32
+ ...init,
33
+ // A separately hosted public snapshot must never receive the API key.
34
+ headers: String(url) === gatewayUrl ? { ...init?.headers, ...headers } : init?.headers,
35
+ }),
36
+ });
37
+ clients.set(identity, client);
38
+ }
39
+ return { identity, client };
40
+ }
41
+ export function getModelCatalogIdentity() {
42
+ try {
43
+ return activeClient().identity;
44
+ }
45
+ catch {
46
+ return `unconfigured:${sessionNetwork ?? loadChain()}`;
47
+ }
48
+ }
49
+ export function getModelCatalog() {
50
+ // Metadata imports precede CLI flag parsing. An invalid saved key must not
51
+ // prevent --help or --wallet from running; request-time refresh still validates auth.
52
+ try {
53
+ return activeClient().client.current();
54
+ }
55
+ catch {
56
+ return bundledState();
57
+ }
58
+ }
59
+ export function onModelCatalogChange(listener) {
60
+ listeners.add(listener);
61
+ return () => { listeners.delete(listener); };
62
+ }
63
+ export async function refreshModelCatalog(options = {}) {
64
+ if (options.network)
65
+ sessionNetwork = options.network;
66
+ const { identity, client } = activeClient();
67
+ const state = process.env.FRANKLIN_CATALOG_OFFLINE === '1'
68
+ ? client.current() : await client.refresh({ force: options.force });
69
+ if (identity === activeClient().identity)
70
+ for (const listener of listeners)
71
+ listener(state);
72
+ return state;
73
+ }
74
+ export function clearModelCatalogCache() {
75
+ clients.clear();
76
+ sessionNetwork = undefined;
77
+ }
@@ -44,12 +44,7 @@ export declare function maskApiKey(key: string): string;
44
44
  * from the wallet for one run.
45
45
  */
46
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
- */
47
+ /** Refresh a rejected credential without changing the user's payment method. */
53
48
  export declare function invalidateKey(): void;
54
49
  /** Test seam — drop the memoised mode so env/file changes are re-read. */
55
50
  export declare function resetPayModeCache(): void;
@@ -61,7 +56,7 @@ export declare function clearApiKey(): boolean;
61
56
  * Resolve the active payment mode. Memoised per process — the resolution reads
62
57
  * the filesystem and is hit on every gateway call.
63
58
  *
64
- * Precedence: `--wallet` / a rejected key > BLOCKRUN_API_KEY > ~/.blockrun/api-key
59
+ * Precedence: `--wallet` > BLOCKRUN_API_KEY > ~/.blockrun/api-key
65
60
  * > wallet on the active chain.
66
61
  */
67
62
  export declare function resolvePayMode(): PayMode;
@@ -72,7 +67,7 @@ export declare function isKeyMode(): boolean;
72
67
  * `API_URLS[loadChain()]` that call sites used before key mode.
73
68
  */
74
69
  export declare function gatewayBase(): string;
75
- /** The x402 base to retry against when a key-mode call has to fall back. */
70
+ /** The x402 base for an explicitly selected wallet chain. */
76
71
  export declare function walletBase(chain?: Chain): string;
77
72
  /**
78
73
  * Auth + identity headers for the active mode. Empty of auth in wallet mode,
@@ -128,20 +123,11 @@ export declare function fetchCreditBalance(timeoutMs?: number): Promise<CreditBa
128
123
  * `gatewayHeaders()` instead.
129
124
  */
130
125
  export declare function applyGatewayAuth(headers: Record<string, string>, mode?: PayMode): Record<string, string>;
131
- /**
132
- * Classify a key-mode failure so callers know whether falling back to the
133
- * wallet is safe.
134
- *
135
- * Only two statuses are worth retrying elsewhere. A 401 means the key itself
136
- * is bad, so the whole process demotes. A 404 `unsupported_endpoint` means
137
- * this one path is not served on the key host, so only that call falls back.
138
- * Everything else — 400, 402, 5xx — surfaces as-is, so a malformed request
139
- * never silently drains wallet USDC on a second attempt.
140
- */
126
+ /** Classify account errors for display; neither error authorizes wallet billing. */
141
127
  export type KeyFailure = 'invalid-key' | 'unsupported-endpoint' | null;
142
128
  export declare function classifyKeyFailure(status: number, body: string): KeyFailure;
143
129
  /**
144
- * Rewrite a key-host URL onto the wallet host for a fallback retry. The two
130
+ * Rewrite a key-host URL after the user explicitly selects wallet mode. The two
145
131
  * differ by the `/api` segment the wallet hosts carry, so this swaps the
146
132
  * origin and re-adds it rather than a plain string replace.
147
133
  */
@@ -48,16 +48,9 @@ export function useWalletMode() {
48
48
  forceWallet = true;
49
49
  cached = null;
50
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
- */
51
+ /** Refresh a rejected credential without changing the user's payment method. */
57
52
  export function invalidateKey() {
58
- if (cached?.kind === 'key')
59
- cached = null;
60
- forceWallet = true;
53
+ cached = null;
61
54
  }
62
55
  /** Test seam — drop the memoised mode so env/file changes are re-read. */
63
56
  export function resetPayModeCache() {
@@ -67,16 +60,18 @@ export function resetPayModeCache() {
67
60
  function readKeyFile() {
68
61
  try {
69
62
  const raw = fs.readFileSync(API_KEY_FILE, 'utf-8').trim();
70
- return raw || null;
63
+ return raw;
71
64
  }
72
- catch {
73
- return null; // no key on disk — wallet mode
65
+ catch (error) {
66
+ if (error.code === 'ENOENT')
67
+ return null;
68
+ throw new Error('Cannot read the saved API key. Fix its permissions or explicitly use --wallet.');
74
69
  }
75
70
  }
76
71
  /** The key Franklin would use, from env first then disk. Null when unset. */
77
72
  export function loadApiKey() {
78
73
  const fromEnv = process.env.BLOCKRUN_API_KEY?.trim();
79
- if (fromEnv)
74
+ if (fromEnv !== undefined)
80
75
  return fromEnv;
81
76
  return readKeyFile();
82
77
  }
@@ -100,7 +95,7 @@ export function clearApiKey() {
100
95
  * Resolve the active payment mode. Memoised per process — the resolution reads
101
96
  * the filesystem and is hit on every gateway call.
102
97
  *
103
- * Precedence: `--wallet` / a rejected key > BLOCKRUN_API_KEY > ~/.blockrun/api-key
98
+ * Precedence: `--wallet` > BLOCKRUN_API_KEY > ~/.blockrun/api-key
104
99
  * > wallet on the active chain.
105
100
  */
106
101
  export function resolvePayMode() {
@@ -108,7 +103,10 @@ export function resolvePayMode() {
108
103
  return cached;
109
104
  if (!forceWallet) {
110
105
  const key = loadApiKey();
111
- if (key && isApiKeyShaped(key)) {
106
+ if (key !== null) {
107
+ if (!isApiKeyShaped(key)) {
108
+ throw new Error('Invalid API key in BLOCKRUN_API_KEY or the saved key file. Correct it, remove it, or explicitly use --wallet.');
109
+ }
112
110
  cached = { kind: 'key', apiBase: KEY_API_URL, key };
113
111
  return cached;
114
112
  }
@@ -128,7 +126,7 @@ export function isKeyMode() {
128
126
  export function gatewayBase() {
129
127
  return resolvePayMode().apiBase;
130
128
  }
131
- /** The x402 base to retry against when a key-mode call has to fall back. */
129
+ /** The x402 base for an explicitly selected wallet chain. */
132
130
  export function walletBase(chain = loadChain()) {
133
131
  return API_URLS[chain];
134
132
  }
@@ -214,7 +212,7 @@ export function classifyKeyFailure(status, body) {
214
212
  return null;
215
213
  }
216
214
  /**
217
- * Rewrite a key-host URL onto the wallet host for a fallback retry. The two
215
+ * Rewrite a key-host URL after the user explicitly selects wallet mode. The two
218
216
  * differ by the `/api` segment the wallet hosts carry, so this swaps the
219
217
  * origin and re-adds it rather than a plain string replace.
220
218
  */
@@ -0,0 +1,37 @@
1
+ /**
2
+ * How Franklin describes a charge to the user and to the model.
3
+ *
4
+ * Key mode spends prepaid account credits; wallet mode signs USDC over x402.
5
+ * Saying "USDC charged" or "paid via x402" in key mode is not a cosmetic slip:
6
+ * these strings are the receipt the user reads, the approval prompt they say
7
+ * yes to, and the text the model reasons over when it decides whether it can
8
+ * afford the next call. Naming the wrong instrument makes all three wrong.
9
+ *
10
+ * Two rules, and the split matters:
11
+ *
12
+ * Runtime output — receipts, approval prompts, cancellations — calls these
13
+ * helpers, which read the mode at call time. `invalidateKey()` can demote a
14
+ * session to wallet mode mid-run, so the mode must not be captured earlier.
15
+ *
16
+ * Static `spec.description` text is built once at module load, before any
17
+ * mode is settled and with no way to re-render afterwards. It must be
18
+ * phrased so it is true in BOTH modes — state the price, not the rail:
19
+ * "Costs $0.001 per call", never "Costs $0.001 USDC from the wallet".
20
+ * These helpers deliberately do not serve that case.
21
+ */
22
+ /**
23
+ * Parenthetical for a completed charge, e.g. `($5.00 USDC charged)` or
24
+ * `(billed to account credits)`. Key mode states no amount: the local figure
25
+ * is an estimate and the account ledger is authoritative.
26
+ */
27
+ export declare function chargedNote(usd: number): string;
28
+ /** Sentence for an action that was cancelled or never dispatched. */
29
+ export declare function noChargeNote(): string;
30
+ /** Trailing reassurance on an approval prompt, before the user answers. */
31
+ export declare function cancelHint(): string;
32
+ /**
33
+ * Italic receipt line appended to a markdown tool result, e.g.
34
+ * `_$0.005 paid via x402._`. In key mode the rail is wrong AND the amount is
35
+ * unverifiable locally, so it names neither.
36
+ */
37
+ export declare function receiptLine(usd: number): string;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * How Franklin describes a charge to the user and to the model.
3
+ *
4
+ * Key mode spends prepaid account credits; wallet mode signs USDC over x402.
5
+ * Saying "USDC charged" or "paid via x402" in key mode is not a cosmetic slip:
6
+ * these strings are the receipt the user reads, the approval prompt they say
7
+ * yes to, and the text the model reasons over when it decides whether it can
8
+ * afford the next call. Naming the wrong instrument makes all three wrong.
9
+ *
10
+ * Two rules, and the split matters:
11
+ *
12
+ * Runtime output — receipts, approval prompts, cancellations — calls these
13
+ * helpers, which read the mode at call time. `invalidateKey()` can demote a
14
+ * session to wallet mode mid-run, so the mode must not be captured earlier.
15
+ *
16
+ * Static `spec.description` text is built once at module load, before any
17
+ * mode is settled and with no way to re-render afterwards. It must be
18
+ * phrased so it is true in BOTH modes — state the price, not the rail:
19
+ * "Costs $0.001 per call", never "Costs $0.001 USDC from the wallet".
20
+ * These helpers deliberately do not serve that case.
21
+ */
22
+ import { isKeyMode } from './auth-mode.js';
23
+ function fmt(usd) {
24
+ // Sub-cent prices are real here ($0.001 tiers), so keep enough places to
25
+ // avoid rendering them as $0.00.
26
+ return usd < 0.01 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`;
27
+ }
28
+ /**
29
+ * Parenthetical for a completed charge, e.g. `($5.00 USDC charged)` or
30
+ * `(billed to account credits)`. Key mode states no amount: the local figure
31
+ * is an estimate and the account ledger is authoritative.
32
+ */
33
+ export function chargedNote(usd) {
34
+ return isKeyMode()
35
+ ? 'billed to account credits — see Activity at user.blockrun.ai'
36
+ : `${fmt(usd)} USDC charged`;
37
+ }
38
+ /** Sentence for an action that was cancelled or never dispatched. */
39
+ export function noChargeNote() {
40
+ return isKeyMode() ? 'No account credits were spent.' : 'No USDC was spent.';
41
+ }
42
+ /** Trailing reassurance on an approval prompt, before the user answers. */
43
+ export function cancelHint() {
44
+ return isKeyMode()
45
+ ? 'No account credits are spent if you cancel.'
46
+ : 'No USDC is spent if you cancel.';
47
+ }
48
+ /**
49
+ * Italic receipt line appended to a markdown tool result, e.g.
50
+ * `_$0.005 paid via x402._`. In key mode the rail is wrong AND the amount is
51
+ * unverifiable locally, so it names neither.
52
+ */
53
+ export function receiptLine(usd) {
54
+ return isKeyMode()
55
+ ? '_Billed to account credits._'
56
+ : `_${fmt(usd)} paid via x402._`;
57
+ }