@blockrun/franklin 3.47.0 → 3.49.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 +31 -15
  2. package/dist/agent/commands.js +11 -9
  3. package/dist/agent/context.js +6 -6
  4. package/dist/agent/intent-prefetch.js +4 -3
  5. package/dist/agent/llm.js +6 -6
  6. package/dist/agent/tokens.js +13 -0
  7. package/dist/agent/types.d.ts +2 -1
  8. package/dist/channel/slack.js +4 -2
  9. package/dist/channel/telegram.js +4 -2
  10. package/dist/commands/balance.js +5 -4
  11. package/dist/commands/doctor.js +3 -2
  12. package/dist/commands/models.js +3 -2
  13. package/dist/commands/proxy.js +4 -4
  14. package/dist/commands/setup.js +6 -5
  15. package/dist/commands/start.js +4 -2
  16. package/dist/config.d.ts +13 -1
  17. package/dist/config.js +28 -8
  18. package/dist/gateway-models.d.ts +11 -5
  19. package/dist/gateway-models.js +11 -5
  20. package/dist/index.js +4 -4
  21. package/dist/model-catalog.d.ts +3 -2
  22. package/dist/model-catalog.js +18 -8
  23. package/dist/onramp/client.js +5 -0
  24. package/dist/panel/html.js +39 -22
  25. package/dist/panel/server.js +8 -7
  26. package/dist/payments/auth-mode.d.ts +11 -1
  27. package/dist/payments/auth-mode.js +13 -1
  28. package/dist/pricing.js +25 -11
  29. package/dist/proxy/server.js +2 -1
  30. package/dist/router/index.js +4 -3
  31. package/dist/router/vision.js +13 -0
  32. package/dist/serve/agent-host.d.ts +2 -1
  33. package/dist/serve/server.js +4 -1
  34. package/dist/session/storage.d.ts +2 -1
  35. package/dist/skills/bootstrap.d.ts +2 -1
  36. package/dist/tools/blockrun.js +2 -2
  37. package/dist/tools/defillama.js +2 -2
  38. package/dist/tools/exa.js +2 -2
  39. package/dist/tools/imagegen.js +2 -2
  40. package/dist/tools/moa.d.ts +2 -1
  41. package/dist/tools/modal.d.ts +2 -1
  42. package/dist/tools/modal.js +2 -2
  43. package/dist/tools/musicgen.js +2 -2
  44. package/dist/tools/phone.js +2 -2
  45. package/dist/tools/prediction.js +2 -2
  46. package/dist/tools/realface.js +2 -2
  47. package/dist/tools/rpc.js +2 -2
  48. package/dist/tools/subagent.d.ts +2 -1
  49. package/dist/tools/surf.js +2 -2
  50. package/dist/tools/videogen.js +2 -2
  51. package/dist/tools/voice.js +2 -2
  52. package/dist/tools/wallet.d.ts +2 -1
  53. package/dist/tools/wallet.js +2 -1
  54. package/dist/trading/providers/blockrun/client.js +5 -4
  55. package/dist/ui/model-picker.js +17 -4
  56. package/dist/wallet/manager.d.ts +15 -0
  57. package/dist/wallet/manager.js +27 -1
  58. package/dist/wallet/reservation.js +4 -2
  59. package/package.json +6 -6
