@blockrun/franklin 3.44.0 → 3.46.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 (54) hide show
  1. package/README.md +36 -24
  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/balance.js +37 -5
  11. package/dist/commands/doctor.js +18 -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/index.js +16 -0
  17. package/dist/payments/account.d.ts +17 -0
  18. package/dist/payments/account.js +105 -0
  19. package/dist/payments/auth-mode.d.ts +39 -19
  20. package/dist/payments/auth-mode.js +54 -17
  21. package/dist/payments/billing-copy.d.ts +37 -0
  22. package/dist/payments/billing-copy.js +57 -0
  23. package/dist/payments/post-with-payment.js +8 -15
  24. package/dist/payments/price-catalog.d.ts +70 -0
  25. package/dist/payments/price-catalog.js +154 -6
  26. package/dist/payments/usage.d.ts +106 -0
  27. package/dist/payments/usage.js +168 -0
  28. package/dist/stats/tracker.d.ts +9 -1
  29. package/dist/stats/tracker.js +6 -1
  30. package/dist/tools/bash.js +17 -7
  31. package/dist/tools/blockrun.js +1 -1
  32. package/dist/tools/defillama.d.ts +5 -5
  33. package/dist/tools/defillama.js +13 -13
  34. package/dist/tools/exa.d.ts +1 -1
  35. package/dist/tools/exa.js +27 -18
  36. package/dist/tools/imagegen.js +5 -4
  37. package/dist/tools/modal.js +12 -6
  38. package/dist/tools/musicgen.js +4 -3
  39. package/dist/tools/phone.js +16 -15
  40. package/dist/tools/prediction.js +13 -11
  41. package/dist/tools/realface.js +3 -3
  42. package/dist/tools/rpc.d.ts +1 -1
  43. package/dist/tools/rpc.js +5 -5
  44. package/dist/tools/sensitive-paths.d.ts +1 -1
  45. package/dist/tools/sensitive-paths.js +13 -4
  46. package/dist/tools/surf.js +33 -5
  47. package/dist/tools/videogen.js +6 -5
  48. package/dist/tools/voice.d.ts +1 -1
  49. package/dist/tools/voice.js +5 -4
  50. package/dist/wallet/reservation.d.ts +24 -0
  51. package/dist/wallet/reservation.js +50 -4
  52. package/dist/wallet/solana-migration.d.ts +48 -0
  53. package/dist/wallet/solana-migration.js +81 -0
  54. package/package.json +2 -2
@@ -13,7 +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
+ import { gatewayHeaders, resolvePayMode, } from './auth-mode.js';
17
17
  async function extractPaymentReq(response) {
18
18
  let header = response.headers.get('payment-required');
19
19
  if (!header) {
@@ -83,21 +83,14 @@ export async function postWithPayment(endpoint, body, resourceDescription, timeo
83
83
  body: payload,
84
84
  });
85
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 };
86
+ // An account failure is never permission to spend from a wallet.
87
+ // The user can explicitly select --wallet and retry the command.
88
+ let parsedKey = {};
89
+ try {
90
+ parsedKey = keyRaw ? JSON.parse(keyRaw) : {};
97
91
  }
98
- if (failure === 'invalid-key')
99
- invalidateKey();
100
- endpoint = toWalletUrl(endpoint, chain);
92
+ catch { /* leave as {} */ }
93
+ return { ok: keyResponse.ok, status: keyResponse.status, body: parsedKey, raw: keyRaw, settled: false };
101
94
  }