package/README.md CHANGED
@@ -54,8 +54,8 @@ Built by the [BlockRun](https://blockrun.ai) team. Apache-2.0. TypeScript. Ships
54
54
  > **YOPO — You Only Pay Outcome**
55
55
  >
56
56
  > Not a subscription (pay for access). Not a generic pay-per-call (pay for trying).
57
- > You pay only for the work Franklin Agent delivers. Provider cost + 5%, settled per action
58
- > in USDC. No monthly fees. No rate limits. No overdraft.
57
+ > You pay only for the work Franklin Agent delivers. Chat is provider cost with no markup, plus $0.001
58
+ > per call; media carries 5%. Settled per action in USDC. No monthly fees. No rate limits. No overdraft.
59
59
 
60
60
  ---
61
61
 
@@ -248,7 +248,7 @@ use the [dashboard](https://user.blockrun.ai/dashboard).
248
248
  | ----------------------- | -------------------------------------------- | ------------------------------------ |
249
249
  | AI subscription | Access. Paid whether you use it or not. | $20–200/month, rate-limited. |
250
250
  | Pay-per-call (OpenAI API, etc.) | Every attempt — even failed ones. | Hidden cost from retries, dead ends. |
251
- | **Franklin Agent (YOPO)** | **The outcome.** Each signed micropayment. | **Provider cost + 5%. No more.** |
251
+ | **Franklin Agent (YOPO)** | **The outcome.** Each signed micropayment. | **Provider cost on chat, no markup, + $0.001/call. Media +5%.** |
252
252
 
253
253
  Three consequences fall out of this:
254
254
 
@@ -544,6 +544,12 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
544
544
  | `/insights [--days N]` | Rich usage analytics |
545
545
  | `/help` | Full command list |
546
546
 
547
+ `/model` takes a shortcut or any full gateway id. The newest models have
548
+ explicit version shortcuts: `opus-5.5`, `sonnet-5.5`, `fable-5.1`,
549
+ `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.1`, `grok-4.7` and `grok-4.6`
550
+ (e.g. `/model gpt-6-sol` or `/model anthropic/claude-opus-5.5`). Bare aliases
551
+ like `opus`, `gpt` and `grok` keep their current targets.
552
+
547
553
  ---
548
554
 
549
555
  ## How it works
@@ -719,20 +725,30 @@ For the recommended live validation order and failure triage, see [docs/live-e2e
719
725
 
720
726
  Franklin uses [BlockRun Model Core](https://github.com/BlockRunAI/model-catalog)
721
727
  for model metadata, picker policy and price estimates. The runtime dependency
722
- is pinned to an immutable commit. On refresh, Franklin reads the public current
728
+ is pinned to an immutable commit. On refresh, Franklin reads the public policy
723
729
  snapshot and the active gateway's catalog, so new models and prices can appear
724
730
  without a Franklin release. Base, Solana and API accounts have separate caches.
725
-
726
- Updates are validated before use. Requests have a four-second deadline each,
727
- refreshes are cached for five minutes, and failures retain the last valid data
728
- (or the bundled snapshot on first launch). `BLOCKRUN_MODEL_CATALOG_URL` can
729
- override the public snapshot URL; an empty value disables remote policy updates.
730
- `FRANKLIN_CATALOG_OFFLINE=1` uses bundled data without catalog network requests.
731
-
732
- Existing free shortcuts remain free. Historical explicit IDs and cost records
733
- remain usable; rolling aliases may select newer models at different prices.
734
- Payment signing and settlement remain in Franklin and its payment SDK. Auto
735
- routing's candidate policy remains separate from the shared catalog pilot.
731
+ The default picker shows Auto and curated groups; other available chat models
732
+ remain accessible through +more / Ctrl+A.
733
+
734
+ Existing Franklin shortcuts, including free aliases, retain their model targets.
735
+ Shared policy can add new shortcuts but cannot retarget one Franklin already
736
+ ships. Gateway price estimates still refresh for the selected model; a stable
737
+ shortcut does not freeze that model's price. Historical explicit IDs and cost
738
+ records remain usable.
739
+
740
+ Policy and gateway requests run concurrently, each with a four-second deadline.
741
+ Successful refreshes are cached for five minutes. If the policy host is
742
+ unreachable, Franklin keeps the last good policy and still refreshes live gateway
743
+ rows. If the gateway fails, the last valid catalog is retained; a cold start can
744
+ use the bundled snapshot, which is not presented as live gateway data. CLI
745
+ startup warms the catalog in the background.
746
+
747
+ `BLOCKRUN_MODEL_CATALOG_URL` overrides the policy snapshot URL; an empty value
748
+ disables remote policy updates. `FRANKLIN_CATALOG_OFFLINE=1` uses bundled data
749
+ without catalog network requests. Payment signing and settlement remain in
750
+ Franklin and its payment SDK. Auto routing's candidate policy remains separate
751
+ from the shared catalog.
736
752
 
737
753
  ## License
738
754
 
@@ -1077,7 +1077,8 @@ export async function handleSlashCommand(input, ctx) {
1077
1077
  }
1078
1078
  // /wallet — show wallet info, import, or export
1079
1079
  if (input === '/wallet' || input.startsWith('/wallet ')) {
1080
- const chain = (await import('../config.js')).loadChain();
1080
+ const { loadChain, CHAIN_LABELS } = await import('../config.js');
1081
+ const chain = loadChain();
1081
1082
  const args = input.slice(7).trim();
1082
1083
  // /wallet export [--show] — key masked by default; --show prints the full key
1083
1084
  // Rationale: terminal scrollback, screen recordings, and shared tmux sessions
@@ -1113,7 +1114,7 @@ export async function handleSlashCommand(input, ctx) {
1113
1114
  return { handled: true };
1114
1115
  }
1115
1116
  const w = getOrCreateWallet();
1116
- ctx.onEvent({ kind: 'text_delta', text: `**Wallet Export (Base)**\n` +
1117
+ ctx.onEvent({ kind: 'text_delta', text: `**Wallet Export (${CHAIN_LABELS[chain]})**\n` +
1117
1118
  ` Address: ${w.address}\n` +
1118
1119
  ` Private Key: ${showKey ? key : mask(key)}\n\n` +
1119
1120
  (showKey
@@ -1136,16 +1137,16 @@ export async function handleSlashCommand(input, ctx) {
1136
1137
  const key = args.slice(6).replace(/\s/g, '');
1137
1138
  if (!key) {
1138
1139
  ctx.onEvent({ kind: 'text_delta', text: `**Usage:** \`/wallet import <private-key>\`\n\n` +
1139
- ` Base: \`/wallet import 0x...\` (hex, 66 chars)\n` +
1140
- ` Solana: \`/wallet import <bs58-key>\` (base58 encoded)\n`
1140
+ ` Base / Arc: \`/wallet import 0x...\` (hex, 66 chars)\n` +
1141
+ ` Solana: \`/wallet import <bs58-key>\` (base58 encoded)\n`
1141
1142
  });
1142
1143
  emitDone(ctx);
1143
1144
  return { handled: true };
1144
1145
  }
1145
- // Shape-validate before touching disk
1146
- if (chain === 'base') {
1146
+ // Shape-validate before touching disk. Base and Arc share the EVM key.
1147
+ if (chain !== 'solana') {
1147
1148
  if (!/^0x[0-9a-fA-F]{64}$/.test(key)) {
1148
- ctx.onEvent({ kind: 'text_delta', text: 'Import error: Base key must be 0x + 64 hex chars (66 total).\n' });
1149
+ ctx.onEvent({ kind: 'text_delta', text: `Import error: ${CHAIN_LABELS[chain]} key must be 0x + 64 hex chars (66 total).\n` });
1149
1150
  emitDone(ctx);
1150
1151
  return { handled: true };
1151
1152
  }
@@ -1175,7 +1176,7 @@ export async function handleSlashCommand(input, ctx) {
1175
1176
  const { saveWallet } = await import('@blockrun/llm');
1176
1177
  const account = privateKeyToAccount(key);
1177
1178
  saveWallet(key);
1178
- ctx.onEvent({ kind: 'text_delta', text: `**Wallet Imported (Base)**\n` +
1179
+ ctx.onEvent({ kind: 'text_delta', text: `**Wallet Imported (${CHAIN_LABELS[chain]})**\n` +
1179
1180
  ` Address: ${account.address}\n` +
1180
1181
  ` Saved to: ~/.blockrun/wallet.json\n\n` +
1181
1182
  `⚠️ IMPORTANT: This session is still using the OLD wallet.\n` +
@@ -1209,11 +1210,12 @@ export async function handleSlashCommand(input, ctx) {
1209
1210
  }
1210
1211
  else {
1211
1212
  const { getOrCreateWallet, setupAgentWallet } = await import('@blockrun/llm');
1213
+ const { readEvmBalance } = await import('../wallet/manager.js');
1212
1214
  const w = getOrCreateWallet();
1213
1215
  address = w.address;
1214
1216
  try {
1215
1217
  const client = setupAgentWallet({ silent: true });
1216
- const bal = await Promise.race([client.getBalance(), fetchTimeout(5000)]);
1218
+ const bal = await Promise.race([readEvmBalance(chain, client), fetchTimeout(5000)]);
1217
1219
  balance = `$${bal.toFixed(2)} USDC`;
1218
1220
  }
1219
1221
  catch {
@@ -5,7 +5,7 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { execSync } from 'node:child_process';
8
- import { BLOCKRUN_DIR } from '../config.js';
8
+ import { API_URLS, BLOCKRUN_DIR, CHAIN_LABELS, CHAINS } from '../config.js';
9
9
  import { getWalletAddress as getBaseWalletAddress } from '@blockrun/llm';
10
10
  import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
@@ -264,9 +264,9 @@ function getBlockRunApiSection() {
264
264
  const chargedBy = mode.kind === 'key' ? 'account credits' : 'x402 wallet payment';
265
265
  const hosts = mode.kind === 'key'
266
266
  ? `- **Your host: \`https://api.blockrun.ai\`** — the account API. Requests carry your configured key; the built-in tools attach it. It is a SEPARATE service, not an alias of the Base gateway.
267
- - Not yours: \`https://blockrun.ai/api\` (Base x402 wallet) and \`https://sol.blockrun.ai/api\` (Solana x402 wallet). They ignore an account key and answer 402. Never send one there, and never attach a wallet payment proof to an account request.`
268
- : `- **Your host: \`${mode.apiBase}\`** — the ${mode.chain === 'solana' ? 'Solana' : 'Base'} x402 wallet gateway. Paid calls answer 402 and the tools sign from your ${mode.chain === 'solana' ? 'Solana' : 'Base'} wallet.
269
- - Not yours: \`${mode.chain === 'solana' ? 'https://blockrun.ai/api' : 'https://sol.blockrun.ai/api'}\` (the other chain's wallet gateway) and \`https://api.blockrun.ai\` (the account API, which needs a key and 401s without one — it is not an alias of either wallet host).`;
267
+ - Not yours: ${CHAINS.map(c => `\`${API_URLS[c]}\` (${CHAIN_LABELS[c]} x402 wallet)`).join(', ')}. They ignore an account key and answer 402. Never send one there, and never attach a wallet payment proof to an account request.`
268
+ : `- **Your host: \`${mode.apiBase}\`** — the ${CHAIN_LABELS[mode.chain]} x402 wallet gateway. Paid calls answer 402 and the tools sign from your ${CHAIN_LABELS[mode.chain]} wallet.
269
+ - Not yours: ${CHAINS.filter(c => c !== mode.chain).map(c => `\`${API_URLS[c]}\` (the ${CHAIN_LABELS[c]} wallet gateway)`).join(', ')} and \`https://api.blockrun.ai\` (the account API, which needs a key and 401s without one — it is not an alias of any wallet host).`;
270
270
  return `# BlockRun Gateway API (the network you live on)
271
271
  You run on the BlockRun AI Gateway. When the user asks you to "test the BlockRun API", "check all endpoints", or call the gateway directly, use ONLY the paths below. **Never invent, pluralize, or singularize an endpoint** — \`/v1/image/generate\` (singular) is wrong, \`/v1/images/generations\` (plural) is correct. If a path you have in mind isn't in this list, fetch the canonical discovery endpoints before calling it.
272
272
 
@@ -279,7 +279,7 @@ Use the built-in tools so the right host and credential are applied. Never switc
279
279
  - \`GET /.well-known/x402\` — x402 resource list with prices
280
280
 
281
281
  **LLM (POST, billed to ${chargedBy})**
282
- - \`POST /v1/chat/completions\` — OpenAI-compatible. Body: \`{ model, messages, stream?, tools?, max_tokens?, temperature? }\`. \`model\` MUST come from \`GET /v1/models\` (real frontier examples on the gateway, verified live 2026-08-30: \`anthropic/claude-sonnet-5\`, \`anthropic/claude-opus-5\`, \`openai/gpt-5.6-sol\`, \`deepseek/deepseek-v4-pro\`, \`zai/glm-5.3\`, \`zai/glm-5.3-flash\`, \`xai/grok-4.5\`, \`qwen/qwen3.7-flash\`, \`nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\` (free, the only free id on BOTH the Base and Solana gateways — the other free models are Base-only)). Do NOT invent versions like \`openai/gpt-5.1\` or \`xai/grok-5\` — those don't exist; the gateway 400s with the valid list in the error body, so when in doubt fetch \`GET /v1/models\` first.
282
+ - \`POST /v1/chat/completions\` — OpenAI-compatible. Body: \`{ model, messages, stream?, tools?, max_tokens?, temperature? }\`. \`model\` MUST come from \`GET /v1/models\` (real frontier examples on the gateway, verified live 2026-08-30: \`anthropic/claude-sonnet-5\`, \`anthropic/claude-opus-5\`, \`openai/gpt-5.6-sol\`, \`deepseek/deepseek-v4-pro\`, \`zai/glm-5.3\`, \`zai/glm-5.3-flash\`, \`xai/grok-4.5\`, \`qwen/qwen3.7-flash\`, \`nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\` (free, the only free id on BOTH the Base and Solana gateways — the other free models are Base-only)). Do NOT invent versions like \`openai/gpt-7\` or \`xai/grok-5\` — those don't exist; the gateway 400s with the valid list in the error body, so when in doubt fetch \`GET /v1/models\` first.
283
283
  - \`POST /v1/messages\` — Anthropic-compatible. Body: \`{ model, messages, max_tokens, system?, tools? }\`.
284
284
 
285
285
  **Media (POST, billed to ${chargedBy}; GET to poll async jobs)**
@@ -742,7 +742,7 @@ function buildEnvironmentSection(workingDir) {
742
742
  if (wallet.chain)
743
743
  lines.push(`- Active chain: ${wallet.chain}`);
744
744
  if (wallet.base)
745
- lines.push(`- Base wallet address: ${wallet.base} (private key at ~/.blockrun/.session)`);
745
+ lines.push(`- EVM wallet address (Base and Arc): ${wallet.base} (private key at ~/.blockrun/.session)`);
746
746
  if (wallet.solana)
747
747
  lines.push(`- Solana wallet address: ${wallet.solana} (private key at ~/.blockrun/.solana-session)`);
748
748
  }
@@ -158,16 +158,17 @@ async function exaAnswerTry(query, client) {
158
158
  // tool framework because prefetch runs outside the agent loop — no
159
159
  // permission prompt, no streaming.
160
160
  const { loadChain } = await import('../config.js');
161
- const { gatewayBase, gatewayHeaders } = await import('../payments/auth-mode.js');
161
+ const { gatewayBase, gatewayHeaders, walletMayPay } = await import('../payments/auth-mode.js');
162
162
  const chain = loadChain();
163
163
  const apiUrl = gatewayBase();
164
164
  void client; // (future: unify the paid-endpoint client so we reuse wallet caching)
165
+ const requestHeaders = { 'Content-Type': 'application/json', ...gatewayHeaders() };
165
166
  const res = await fetch(`${apiUrl}/v1/exa/answer`, {
166
167
  method: 'POST',
167
- headers: { 'Content-Type': 'application/json', ...gatewayHeaders() },
168
+ headers: requestHeaders,
168
169
  body: JSON.stringify({ query }),
169
170
  });
170
- if (res.status === 402) {
171
+ if (res.status === 402 && walletMayPay(requestHeaders)) {
171
172
  const payHdr = await extractPaymentReq(res);
172
173
  if (!payHdr)
173
174
  return { text: null, costUsd: 0 };
package/dist/agent/llm.js CHANGED
@@ -5,7 +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
+ import { gatewayHeaders, walletMayPay } from '../payments/auth-mode.js';
9
9
  import { appendSettlementRow } from '../stats/cost-log.js';
10
10
  import { routeRequest, parseRoutingProfile } from '../router/index.js';
11
11
  import { ThinkTagStripper } from './think-tag-stripper.js';
@@ -657,10 +657,9 @@ export class ModelClient {
657
657
  body,
658
658
  signal: requestController.signal,
659
659
  }), requestController, createModelTimeoutError('request', request.model, requestTimeoutMs), requestTimeoutMs);
660
- // Handle x402 payment
661
- // Account 402 is a credit refusal. Only a request that started on
662
- // the wallet rail may initiate a signing handshake.
663
- if (response.status === 402 && !headers.Authorization) {
660
+ // Handle x402 payment. An account 402 is a credit refusal, never a
661
+ // challenge the wallet may answer.
662
+ if (response.status === 402 && walletMayPay(headers)) {
664
663
  if (this.debug)
665
664
  console.error('[franklin] Payment required — signing...');
666
665
  const signedPayment = await this.signPayment(response, request.model);
@@ -734,7 +733,8 @@ export class ModelClient {
734
733
  body: retryBody,
735
734
  signal: requestController.signal,
736
735
  }), requestController, createModelTimeoutError('request', request.model, requestTimeoutMs), requestTimeoutMs);
737
- if (response.status === 402) {
736
+ // A retry must preserve the request's original payment rail too.
737
+ if (response.status === 402 && walletMayPay(headers)) {
738
738
  const signedPayment = await this.signPayment(response, request.model);
739
739
  if (!signedPayment) {
740
740
  yield { kind: 'error', payload: { message: 'Payment signing failed' } };
@@ -199,6 +199,11 @@ const MODEL_CONTEXT_WINDOWS = {
199
199
  // a real >200k call has been verified end-to-end.
200
200
  // Fable 5 / Sonnet 5 advertise 1M at the gateway; keep the 200k safe baseline
201
201
  // (same rationale as Opus above) until a real >200k call is verified.
202
+ // Fable 5.1 / Opus 5.5 / Sonnet 5.5 (2026-10) also advertise 1M; same
203
+ // 200k baseline. Without a row the live catalog's 1M would win here.
204
+ 'anthropic/claude-fable-5.1': 200_000,
205
+ 'anthropic/claude-opus-5.5': 200_000,
206
+ 'anthropic/claude-sonnet-5.5': 200_000,
202
207
  'anthropic/claude-fable-5': 200_000,
203
208
  'anthropic/claude-opus-5': 200_000,
204
209
  'anthropic/claude-opus-4.8': 200_000,
@@ -217,6 +222,12 @@ const MODEL_CONTEXT_WINDOWS = {
217
222
  // gpt-5.5 advertises 1.05M context at the gateway, but Franklin keeps the
218
223
  // conservative 128k baseline matching every other gpt-5.x line — bump in
219
224
  // a separate change once a real >128k call has been verified end-to-end.
225
+ // GPT-6 (1.05M advertised; input above 272K bills at 2x) and GPT-5.1 (400K
226
+ // advertised) take the same 128k baseline until verified end-to-end.
227
+ 'openai/gpt-6-astra': 128_000,
228
+ 'openai/gpt-6-sol': 128_000,
229
+ 'openai/gpt-6-luna': 128_000,
230
+ 'openai/gpt-5.1': 128_000,
220
231
  'openai/gpt-5.6-sol': 128_000,
221
232
  'openai/gpt-5.6-terra': 128_000,
222
233
  'openai/gpt-5.6-luna': 128_000,
@@ -256,6 +267,8 @@ const MODEL_CONTEXT_WINDOWS = {
256
267
  // xAI. grok-4.5 / 4.3 / build were missing until 2026-08-20: neither matches
257
268
  // any inference pattern below, so a cold catalog cache fell through to the
258
269
  // blind 128k default and compacted a 500K–1M window ~4-8x too early.
270
+ 'xai/grok-4.7': 500_000,
271
+ 'xai/grok-4.6': 500_000,
259
272
  'xai/grok-4.5': 500_000,
260
273
  'xai/grok-4.3': 1_000_000,
261
274
  'xai/grok-build-0.1': 256_000,
@@ -2,6 +2,7 @@
2
2
  * Core types for the Franklin agent system.
3
3
  * All type names and structures are original designs.
4
4
  */
5
+ import type { Chain } from '../config.js';
5
6
  export type Role = 'user' | 'assistant';
6
7
  export interface TextSegment {
7
8
  type: 'text';
@@ -157,7 +158,7 @@ export type StreamEvent = StreamTextDelta | StreamThinkingDelta | StreamCapabili
157
158
  export interface AgentConfig {
158
159
  model: string;
159
160
  apiUrl: string;
160
- chain: 'base' | 'solana';
161
+ chain: Chain;
161
162
  systemInstructions: string[];
162
163
  capabilities: CapabilityHandler[];
163
164
  maxTurns?: number;
@@ -28,6 +28,7 @@ import { interactiveSession } from '../agent/loop.js';
28
28
  import { ModelClient } from '../agent/llm.js';
29
29
  import { extractBrainEntities } from '../brain/extract.js';
30
30
  import { extractLearnings } from '../learnings/extractor.js';
31
+ import { readEvmBalance } from '../wallet/manager.js';
31
32
  // Slack's hard per-message cap is ~40 KB, but readability tanks long before
32
33
  // that. Keep chunks small so a long answer arrives as a few tidy messages.
33
34
  const CHUNK_MAX = 3500;
@@ -174,10 +175,11 @@ export async function runSlackBot(agentConfig, opts) {
174
175
  await postMessage(target, `Chain: solana\nWallet: ${addr}\nBalance: $${bal.toFixed(2)} USDC`);
175
176
  }
176
177
  else {
178
+ const chain = agentConfig.chain;
177
179
  const c = setupAgentWallet({ silent: true });
178
180
  const addr = c.getWalletAddress();
179
- const bal = await c.getBalance();
180
- await postMessage(target, `Chain: base\nWallet: ${addr}\nBalance: $${bal.toFixed(2)} USDC`);
181
+ const bal = await readEvmBalance(chain, c);
182
+ await postMessage(target, `Chain: ${chain}\nWallet: ${addr}\nBalance: $${bal.toFixed(2)} USDC`);
181
183
  }
182
184
  }
183
185
  catch (err) {
@@ -23,6 +23,7 @@ import { interactiveSession } from '../agent/loop.js';
23
23
  import { ModelClient } from '../agent/llm.js';
24
24
  import { extractBrainEntities } from '../brain/extract.js';
25
25
  import { extractLearnings } from '../learnings/extractor.js';
26
+ import { readEvmBalance } from '../wallet/manager.js';
26
27
  // Per-bot prefs (persisted so a restart keeps the user's choice).
27
28
  const PREFS_FILE = path.join(os.homedir(), '.blockrun', 'telegram-prefs.json');
28
29
  function loadPrefs() {
@@ -201,10 +202,11 @@ export async function runTelegramBot(agentConfig, opts) {
201
202
  await sendMessage(chatId, `Chain: solana\nWallet: ${addr}\nBalance: $${bal.toFixed(2)} USDC`);
202
203
  }
203
204
  else {
205
+ const chain = agentConfig.chain;
204
206
  const c = setupAgentWallet({ silent: true });
205
207
  const addr = c.getWalletAddress();
206
- const bal = await c.getBalance();
207
- await sendMessage(chatId, `Chain: base\nWallet: ${addr}\nBalance: $${bal.toFixed(2)} USDC`);
208
+ const bal = await readEvmBalance(chain, c);
209
+ await sendMessage(chatId, `Chain: ${chain}\nWallet: ${addr}\nBalance: $${bal.toFixed(2)} USDC`);
208
210
  }
209
211
  }
210
212
  catch (err) {
@@ -1,8 +1,9 @@
1
1
  import chalk from 'chalk';
2
2
  import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
3
- import { loadChain, DASHBOARD_URL } from '../config.js';
3
+ import { loadChain, CHAIN_LABELS, DASHBOARD_URL } from '../config.js';
4
4
  import { fetchCreditBalance, isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
5
5
  import { loadStats } from '../stats/tracker.js';
6
+ import { readEvmBalance } from '../wallet/manager.js';
6
7
  export async function balanceCommand() {
7
8
  const chain = loadChain();
8
9
  // API-key mode settles against a prepaid credit balance. The gateway exposes
@@ -74,12 +75,12 @@ export async function balanceCommand() {
74
75
  else {
75
76
  const client = setupAgentWallet({ silent: true });
76
77
  const address = client.getWalletAddress();
77
- const balance = await client.getBalance();
78
- console.log(`Chain: ${chalk.magenta('base')}`);
78
+ const balance = await readEvmBalance(chain, client);
79
+ console.log(`Chain: ${chalk.magenta(chain)}`);
79
80
  console.log(`Wallet: ${chalk.cyan(address)}`);
80
81
  console.log(`USDC Balance: ${chalk.green(`$${balance.toFixed(2)}`)}`);
81
82
  if (balance === 0) {
82
- console.log(chalk.dim(`\nSend USDC on Base to ${address} to get started.`));
83
+ console.log(chalk.dim(`\nSend USDC on ${CHAIN_LABELS[chain]} to ${address} to get started.`));
83
84
  }
84
85
  }
85
86
  }
@@ -19,6 +19,7 @@ import { loadChain, VERSION, BLOCKRUN_DIR, DASHBOARD_URL, KEY_API_URL, USER_AGEN
19
19
  import { gatewayBase, isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
20
20
  import { isTelemetryEnabled, readAllRecords } from '../telemetry/store.js';
21
21
  import { getAvailableUpdateFresh, kickoffVersionCheck } from '../version-check.js';
22
+ import { readEvmBalance } from '../wallet/manager.js';
22
23
  /** Free, auth-gated probe — proves the key works without spending credit. */
23
24
  async function verifyKeyReachable() {
24
25
  const key = loadApiKey();
@@ -106,7 +107,7 @@ async function runChecks() {
106
107
  name: 'Chain',
107
108
  status: 'fail',
108
109
  detail: `failed to load — ${err.message}`,
109
- remedy: 'Run: franklin setup base (or: franklin setup solana)',
110
+ remedy: 'Run: franklin setup solana (or: franklin setup base / franklin setup arc)',
110
111
  });
111
112
  }
112
113
  // ── 5. Wallet ─────────────────────────────────────────────────────
@@ -147,7 +148,7 @@ async function runChecks() {
147
148
  else {
148
149
  const client = setupAgentWallet({ silent: true });
149
150
  walletAddress = client.getWalletAddress();
150
- walletBalance = await client.getBalance();
151
+ walletBalance = await readEvmBalance(chain, client);
151
152
  }
152
153
  out.push({
153
154
  name: 'Wallet',
@@ -1,7 +1,7 @@
1
1
  import chalk from 'chalk';
2
2
  import { loadChain } from '../config.js';
3
3
  import { gatewayBase } from '../payments/auth-mode.js';
4
- import { getGatewayModels, GATEWAY_MARGIN, } from '../gateway-models.js';
4
+ import { getGatewayModels, GATEWAY_MARGIN, GATEWAY_TRANSACTION_FEE_USD, } from '../gateway-models.js';
5
5
  /**
6
6
  * `franklin models` — the live catalog.
7
7
  *
@@ -172,6 +172,7 @@ export async function modelsCommand() {
172
172
  const unknown = models.filter(m => !known.has(m.billing_mode));
173
173
  printSection('Other billing modes (not yet modelled by this Franklin build)', unknown, m => chalk.dim(`${m.billing_mode}: ${JSON.stringify(m.pricing)}`));
174
174
  const margin = Math.round((GATEWAY_MARGIN - 1) * 100);
175
- console.log(chalk.dim(`${models.length} models available. Prices are gateway list — x402 settlement adds ~${margin}%.`));
175
+ console.log(chalk.dim(`${models.length} models available. Prices are gateway list — chat adds only the ` +
176
+ `$${GATEWAY_TRANSACTION_FEE_USD} per-call fee; media adds ${margin}% + $${GATEWAY_TRANSACTION_FEE_USD}.`));
176
177
  console.log(`${chalk.dim('Use:')} ${chalk.bold('franklin start --model <model-id>')}`);
177
178
  }
@@ -5,7 +5,7 @@
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, DEFAULT_PROXY_PORT } from '../config.js';
8
+ import { loadChain, CHAIN_LABELS, DEFAULT_PROXY_PORT } from '../config.js';
9
9
  import { gatewayBase } from '../payments/auth-mode.js';
10
10
  import { loadConfig } from './config.js';
11
11
  import { printBanner } from '../banner.js';
@@ -53,12 +53,12 @@ export async function proxyCommand(options) {
53
53
  if (wallet.isNew) {
54
54
  console.log(chalk.yellow('No wallet found — created a new one.'));
55
55
  console.log(`Address: ${chalk.cyan(wallet.address)}`);
56
- console.log(`\nSend USDC on Base to this address, then run ${chalk.bold('franklin proxy')} again.\n`);
56
+ console.log(`\nSend USDC on ${CHAIN_LABELS[chain]} to this address, then run ${chalk.bold('franklin proxy')} again.\n`);
57
57
  return;
58
58
  }
59
59
  printBanner(version);
60
60
  console.log(`Mode: ${chalk.bold('proxy')}`);
61
- console.log(`Chain: ${chalk.magenta('base')}`);
61
+ console.log(`Chain: ${chalk.magenta(chain)}`);
62
62
  console.log(`Wallet: ${chalk.cyan(wallet.address)}`);
63
63
  if (model)
64
64
  console.log(`Model: ${chalk.green(model)}`);
@@ -68,7 +68,7 @@ export async function proxyCommand(options) {
68
68
  const server = createProxy({
69
69
  port,
70
70
  apiUrl,
71
- chain: 'base',
71
+ chain,
72
72
  modelOverride: model,
73
73
  debug: options.debug,
74
74
  fallbackEnabled,
@@ -1,10 +1,11 @@
1
1
  import chalk from 'chalk';
2
2
  import { getOrCreateWallet, scanWallets, getOrCreateSolanaWallet, scanSolanaWallets, } from '@blockrun/llm';
3
- import { saveChain, DASHBOARD_URL } from '../config.js';
3
+ import { CHAIN_LABELS, saveChain, DASHBOARD_URL } from '../config.js';
4
4
  import { isKeyMode, loadApiKey, maskApiKey } from '../payments/auth-mode.js';
5
5
  export async function setupCommand(chainArg) {
6
- // Solana is the default chain; `franklin setup base` opts into Base.
7
- const chain = chainArg === 'base' ? 'base' : 'solana';
6
+ // Solana is the default chain; `franklin setup base` / `franklin setup arc`
7
+ // opt into an EVM chain. Base and Arc share one EVM wallet.
8
+ const chain = chainArg === 'base' || chainArg === 'arc' ? chainArg : 'solana';
8
9
  // A configured key already pays for everything, so creating a wallet here
9
10
  // would be busywork the user did not ask for. Say so and stop, rather than
10
11
  // silently making a second credential they will never fund.
@@ -45,7 +46,7 @@ export async function setupCommand(chainArg) {
45
46
  console.log(chalk.dim(' franklin start — start coding'));
46
47
  console.log(chalk.dim(' franklin balance — check USDC balance'));
47
48
  console.log(chalk.dim(' franklin start -m free — use free models (no USDC needed)'));
48
- saveChain('base');
49
+ saveChain(chain);
49
50
  return;
50
51
  }
51
52
  console.log('Creating new wallet...\n');
@@ -54,7 +55,7 @@ export async function setupCommand(chainArg) {
54
55
  console.log(chalk.green('Wallet created!\n'));
55
56
  }
56
57
  console.log(`Address: ${chalk.cyan(address)}`);
57
- console.log(`\nSend USDC on Base to this address to fund your account.`);
58
+ console.log(`\nSend USDC on ${CHAIN_LABELS[chain]} to this address to fund your account.`);
58
59
  }
59
60
  saveChain(chain);
60
61
  console.log(`Then run ${chalk.bold('franklin start')} to begin.\n`);
@@ -19,6 +19,7 @@ import { pickModel, resolveModel, resolveModelStrict } from '../ui/model-picker.
19
19
  import { loadMcpConfig } from '../mcp/config.js';
20
20
  import { connectMcpServers, disconnectMcpServers, getMcpServerInstructions } from '../mcp/client.js';
21
21
  import { ensureCodegraphIndex } from '../mcp/codegraph.js';
22
+ import { readEvmBalance } from '../wallet/manager.js';
22
23
  export async function startCommand(options) {
23
24
  const version = options.version ?? '1.0.0';
24
25
  // Early-validate explicit resume ID so a typo fails fast — before wallet
@@ -249,15 +250,16 @@ export async function startCommand(options) {
249
250
  // zero result; genuinely empty wallets still resolve to $0.00 quickly.
250
251
  const fetchBalance = async () => {
251
252
  try {
253
+ const payChain = chain;
252
254
  const bal = await retryFetchBalance(async () => {
253
- if (chain === 'solana') {
255
+ if (payChain === 'solana') {
254
256
  const { setupAgentSolanaWallet } = await import('@blockrun/llm');
255
257
  const client = await setupAgentSolanaWallet({ silent: true });
256
258
  return client.getBalance();
257
259
  }
258
260
  const { setupAgentWallet } = await import('@blockrun/llm');
259
261
  const client = setupAgentWallet({ silent: true });
260
- return client.getBalance();
262
+ return readEvmBalance(payChain, client);
261
263
  });
262
264
  return `$${bal.toFixed(2)} USDC`;
263
265
  }
package/dist/config.d.ts CHANGED
@@ -1,6 +1,18 @@
1
1
  export declare const VERSION: string;
2
2
  export declare const USER_AGENT: string;
3
- export type Chain = 'base' | 'solana';
3
+ export type Chain = 'base' | 'solana' | 'arc';
4
+ /**
5
+ * Every chain Franklin can pay on. Base and Arc are both EVM and share one
6
+ * wallet key (~/.blockrun/.session): the same address holds USDC on each, and
7
+ * the 402's `network` selects which chain's USDC domain gets signed. Solana has
8
+ * its own key.
9
+ */
10
+ export declare const CHAINS: readonly Chain[];
11
+ export declare function isChain(value: unknown): value is Chain;
12
+ /** True for the chains paid from the EVM wallet (Base, Arc). */
13
+ export declare function isEvmChain(chain: Chain): boolean;
14
+ /** Display name, for copy that names the chain a payment settles on. */
15
+ export declare const CHAIN_LABELS: Record<Chain, string>;
4
16
  export declare const BLOCKRUN_DIR: string;
5
17
  export declare const CHAIN_FILE: string;
6
18
  export declare const API_URLS: Record<Chain, string>;
package/dist/config.js CHANGED
@@ -12,11 +12,35 @@ catch { /* use default */ }
12
12
  export const VERSION = _version;
13
13
  // Shared User-Agent string for all outbound HTTP requests
14
14
  export const USER_AGENT = `franklin/${_version} (node/${process.versions.node}; ${process.platform}; ${process.arch})`;
15
+ /**
16
+ * Every chain Franklin can pay on. Base and Arc are both EVM and share one
17
+ * wallet key (~/.blockrun/.session): the same address holds USDC on each, and
18
+ * the 402's `network` selects which chain's USDC domain gets signed. Solana has
19
+ * its own key.
20
+ */
21
+ export const CHAINS = ['base', 'solana', 'arc'];
22
+ export function isChain(value) {
23
+ return typeof value === 'string' && CHAINS.includes(value);
24
+ }
25
+ /** True for the chains paid from the EVM wallet (Base, Arc). */
26
+ export function isEvmChain(chain) {
27
+ return chain !== 'solana';
28
+ }
29
+ /** Display name, for copy that names the chain a payment settles on. */
30
+ export const CHAIN_LABELS = {
31
+ base: 'Base',
32
+ solana: 'Solana',
33
+ arc: 'Arc',
34
+ };
15
35
  export const BLOCKRUN_DIR = path.join(os.homedir(), '.blockrun');
16
36
  export const CHAIN_FILE = path.join(BLOCKRUN_DIR, 'payment-chain');
17
37
  export const API_URLS = {
18
38
  base: 'https://blockrun.ai/api',
19
39
  solana: 'https://sol.blockrun.ai/api',
40
+ // Circle's Arc (eip155:5042): the same gateway API as Base, settled through
41
+ // the Circle facilitator. Needs @blockrun/llm >= 3.16, which signs the 402's
42
+ // network rather than Base's USDC domain.
43
+ arc: 'https://arc.blockrun.ai/api',
20
44
  };
21
45
  export const DEFAULT_PROXY_PORT = 8402;
22
46
  // BlockRun agent-market (the paid skill marketplace Franklin browses with
@@ -31,16 +55,12 @@ export function saveChain(chain) {
31
55
  }
32
56
  export function loadChain() {
33
57
  const envChain = process.env.RUNCODE_CHAIN;
34
- if (envChain === 'solana')
35
- return 'solana';
36
- if (envChain === 'base')
37
- return 'base';
58
+ if (isChain(envChain))
59
+ return envChain;
38
60
  try {
39
61
  const content = fs.readFileSync(CHAIN_FILE, 'utf-8').trim();
40
- if (content === 'base')
41
- return 'base';
42
- if (content === 'solana')
43
- return 'solana';
62
+ if (isChain(content))
63
+ return content;
44
64
  }
45
65
  catch { /* no explicit choice on disk — fall through to the default */ }
46
66
  // Default chain is Solana. Exception: a Base wallet with no Solana wallet
@@ -9,8 +9,10 @@
9
9
  *
10
10
  * Per gateway team (2026-04-22): every model returns `billing_mode` and
11
11
  * a mode-specific `pricing` object. Dispatch on billing_mode to compute
12
- * an estimated charge. x402 adds a fixed 5% margin on top of base price,
13
- * plus a flat $0.001 per-transaction fee on paid calls (Base since
12
+ * an estimated charge. Token-metered chat is billed at the provider's list
13
+ * rate with no margin (since 2026-09-04); media (image/video/music/speech/
14
+ * sfx) and Live Search carry a 5% platform fee. Every paid call adds a flat
15
+ * $0.001 per-transaction fee (Base since
14
16
  * 2026-07-10; Solana instead enforces a $0.001 minimum per call with no
15
17
  * service fee — the flat-fee estimate over-counts there by ≤$0.001, which
16
18
  * is the safe direction for budget tracking).
@@ -100,11 +102,15 @@ export declare function getGatewayModels(): Promise<GatewayModel[]>;
100
102
  export declare function getModelsByCategory(category: string): Promise<GatewayModel[]>;
101
103
  /** Find a single model by ID, or null if it's not in the current catalog. */
102
104
  export declare function findModel(id: string): Promise<GatewayModel | null>;
103
- /** x402 gateway's fixed margin percentage applied on top of the base price. */
105
+ /**
106
+ * Platform fee multiplier on MEDIA (per_image / per_second / per_track /
107
+ * per_character / per_generation / flat) list prices. Token-metered chat
108
+ * carries no margin — the gateway bills it at the provider's list rate.
109
+ */
104
110
  export declare const GATEWAY_MARGIN = 1.05;
105
111
  /**
106
112
  * Flat per-transaction fee (USD) the gateway adds on top of the margined
107
- * price on every PAID call (no-op on $0 calls). Introduced upstream
113
+ * (media) or list (chat) price on every PAID call (no-op on $0 calls). Introduced upstream
108
114
  * 2026-07-10, briefly $0.002, back to $0.001 since 2026-07-29
109
115
  * (blockrun src/lib/transaction-fee.ts).
110
116
  */
@@ -119,7 +125,7 @@ export interface EstimateContext {
119
125
  }
120
126
  /**
121
127
  * Estimated USD charge to generate one response from this model under the
122
- * given context. Includes the 5% gateway margin and the flat $0.001
128
+ * given context. Includes the 5% media platform fee and the flat $0.001
123
129
  * per-transaction fee on paid calls. Returns 0 for free and token-metered
124
130
  * (paid) models where a pre-call estimate isn't meaningful.
125
131
  */