102
95
  const headers = {
103
96
  'Content-Type': 'application/json',
@@ -50,6 +50,74 @@ export declare function __primePriceCatalog(entries: CatalogEntry[]): void;
50
50
  * catalog refreshes in the background via `warmPriceCatalog()`.
51
51
  */
52
52
  export declare function priceForPath(apiPath: string): number | null;
53
+ /**
54
+ * The base price for an endpoint — what the API-key rail charges — or null
55
+ * when the endpoint is not catalogued.
56
+ *
57
+ * There are two real prices per endpoint and one literal cannot serve both.
58
+ * The catalog and the 402 challenge both state the WALLET price, which is the
59
+ * base plus a settlement fee. The key rail charges the base and no fee, which
60
+ * is why it issues no 402 at all.
61
+ *
62
+ * Measured 2026-09-05 via x-blockrun-cost-usd against the unsigned 402:
63
+ *
64
+ * endpoint 402 / catalog key rail charges
65
+ * surf $0.0085 $0.0075
66
+ * rpc $0.0030 $0.0020
67
+ * exa search $0.0110 $0.0100
68
+ * defillama $0.0060 $0.0050
69
+ *
70
+ * Exactly one fee apart, every time. Quoting the 402 figure to a key-mode user
71
+ * overstates every call by $0.001 — small in absolute terms and 50% on a
72
+ * $0.002 RPC call.
73
+ */
74
+ export declare function basePriceForPath(apiPath: string): number | null;
75
+ /**
76
+ * The exact amount BlockRun charged for this call, from
77
+ * `x-blockrun-cost-usd`, or null when the response does not state one.
78
+ *
79
+ * Live on the pre-priced service families (exa, surf, pm, phone, modal,
80
+ * speech, images, rpc, defillama). Deliberately and permanently ABSENT on
81
+ * chat, which settles after the answer is on the wire (`x-settlement-async`)
82
+ * — at header-writing time the amount does not exist yet, and waiting for it
83
+ * would mean holding the customer's response until the money lands. Chat is
84
+ * reconstructed from tokens x published rate instead.
85
+ *
86
+ * Absent means "no charge settled at response time", NOT "free" — reading it
87
+ * as $0 would zero out chat, the largest spend category. A charge that really
88
+ * did settle at zero is written explicitly as `0.000000`, so 0 is a value and
89
+ * missing is not.
90
+ *
91
+ * Empty, malformed and negative are all treated as absent. `Number('')` is 0
92
+ * in JS, which would book $0 against a billed call.
93
+ */
94
+ export declare function chargeFromResponse(res: HeaderBag): number | null;
95
+ /**
96
+ * The gateway's id for this request, from `x-blockrun-request-id`.
97
+ *
98
+ * Recorded locally so `franklin usage` can join Franklin's journal to the
99
+ * account ledger row by row. Comparing totals is not the same check: two
100
+ * errors of opposite sign produce a total that matches and a ledger that is
101
+ * wrong in two places.
102
+ */
103
+ export declare function requestIdFromResponse(res: HeaderBag): string | null;
104
+ /**
105
+ * Credit left on the account after this call, from
106
+ * `x-blockrun-credit-remaining-usd`. Absent on ungated accounts, which have no
107
+ * ceiling and so nothing to report — that is correct, not a failure.
108
+ *
109
+ * It can understate and never overstates: the figure is read inside the
110
+ * reservation transaction, already net of concurrent in-flight holds. That is
111
+ * the right error direction for a pre-run low-balance warning (warn early
112
+ * rather than fail to warn), and the wrong one for display — GET /v1/credits
113
+ * is the authority for a number shown to a user.
114
+ */
115
+ export declare function remainingCreditFromResponse(res: HeaderBag): number | null;
116
+ interface HeaderBag {
117
+ headers: {
118
+ get(name: string): string | null;
119
+ };
120
+ }
53
121
  /**
54
122
  * The amount to record for a completed paid call.
55
123
  *
@@ -64,6 +132,8 @@ export interface ResolvedCharge {
64
132
  }
65
133
  export declare function resolveCharge(opts: {
66
134
  apiPath: string;
135
+ /** From `x-blockrun-cost-usd` — what BlockRun actually charged. Wins outright. */
136
+ chargedUsd?: number | null;
67
137
  settledUsd?: number;
68
138
  reportedUsd?: number;
69
139
  fallbackUsd?: number;
@@ -24,10 +24,43 @@
24
24
  import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import { BLOCKRUN_DIR, USER_AGENT } from '../config.js';
27
+ import { logger } from '../logger.js';
28
+ import { GATEWAY_TRANSACTION_FEE_USD } from '../gateway-models.js';
27
29
  /**
28
- * The discovery doc is public, unauthenticated, and identical across the
29
- * payment hosts, so it is always read from the Base origin — including in key
30
- * mode, where `api.blockrun.ai` does not serve it.
30
+ * Always the Base origin — because it is the only host serving the SHAPE this
31
+ * module parses, not because it is the only one that publishes prices.
32
+ *
33
+ * Measured 2026-09-05:
34
+ * blockrun.ai/.well-known/x402 68KB, `services[]` with per-endpoint prices
35
+ * sol.blockrun.ai/.well-known/x402 4KB, x402scan v1 fallback shape:
36
+ * {version: 1, resources: [114 strings]},
37
+ * no `services`, no prices
38
+ * sol.blockrun.ai/openapi.json 34 paths priced under `x-payment-info`
39
+ * api.blockrun.ai/.well-known/x402 404
40
+ *
41
+ * So sol does publish prices, just in a different document and schema that
42
+ * parsePricing does not read. Do not "fix" this to fetch /.well-known per host:
43
+ * fetchCatalog bails on a missing `services[]`, so the sol origin would freeze
44
+ * every price at the static floor below with nothing reporting it.
45
+ *
46
+ * Do not switch to sol's openapi prices either, which is the tempting move once
47
+ * you know they exist. They currently disagree with what sol itself quotes and
48
+ * settles. For /v1/surf/market/fear-greed on 2026-09-05:
49
+ *
50
+ * sol openapi.json publishes $0.001
51
+ * sol 402 quotes and settles $0.0075 (measured against a funded wallet)
52
+ * this Base card publishes $0.0085
53
+ *
54
+ * The payment layer charges one flat rate across Surf while sol's sheet still
55
+ * lists three tiers, so nine Surf endpoints publish 7.5x under what they
56
+ * charge. Until that is reconciled the Base card is the closer predictor of a
57
+ * real sol Surf charge, which is the opposite of what you would assume.
58
+ *
59
+ * The remaining Base-vs-Solana gap is the service fee: Solana charges none
60
+ * (SERVICE_FEE_USD = 0 in the sol gateway), so a settled Solana call runs
61
+ * $0.001 under this card. None of this touches the amount recorded for a
62
+ * settled wallet call, which uses the exact 402 figure and never reaches this
63
+ * module — it only bounds how precise a catalog-priced estimate can be.
31
64
  */
32
65
  const CATALOG_URL = 'https://blockrun.ai/.well-known/x402';
33
66
  const CACHE_FILE = path.join(BLOCKRUN_DIR, 'price-catalog.json');
@@ -208,8 +241,16 @@ async function fetchCatalog() {
208
241
  if (!res.ok)
209
242
  return;
210
243
  const body = (await res.json());
211
- if (!Array.isArray(body.services))
244
+ if (!Array.isArray(body.services)) {
245
+ // The one failure that would otherwise be invisible: a 200 with no
246
+ // priced catalog leaves every estimate pinned to the static floor
247
+ // forever, and nothing else in the product would ever say so. The sol
248
+ // origin's discovery doc has exactly this shape, so this fires the
249
+ // moment someone repoints CATALOG_URL at it.
250
+ logger.warn(`[franklin] price catalog at ${CATALOG_URL} returned no services[] — ` +
251
+ 'estimates will stay on the built-in floor');
212
252
  return;
253
+ }
213
254
  const entries = [];
214
255
  for (const svc of body.services) {
215
256
  if (!svc || typeof svc !== 'object')
@@ -304,13 +345,120 @@ export function priceForPath(apiPath) {
304
345
  }
305
346
  return best ? best.usd : null;
306
347
  }
348
+ /**
349
+ * The base price for an endpoint — what the API-key rail charges — or null
350
+ * when the endpoint is not catalogued.
351
+ *
352
+ * There are two real prices per endpoint and one literal cannot serve both.
353
+ * The catalog and the 402 challenge both state the WALLET price, which is the
354
+ * base plus a settlement fee. The key rail charges the base and no fee, which
355
+ * is why it issues no 402 at all.
356
+ *
357
+ * Measured 2026-09-05 via x-blockrun-cost-usd against the unsigned 402:
358
+ *
359
+ * endpoint 402 / catalog key rail charges
360
+ * surf $0.0085 $0.0075
361
+ * rpc $0.0030 $0.0020
362
+ * exa search $0.0110 $0.0100
363
+ * defillama $0.0060 $0.0050
364
+ *
365
+ * Exactly one fee apart, every time. Quoting the 402 figure to a key-mode user
366
+ * overstates every call by $0.001 — small in absolute terms and 50% on a
367
+ * $0.002 RPC call.
368
+ */
369
+ export function basePriceForPath(apiPath) {
370
+ const wallet = priceForPath(apiPath);
371
+ if (wallet === null)
372
+ return null;
373
+ if (wallet <= 0)
374
+ return wallet; // free stays free on both rails
375
+ const base = wallet - GATEWAY_TRANSACTION_FEE_USD;
376
+ return base > 0 ? +base.toFixed(6) : wallet;
377
+ }
378
+ /**
379
+ * The exact amount BlockRun charged for this call, from
380
+ * `x-blockrun-cost-usd`, or null when the response does not state one.
381
+ *
382
+ * Live on the pre-priced service families (exa, surf, pm, phone, modal,
383
+ * speech, images, rpc, defillama). Deliberately and permanently ABSENT on
384
+ * chat, which settles after the answer is on the wire (`x-settlement-async`)
385
+ * — at header-writing time the amount does not exist yet, and waiting for it
386
+ * would mean holding the customer's response until the money lands. Chat is
387
+ * reconstructed from tokens x published rate instead.
388
+ *
389
+ * Absent means "no charge settled at response time", NOT "free" — reading it
390
+ * as $0 would zero out chat, the largest spend category. A charge that really
391
+ * did settle at zero is written explicitly as `0.000000`, so 0 is a value and
392
+ * missing is not.
393
+ *
394
+ * Empty, malformed and negative are all treated as absent. `Number('')` is 0
395
+ * in JS, which would book $0 against a billed call.
396
+ */
397
+ export function chargeFromResponse(res) {
398
+ return usdHeader(res, 'x-blockrun-cost-usd');
399
+ }
400
+ /**
401
+ * The gateway's id for this request, from `x-blockrun-request-id`.
402
+ *
403
+ * Recorded locally so `franklin usage` can join Franklin's journal to the
404
+ * account ledger row by row. Comparing totals is not the same check: two
405
+ * errors of opposite sign produce a total that matches and a ledger that is
406
+ * wrong in two places.
407
+ */
408
+ export function requestIdFromResponse(res) {
409
+ const raw = res.headers?.get?.('x-blockrun-request-id');
410
+ const id = typeof raw === 'string' ? raw.trim() : '';
411
+ return id.length > 0 && id.length <= 128 ? id : null;
412
+ }
413
+ /**
414
+ * Credit left on the account after this call, from
415
+ * `x-blockrun-credit-remaining-usd`. Absent on ungated accounts, which have no
416
+ * ceiling and so nothing to report — that is correct, not a failure.
417
+ *
418
+ * It can understate and never overstates: the figure is read inside the
419
+ * reservation transaction, already net of concurrent in-flight holds. That is
420
+ * the right error direction for a pre-run low-balance warning (warn early
421
+ * rather than fail to warn), and the wrong one for display — GET /v1/credits
422
+ * is the authority for a number shown to a user.
423
+ */
424
+ export function remainingCreditFromResponse(res) {
425
+ return usdHeader(res, 'x-blockrun-credit-remaining-usd');
426
+ }
427
+ /**
428
+ * Shared parse for both money headers. 0 is a value; empty, malformed and
429
+ * negative are all absence. `Number('')` is 0 in JS, which would book $0
430
+ * against a billed call.
431
+ */
432
+ function usdHeader(res, name) {
433
+ const raw = res.headers.get(name);
434
+ if (raw === null)
435
+ return null;
436
+ const trimmed = raw.trim();
437
+ if (trimmed === '')
438
+ return null;
439
+ const n = Number(trimmed);
440
+ if (!Number.isFinite(n) || n < 0)
441
+ return null;
442
+ return n;
443
+ }
307
444
  export function resolveCharge(opts) {
308
- const { apiPath, settledUsd, reportedUsd, fallbackUsd } = opts;
445
+ const { apiPath, chargedUsd, settledUsd, reportedUsd, fallbackUsd } = opts;
446
+ // The gateway stating its own charge beats every other source, including a
447
+ // settled x402 amount. 0 is a real answer here, so test for null, not truth.
448
+ if (typeof chargedUsd === 'number') {
449
+ return { usd: chargedUsd, estimated: false };
450
+ }
309
451
  if (typeof settledUsd === 'number' && settledUsd > 0) {
310
452
  return { usd: settledUsd, estimated: false };
311
453
  }
454
+ // An upstream provider's self-reported cost is NOT what BlockRun charged.
455
+ // Measured 2026-09-05: Exa reported costDollars $0.007 on a call BlockRun
456
+ // charged $0.010 for. Treating it as exact booked a wrong number with false
457
+ // confidence, which is worse than a hedged one — so it now ranks below the
458
+ // catalog price and is tagged estimated like any other guess.
312
459
  if (typeof reportedUsd === 'number' && reportedUsd > 0) {
313
- return { usd: reportedUsd, estimated: false };
460
+ const listed = priceForPath(apiPath);
461
+ return { usd: listed !== null && listed > 0 ? listed : reportedUsd, estimated: true };
314
462
  }
315
463
  const listed = priceForPath(apiPath);
316
464
  if (listed !== null)
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The gateway's own per-request ledger, and how Franklin reconciles to it.
3
+ *
4
+ * Franklin's local numbers in key mode are catalog estimates: the account
5
+ * gateway settles against a prepaid balance and returns no charge on the
6
+ * response, so `franklin stats` reports what a call SHOULD have cost. This
7
+ * module fetches what it DID cost.
8
+ *
9
+ * `GET /v1/usage` returns one row per request with a `request_id` that matches
10
+ * the `x-blockrun-request-id` header the gateway already sends, so the join is
11
+ * line-by-line rather than a comparison of two totals — a total that matches
12
+ * can still be two errors cancelling out.
13
+ *
14
+ * Four properties of this feed change how it must be read, and getting any of
15
+ * them wrong produces a confident wrong answer:
16
+ *
17
+ * `cost_state: 'pending'` means the usage exists and its charge does not yet.
18
+ * Those rows can still be repriced. Summing them as zero understates spend
19
+ * and, worse, looks settled.
20
+ *
21
+ * Zero-cost rows are INCLUDED on purpose. "You were not charged for this" is
22
+ * an answer; a row that is simply absent is indistinguishable from one the
23
+ * client dropped. Never filter them.
24
+ *
25
+ * `unavailable_days` names days the gateway could not list rather than
26
+ * silently returning a short page. Swallowing it makes two correct ledgers
27
+ * look like they disagree.
28
+ *
29
+ * `kind` says whether a row is checkable locally at all. A `chat` charge can
30
+ * be rebuilt from tokens and a published rate; a `service` charge is a
31
+ * per-call figure only the gateway holds, so a local estimate for one is a
32
+ * guess by construction and a mismatch is not evidence of a bug.
33
+ *
34
+ * The cursor is opaque. Do not parse it, and do not construct one.
35
+ */
36
+ export type CostState = 'priced' | 'pending' | 'free';
37
+ export type UsageKind = 'chat' | 'service';
38
+ export interface UsageRow {
39
+ requestId: string;
40
+ timestamp: string;
41
+ endpoint: string;
42
+ model: string | null;
43
+ kind: UsageKind;
44
+ inputTokens: number;
45
+ outputTokens: number;
46
+ costUsd: number;
47
+ costState: CostState;
48
+ status: number;
49
+ }
50
+ export interface UsagePage {
51
+ rows: UsageRow[];
52
+ /** Days the gateway could not list. Surface these; never treat as empty. */
53
+ unavailableDays: string[];
54
+ }
55
+ /**
56
+ * Fetch usage rows, following the cursor. Returns null when there is no key or
57
+ * the gateway is unreachable — callers show what they do know rather than
58
+ * inventing a ledger.
59
+ */
60
+ export declare function fetchUsage(opts?: {
61
+ from?: string;
62
+ to?: string;
63
+ limit?: number;
64
+ timeoutMs?: number;
65
+ }): Promise<UsagePage | null>;
66
+ export interface UsageTotals {
67
+ /** Rows whose charge has settled. This is the number you can trust. */
68
+ pricedUsd: number;
69
+ pricedCount: number;
70
+ /** Usage that exists with no charge yet. Not a zero — it can still be priced. */
71
+ pendingCount: number;
72
+ /** Explicitly not chargeable. Counted, never hidden. */
73
+ freeCount: number;
74
+ chatCount: number;
75
+ serviceCount: number;
76
+ }
77
+ export declare function summarize(rows: readonly UsageRow[]): UsageTotals;
78
+ export interface Reconciliation {
79
+ /** Ledger rows Franklin also has locally, and whether the numbers agree. */
80
+ matched: Array<{
81
+ row: UsageRow;
82
+ localUsd: number;
83
+ deltaUsd: number;
84
+ }>;
85
+ /** Charged by the gateway with no local row. Franklin under-counted. */
86
+ missingLocally: UsageRow[];
87
+ /** Rows Franklin recorded that carry no id to join on. */
88
+ unjoinable: number;
89
+ totals: UsageTotals;
90
+ unavailableDays: string[];
91
+ }
92
+ /**
93
+ * Join the gateway ledger to Franklin's own journal on `request_id`.
94
+ *
95
+ * Only `priced` rows are compared. A `pending` row has no charge to disagree
96
+ * with yet, and a `free` row's zero is an answer rather than a discrepancy.
97
+ *
98
+ * `unjoinable` counts local rows with no id — wallet-mode calls, free-path
99
+ * calls, and anything recorded before the id was captured. They are reported
100
+ * rather than hidden, because "0 mismatches" from a journal that could not be
101
+ * joined is not the same statement as "0 mismatches".
102
+ */
103
+ export declare function reconcile(ledger: UsagePage, local: ReadonlyArray<{
104
+ requestId?: string;
105
+ costUsd: number;
106
+ }>): Reconciliation;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The gateway's own per-request ledger, and how Franklin reconciles to it.
3
+ *
4
+ * Franklin's local numbers in key mode are catalog estimates: the account
5
+ * gateway settles against a prepaid balance and returns no charge on the
6
+ * response, so `franklin stats` reports what a call SHOULD have cost. This
7
+ * module fetches what it DID cost.
8
+ *
9
+ * `GET /v1/usage` returns one row per request with a `request_id` that matches
10
+ * the `x-blockrun-request-id` header the gateway already sends, so the join is
11
+ * line-by-line rather than a comparison of two totals — a total that matches
12
+ * can still be two errors cancelling out.
13
+ *
14
+ * Four properties of this feed change how it must be read, and getting any of
15
+ * them wrong produces a confident wrong answer:
16
+ *
17
+ * `cost_state: 'pending'` means the usage exists and its charge does not yet.
18
+ * Those rows can still be repriced. Summing them as zero understates spend
19
+ * and, worse, looks settled.
20
+ *
21
+ * Zero-cost rows are INCLUDED on purpose. "You were not charged for this" is
22
+ * an answer; a row that is simply absent is indistinguishable from one the
23
+ * client dropped. Never filter them.
24
+ *
25
+ * `unavailable_days` names days the gateway could not list rather than
26
+ * silently returning a short page. Swallowing it makes two correct ledgers
27
+ * look like they disagree.
28
+ *
29
+ * `kind` says whether a row is checkable locally at all. A `chat` charge can
30
+ * be rebuilt from tokens and a published rate; a `service` charge is a
31
+ * per-call figure only the gateway holds, so a local estimate for one is a
32
+ * guess by construction and a mismatch is not evidence of a bug.
33
+ *
34
+ * The cursor is opaque. Do not parse it, and do not construct one.
35
+ */
36
+ import { KEY_API_URL, USER_AGENT } from '../config.js';
37
+ import { loadApiKey } from './auth-mode.js';
38
+ /** Max rows the endpoint will return per page. */
39
+ const MAX_LIMIT = 500;
40
+ /** Stop paging rather than walk an unbounded history. */
41
+ const MAX_PAGES = 40;
42
+ function toRow(raw) {
43
+ const requestId = typeof raw.request_id === 'string' ? raw.request_id : '';
44
+ if (!requestId)
45
+ return null; // without the join key the row is not usable here
46
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
47
+ const state = raw.cost_state;
48
+ return {
49
+ requestId,
50
+ timestamp: typeof raw.timestamp === 'string' ? raw.timestamp : '',
51
+ endpoint: typeof raw.endpoint === 'string' ? raw.endpoint : '',
52
+ model: typeof raw.model === 'string' ? raw.model : null,
53
+ kind: raw.kind === 'chat' ? 'chat' : 'service',
54
+ inputTokens: num(raw.input_tokens),
55
+ outputTokens: num(raw.output_tokens),
56
+ costUsd: num(raw.cost_usd),
57
+ // An unrecognised state is treated as pending, not priced: the safe error
58
+ // is "we do not know yet", never "settled at whatever number came through".
59
+ costState: state === 'priced' || state === 'free' ? state : 'pending',
60
+ status: num(raw.status),
61
+ };
62
+ }
63
+ /**
64
+ * Fetch usage rows, following the cursor. Returns null when there is no key or
65
+ * the gateway is unreachable — callers show what they do know rather than
66
+ * inventing a ledger.
67
+ */
68
+ export async function fetchUsage(opts = {}) {
69
+ const key = loadApiKey();
70
+ if (!key)
71
+ return null;
72
+ const rows = [];
73
+ const unavailableDays = new Set();
74
+ let cursor = null;
75
+ for (let page = 0; page < MAX_PAGES; page++) {
76
+ const url = new URL(`${KEY_API_URL}/v1/usage`);
77
+ if (opts.from)
78
+ url.searchParams.set('from', opts.from);
79
+ if (opts.to)
80
+ url.searchParams.set('to', opts.to);
81
+ url.searchParams.set('limit', String(Math.min(opts.limit ?? MAX_LIMIT, MAX_LIMIT)));
82
+ if (cursor)
83
+ url.searchParams.set('cursor', cursor);
84
+ let body;
85
+ try {
86
+ const res = await fetch(url, {
87
+ headers: { Authorization: `Bearer ${key}`, 'User-Agent': USER_AGENT },
88
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 20_000),
89
+ });
90
+ if (!res.ok)
91
+ return null;
92
+ body = (await res.json());
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ for (const raw of Array.isArray(body.data) ? body.data : []) {
98
+ const row = toRow(raw);
99
+ if (row)
100
+ rows.push(row);
101
+ }
102
+ for (const d of Array.isArray(body.unavailable_days) ? body.unavailable_days : []) {
103
+ if (typeof d === 'string')
104
+ unavailableDays.add(d);
105
+ }
106
+ cursor = typeof body.next_cursor === 'string' && body.next_cursor ? body.next_cursor : null;
107
+ if (!cursor)
108
+ break;
109
+ }
110
+ return { rows, unavailableDays: [...unavailableDays] };
111
+ }
112
+ export function summarize(rows) {
113
+ const t = {
114
+ pricedUsd: 0, pricedCount: 0, pendingCount: 0, freeCount: 0, chatCount: 0, serviceCount: 0,
115
+ };
116
+ for (const r of rows) {
117
+ if (r.costState === 'priced') {
118
+ t.pricedUsd += r.costUsd;
119
+ t.pricedCount++;
120
+ }
121
+ else if (r.costState === 'pending')
122
+ t.pendingCount++;
123
+ else
124
+ t.freeCount++;
125
+ if (r.kind === 'chat')
126
+ t.chatCount++;
127
+ else
128
+ t.serviceCount++;
129
+ }
130
+ return t;
131
+ }
132
+ /**
133
+ * Join the gateway ledger to Franklin's own journal on `request_id`.
134
+ *
135
+ * Only `priced` rows are compared. A `pending` row has no charge to disagree
136
+ * with yet, and a `free` row's zero is an answer rather than a discrepancy.
137
+ *
138
+ * `unjoinable` counts local rows with no id — wallet-mode calls, free-path
139
+ * calls, and anything recorded before the id was captured. They are reported
140
+ * rather than hidden, because "0 mismatches" from a journal that could not be
141
+ * joined is not the same statement as "0 mismatches".
142
+ */
143
+ export function reconcile(ledger, local) {
144
+ const byId = new Map();
145
+ let unjoinable = 0;
146
+ for (const r of local) {
147
+ if (r.requestId)
148
+ byId.set(r.requestId, (byId.get(r.requestId) ?? 0) + r.costUsd);
149
+ else
150
+ unjoinable++;
151
+ }
152
+ const matched = [];
153
+ const missingLocally = [];
154
+ for (const row of ledger.rows) {
155
+ if (row.costState !== 'priced')
156
+ continue;
157
+ const localUsd = byId.get(row.requestId);
158
+ if (localUsd === undefined) {
159
+ // A charge with no local row: real spend Franklin never counted, so it
160
+ // never reached --max-spend either.
161
+ if (row.costUsd > 0)
162
+ missingLocally.push(row);
163
+ continue;
164
+ }
165
+ matched.push({ row, localUsd, deltaUsd: localUsd - row.costUsd });
166
+ }
167
+ return { matched, missingLocally, unjoinable, totals: summarize(ledger.rows), unavailableDays: ledger.unavailableDays };
168
+ }
@@ -11,6 +11,12 @@ export interface UsageRecord {
11
11
  costUsd: number;
12
12
  latencyMs: number;
13
13
  fallback?: boolean;
14
+ /**
15
+ * The gateway's `x-blockrun-request-id` for this call, when it sent one.
16
+ * The join key `franklin usage` uses to line this row up against the
17
+ * account ledger. Absent on wallet-mode and free-path calls.
18
+ */
19
+ requestId?: string;
14
20
  }
15
21
  export interface ModelStats {
16
22
  requests: number;
@@ -60,7 +66,9 @@ export declare function recordUsage(model: string, inputTokens: number, outputTo
60
66
  * key-mode row is priced locally. Surfaced by `franklin stats` so the ledger
61
67
  * never claims more precision than it has.
62
68
  */
63
- estimated?: boolean): void;
69
+ estimated?: boolean,
70
+ /** Gateway request id, from `requestIdFromResponse`. Enables reconciliation. */
71
+ requestId?: string | null): void;
64
72
  /**
65
73
  * Get stats summary for display
66
74
  */
@@ -200,7 +200,9 @@ export function recordUsage(model, inputTokens, outputTokens, costUsd, latencyMs
200
200
  * key-mode row is priced locally. Surfaced by `franklin stats` so the ledger
201
201
  * never claims more precision than it has.
202
202
  */
203
- estimated = isKeyMode()) {
203
+ estimated = isKeyMode(),
204
+ /** Gateway request id, from `requestIdFromResponse`. Enables reconciliation. */
205
+ requestId) {
204
206
  // Count real spend BEFORE the test/audit gates — the --max-spend ceiling must
205
207
  // see every paid tool call even when history persistence is suppressed.
206
208
  if (Number.isFinite(costUsd) && costUsd > 0)
@@ -262,6 +264,9 @@ estimated = isKeyMode()) {
262
264
  costUsd,
263
265
  latencyMs,
264
266
  fallback,
267
+ // Omit rather than store undefined: history is JSON round-tripped, and an
268
+ // explicit `requestId: undefined` survives as a key with no value.
269
+ ...(requestId ? { requestId } : {}),
265
270
  });
266
271
  scheduleSave();
267
272
  }
@@ -289,15 +289,25 @@ function executeCommand(command, timeoutMs, ctx) {
289
289
  const shell = fs.existsSync('/bin/bash') ? '/bin/bash' : (process.env.SHELL || '/bin/sh');
290
290
  let child;
291
291
  try {
292
+ // The account bearer key is deliberately withheld from the subprocess.
293
+ // bash-guard auto-approves `printenv` and `echo` as safe, so
294
+ // `printenv BLOCKRUN_API_KEY` ran with no confirmation and returned the
295
+ // key as tool output — into the model prompt and the saved transcript.
296
+ // Wallet private keys are never in the environment at all; this gives
297
+ // the key the same treatment. Franklin's own gateway calls read
298
+ // process.env in-process and are unaffected, and a user who genuinely
299
+ // needs the key in a shell can export it there themselves.
300
+ const childEnv = {
301
+ ...process.env,
302
+ FRANKLIN: '1', // Let scripts detect they're running inside Franklin
303
+ FRANKLIN_WORKDIR: ctx.workingDir,
304
+ RUNCODE: '1', // Backwards compat
305
+ RUNCODE_WORKDIR: ctx.workingDir,
306
+ };
307
+ delete childEnv.BLOCKRUN_API_KEY;
292
308
  child = spawn(shell, ['-c', command], {
293
309
  cwd: ctx.workingDir,
294
- env: {
295
- ...process.env,
296
- FRANKLIN: '1', // Let scripts detect they're running inside Franklin
297
- FRANKLIN_WORKDIR: ctx.workingDir,
298
- RUNCODE: '1', // Backwards compat
299
- RUNCODE_WORKDIR: ctx.workingDir,
300
- },
310
+ env: childEnv,
301
311
  stdio: ['ignore', 'pipe', 'pipe'],
302
312
  // Put the shell in its own process group (pgid = pid) so a timeout
303
313
  // can SIGTERM the entire tree. Without this, signalling only the
@@ -176,7 +176,7 @@ function fmtUsd(n) {
176
176
  export const blockrunCapability = {
177
177
  spec: {
178
178
  name: 'BlockRun',
179
- description: 'Call any BlockRun gateway endpoint. Signs an x402 USDC payment from the user wallet, retries on HTTP 402, and returns the response. ' +
179
+ description: 'Call any BlockRun gateway endpoint. Billed to account credits or, in wallet mode, by signing an x402 USDC payment and retrying on HTTP 402. ' +
180
180
  'Use this for crypto data (Surf — markets, on-chain, social), AI inference (chat / image / video / music), prediction markets, DeFi data, and any other API exposed under https://blockrun.ai/marketplace. ' +
181
181
  'For phone and voice, prefer the typed tools (ListPhoneNumbers, BuyPhoneNumber, RenewPhoneNumber, ReleasePhoneNumber, PhoneLookup, PhoneFraudCheck, VoiceCall, VoiceStatus) — they spell out cost, required fields, and the buy-number-first requirement. ' +
182
182
  'The path must start with "/v1/" or "/.well-known/". ' +