@blockrun/franklin 3.29.7 → 3.29.8

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.
@@ -19,7 +19,7 @@ import { ToolCallRepair } from './repair/index.js';
19
19
  import { resetToolSessionState } from '../tools/index.js';
20
20
  import { CORE_TOOL_NAMES, dynamicToolsEnabled } from '../tools/tool-categories.js';
21
21
  import { createActivateToolCapability } from '../tools/activate.js';
22
- import { recordUsage } from '../stats/tracker.js';
22
+ import { recordUsage, getLiveSpendUsd } from '../stats/tracker.js';
23
23
  import { recordSessionUsage } from '../stats/session-tracker.js';
24
24
  import { appendAudit, extractLastUserPrompt } from '../stats/audit.js';
25
25
  import { logger, setDebugMode } from '../logger.js';
@@ -1322,6 +1322,14 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1322
1322
  // "this model is consistently slow" or "fallback was faster" until
1323
1323
  // this was fixed.
1324
1324
  const llmCallStartedAt = Date.now();
1325
+ // Snapshot live spend BEFORE the stream starts. Concurrent paid tools
1326
+ // (DeFiLlama/RPC/Prediction/...) are kicked off mid-stream via
1327
+ // onToolReceived and can settle their x402 charge before collectResults —
1328
+ // a snapshot taken AFTER the stream would miss them and let them slip the
1329
+ // --max-spend cap. We subtract the LLM's own callCost from the post-tool
1330
+ // delta below (it is added to sessionCostUsd separately), leaving a clean
1331
+ // paid-tool-only total that captures concurrent and sequential tools alike.
1332
+ const turnSpendBefore = getLiveSpendUsd();
1325
1333
  try {
1326
1334
  const result = await client.complete({
1327
1335
  model: resolvedModel,
@@ -1446,6 +1454,19 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1446
1454
  }
1447
1455
  }
1448
1456
  catch (err) {
1457
+ // ── Count a paid-but-dropped LLM charge before any retry resets it ──
1458
+ // recordSettledPayment debits the wallet BEFORE the SSE stream is parsed;
1459
+ // if the stream then fails (idle timeout, mid-stream error, or Esc), that
1460
+ // USDC is real but the success-path accounting (which reads
1461
+ // getLastPaidUsd) never ran, and the next attempt resets the accumulator.
1462
+ // Fold it into the session total NOW so --max-spend and the running cost
1463
+ // stay honest. The on-chain charge is already in cost_log via the SDK;
1464
+ // this fixes the in-session view / ceiling, not the wire ledger.
1465
+ const droppedPaidUsd = client.getLastPaidUsd();
1466
+ if (droppedPaidUsd > 0) {
1467
+ sessionCostUsd += droppedPaidUsd;
1468
+ turnCostUsd += droppedPaidUsd;
1469
+ }
1449
1470
  // ── User abort (Esc key) ──
1450
1471
  if (err.name === 'AbortError' || abort.signal.aborted) {
1451
1472
  // Save any partial response that was streamed before abort
@@ -1459,6 +1480,20 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1459
1480
  onEvent({ kind: 'turn_done', reason: 'aborted' });
1460
1481
  break;
1461
1482
  }
1483
+ // If the dropped charge pushed us over the hard cap, stop rather than
1484
+ // retry (a retry would spend more). Abort already returned above.
1485
+ const capAfterDrop = config.maxSpendUsd;
1486
+ if (droppedPaidUsd > 0 && typeof capAfterDrop === 'number' && Number.isFinite(capAfterDrop) &&
1487
+ capAfterDrop > 0 && sessionCostUsd >= capAfterDrop) {
1488
+ onEvent({
1489
+ kind: 'text_delta',
1490
+ text: `\n\n_Max-spend reached: $${sessionCostUsd.toFixed(4)} ≥ cap $${capAfterDrop.toFixed(2)} ` +
1491
+ `(incl. a charged-but-failed call). Stopping session._\n`,
1492
+ });
1493
+ persistSessionMeta();
1494
+ onEvent({ kind: 'turn_done', reason: 'budget' });
1495
+ return history;
1496
+ }
1462
1497
  const errMsg = err.message || '';
1463
1498
  const classified = classifyAgentError(errMsg);
1464
1499
  // ── Media size error recovery (strip images/PDFs + retry) ──
@@ -2084,6 +2119,31 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2084
2119
  for (const [inv, result] of results) {
2085
2120
  onEvent({ kind: 'capability_done', id: inv.id, result });
2086
2121
  }
2122
+ // ── Fold paid-TOOL spend into the session cost ceiling ──
2123
+ // sessionCostUsd above only tracks LLM token cost; paid tools (ImageGen,
2124
+ // VideoGen, MusicGen, Exa, Surf, RealFace, Voice, Phone, Modal, DeFiLlama,
2125
+ // RPC, Prediction) settle USDC through their own x402 paths and report it
2126
+ // via recordUsage. Diff the live-spend accumulator across the WHOLE turn
2127
+ // (snapshot taken before the stream, so mid-stream concurrent tools are
2128
+ // captured too) and subtract the LLM's own callCost — which recordUsage at
2129
+ // line ~1948 already added to liveSpendUsd and which sessionCostUsd counts
2130
+ // separately — leaving paid-tool-only spend so --max-spend bounds total USDC.
2131
+ const toolSpendUsd = Math.max(0, getLiveSpendUsd() - turnSpendBefore - callCost);
2132
+ if (toolSpendUsd > 0) {
2133
+ sessionCostUsd += toolSpendUsd;
2134
+ turnCostUsd += toolSpendUsd;
2135
+ const cap = config.maxSpendUsd;
2136
+ if (typeof cap === 'number' && Number.isFinite(cap) && cap > 0 && sessionCostUsd >= cap) {
2137
+ onEvent({
2138
+ kind: 'text_delta',
2139
+ text: `\n\n_Max-spend reached: $${sessionCostUsd.toFixed(4)} ≥ cap $${cap.toFixed(2)} (incl. paid-tool spend). ` +
2140
+ `Stopping session — further calls would exceed the budget._\n`,
2141
+ });
2142
+ persistSessionMeta();
2143
+ onEvent({ kind: 'turn_done', reason: 'budget' });
2144
+ return history;
2145
+ }
2146
+ }
2087
2147
  // ── Tool call guardrails ──
2088
2148
  turnToolCalls += results.length;
2089
2149
  for (const [inv, result] of results) {
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { API_URLS, loadChain } from '../config.js';
16
16
  import { postWithPayment } from '../payments/post-with-payment.js';
17
+ import { recordUsage } from '../stats/tracker.js';
17
18
  import { writeCache } from './cache.js';
18
19
  function phoneEndpoint(chain, path) {
19
20
  return `${API_URLS[chain]}/v1/phone/${path}`;
@@ -24,6 +25,7 @@ function phoneEndpoint(chain, path) {
24
25
  */
25
26
  export async function listNumbers(opts) {
26
27
  const chain = loadChain();
28
+ const startedAt = Date.now();
27
29
  const result = await postWithPayment(phoneEndpoint(chain, 'numbers/list'), {}, 'List wallet-owned BlockRun phone numbers');
28
30
  if (!result.ok) {
29
31
  const message = typeof result.body.error === 'string' ? result.body.error : `gateway ${result.status}`;
@@ -33,15 +35,28 @@ export async function listNumbers(opts) {
33
35
  ? result.body.numbers
34
36
  : [];
35
37
  writeCache({ wallet: opts.walletAddress, chain, numbers });
38
+ // Record the $0.001 x402 spend so panel/background list calls land in
39
+ // franklin stats — same label the agent's ListPhoneNumbers tool uses so the
40
+ // two aggregate (panel-initiated spend was previously dropped entirely).
41
+ try {
42
+ recordUsage('ListPhoneNumbers', 0, 0, 0.001, Date.now() - startedAt);
43
+ }
44
+ catch { /* best-effort */ }
36
45
  return { numbers, count: numbers.length, paid: 0.001 };
37
46
  }
38
47
  export async function renewNumber(phoneNumber) {
39
48
  const chain = loadChain();
49
+ const startedAt = Date.now();
40
50
  const result = await postWithPayment(phoneEndpoint(chain, 'numbers/renew'), { phoneNumber }, `Renew BlockRun phone number ${phoneNumber}`);
41
51
  if (!result.ok) {
42
52
  const message = typeof result.body.error === 'string' ? result.body.error : `gateway ${result.status}`;
43
53
  throw new Error(message);
44
54
  }
55
+ // Record the $5 x402 spend (parity with the agent's RenewPhoneNumber tool).
56
+ try {
57
+ recordUsage('RenewPhoneNumber', 0, 0, 5.0, Date.now() - startedAt);
58
+ }
59
+ catch { /* best-effort */ }
45
60
  return {
46
61
  phone_number: String(result.body.phone_number ?? phoneNumber),
47
62
  expires_at: String(result.body.expires_at ?? ''),
@@ -50,6 +65,7 @@ export async function renewNumber(phoneNumber) {
50
65
  }
51
66
  export async function buyNumber(opts) {
52
67
  const chain = loadChain();
68
+ const startedAt = Date.now();
53
69
  const body = { country: opts.country || 'US' };
54
70
  if (opts.areaCode)
55
71
  body.areaCode = opts.areaCode;
@@ -58,6 +74,12 @@ export async function buyNumber(opts) {
58
74
  const message = typeof result.body.error === 'string' ? result.body.error : `gateway ${result.status}`;
59
75
  throw new Error(message);
60
76
  }
77
+ // Record the $5 x402 spend (parity with the agent's BuyPhoneNumber tool) so a
78
+ // panel-initiated buy is no longer invisible to franklin stats / the ledger.
79
+ try {
80
+ recordUsage('BuyPhoneNumber', 0, 0, 5.0, Date.now() - startedAt);
81
+ }
82
+ catch { /* best-effort */ }
61
83
  return {
62
84
  phone_number: String(result.body.phone_number ?? ''),
63
85
  expires_at: String(result.body.expires_at ?? ''),
@@ -39,6 +39,10 @@ export declare function saveStats(stats: Stats): void;
39
39
  export declare function clearStats(): void;
40
40
  /** Flush stats to disk immediately (call on process exit) */
41
41
  export declare function flushStats(): void;
42
+ /** Cumulative USDC recorded via recordUsage this process. */
43
+ export declare function getLiveSpendUsd(): number;
44
+ /** Test helper: reset the live-spend accumulator. */
45
+ export declare function resetLiveSpend(): void;
42
46
  /**
43
47
  * Record a completed request for stats tracking
44
48
  */
@@ -154,10 +154,29 @@ export function flushStats() {
154
154
  if (cachedStats)
155
155
  saveStats(cachedStats);
156
156
  }
157
+ // ── Live spend accumulator (process-lifetime) ──────────────────────────────
158
+ // Sum of every positive costUsd passed to recordUsage, counted BEFORE the
159
+ // test/audit gates below so it reflects REAL USDC spend regardless of whether
160
+ // the row is persisted to history. The agent loop diffs this around tool
161
+ // execution to fold paid-tool spend into the --max-spend session ceiling, which
162
+ // would otherwise only see LLM token cost. See src/agent/loop.ts.
163
+ let liveSpendUsd = 0;
164
+ /** Cumulative USDC recorded via recordUsage this process. */
165
+ export function getLiveSpendUsd() {
166
+ return liveSpendUsd;
167
+ }
168
+ /** Test helper: reset the live-spend accumulator. */
169
+ export function resetLiveSpend() {
170
+ liveSpendUsd = 0;
171
+ }
157
172
  /**
158
173
  * Record a completed request for stats tracking
159
174
  */
160
175
  export function recordUsage(model, inputTokens, outputTokens, costUsd, latencyMs, fallback = false) {
176
+ // Count real spend BEFORE the test/audit gates — the --max-spend ceiling must
177
+ // see every paid tool call even when history persistence is suppressed.
178
+ if (Number.isFinite(costUsd) && costUsd > 0)
179
+ liveSpendUsd += costUsd;
161
180
  // Same rationale as appendAudit — tests run in-process with
162
181
  // local/test* models and would otherwise mix into franklin-stats.json
163
182
  // history (verified: 8.4% of a real user's 1000-entry history was
@@ -18,6 +18,7 @@
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
19
  import { loadChain, API_URLS, VERSION } from '../config.js';
20
20
  import { logger } from '../logger.js';
21
+ import { recordUsage } from '../stats/tracker.js';
21
22
  const TIMEOUT_MS = 30_000;
22
23
  // ─── Shared GET-with-x402 flow ────────────────────────────────────────────
23
24
  async function getWithPayment(path, ctx) {
@@ -32,6 +33,8 @@ async function getWithPayment(path, ctx) {
32
33
  const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
33
34
  const onAbort = () => controller.abort();
34
35
  ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
36
+ const startedAt = Date.now();
37
+ let paidUsd = 0;
35
38
  try {
36
39
  let response = await fetch(endpoint, {
37
40
  method: 'GET',
@@ -39,20 +42,27 @@ async function getWithPayment(path, ctx) {
39
42
  headers,
40
43
  });
41
44
  if (response.status === 402) {
42
- const paymentHeaders = await signPayment(response, chain, endpoint);
43
- if (!paymentHeaders) {
45
+ const signed = await signPayment(response, chain, endpoint);
46
+ if (!signed) {
44
47
  throw new Error('Payment signing failed — check wallet balance');
45
48
  }
49
+ paidUsd = signed.amountUsd;
46
50
  response = await fetch(endpoint, {
47
51
  method: 'GET',
48
52
  signal: controller.signal,
49
- headers: { ...headers, ...paymentHeaders },
53
+ headers: { ...headers, ...signed.headers },
50
54
  });
51
55
  }
52
56
  if (!response.ok) {
53
57
  const errText = await response.text().catch(() => '');
54
58
  throw new Error(`DefiLlama ${path} failed (${response.status}): ${errText.slice(0, 200)}`);
55
59
  }
60
+ // Record the settled x402 spend so DeFiLlama calls show up in franklin
61
+ // stats / audit AND count against the --max-spend ceiling (parity with surf.ts).
62
+ try {
63
+ recordUsage(`DeFiLlama:${path}`, 0, 0, paidUsd, Date.now() - startedAt);
64
+ }
65
+ catch { /* best-effort */ }
56
66
  return (await response.json());
57
67
  }
58
68
  finally {
@@ -77,7 +87,7 @@ async function signPayment(response, chain, endpoint) {
77
87
  maxTimeoutSeconds: details.maxTimeoutSeconds || 60,
78
88
  extra: details.extra,
79
89
  });
80
- return { 'PAYMENT-SIGNATURE': payload };
90
+ return { headers: { 'PAYMENT-SIGNATURE': payload }, amountUsd: Number(details.amount) / 1_000_000 };
81
91
  }
82
92
  const wallet = await getOrCreateWallet();
83
93
  const paymentRequired = parsePaymentRequired(paymentHeader);
@@ -88,7 +98,7 @@ async function signPayment(response, chain, endpoint) {
88
98
  maxTimeoutSeconds: details.maxTimeoutSeconds || 60,
89
99
  extra: details.extra,
90
100
  });
91
- return { 'PAYMENT-SIGNATURE': payload };
101
+ return { headers: { 'PAYMENT-SIGNATURE': payload }, amountUsd: Number(details.amount) / 1_000_000 };
92
102
  }
93
103
  catch (err) {
94
104
  logger.warn(`[franklin] DefiLlama payment error: ${err.message}`);
@@ -16,5 +16,6 @@
16
16
  * https://github.com/Jupiter-DevRel/typescript-examples/tree/main/ultra/order-execute-with-referral-accounts
17
17
  */
18
18
  import type { CapabilityHandler } from '../agent/types.js';
19
+ export declare function toAtomicUnits(amount: number, decimals: number): string;
19
20
  export declare const jupiterQuoteCapability: CapabilityHandler;
20
21
  export declare const jupiterSwapCapability: CapabilityHandler;
@@ -113,12 +113,38 @@ function symbolFor(mint) {
113
113
  }
114
114
  return mint.slice(0, 4) + '…';
115
115
  }
116
- function toAtomicUnits(amount, decimals) {
117
- // BigInt math — JavaScript number can lose precision for large lamport counts.
118
- const scale = BigInt(10) ** BigInt(decimals);
119
- const whole = BigInt(Math.floor(amount));
120
- const fractional = BigInt(Math.round((amount - Math.floor(amount)) * Number(scale)));
121
- return (whole * scale + fractional).toString();
116
+ export function toAtomicUnits(amount, decimals) {
117
+ if (!Number.isFinite(amount) || amount <= 0) {
118
+ throw new Error('amount must be a positive finite number');
119
+ }
120
+ if (!Number.isSafeInteger(decimals) || decimals < 0) {
121
+ throw new Error('decimals must be a nonnegative safe integer');
122
+ }
123
+ // Parse the decimal string directly — no `float * scale`, which loses
124
+ // precision on high-decimal tokens (the original bug #89 fixed). Excess
125
+ // precision beyond the token's `decimals` is FLOORED to the atomic unit
126
+ // (slice keeps the leading `decimals` digits), so an agent-computed amount —
127
+ // ⅓ of a balance, or float noise like 0.1 + 0.2 = 0.30000000000000004 — still
128
+ // swaps its representable part instead of being rejected. The original
129
+ // Math.round approach instead rounded a sub-unit amount UP to one atomic unit.
130
+ // Plain-decimal string (never exponential form, so BigInt(wholePart) can't
131
+ // throw on large amounts like 1e21). toLocaleString keeps the exact value to
132
+ // 20 fraction digits — more than any token's decimals — and the slice() below
133
+ // FLOORS by truncation, so sub-precision dust is never rounded UP to one unit
134
+ // (unlike the old toFixed path, which rounded 9.999e-10 up to 1).
135
+ const amountText = amount.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 20 });
136
+ const [wholePart, fractionalPart = ''] = amountText.split('.');
137
+ const normalizedFraction = fractionalPart.padEnd(decimals, '0').slice(0, decimals);
138
+ const whole = BigInt(wholePart);
139
+ const fraction = normalizedFraction === '' ? 0n : BigInt(normalizedFraction);
140
+ const scale = 10n ** BigInt(decimals);
141
+ const atomic = whole * scale + fraction;
142
+ // Reject only TRUE dust: an amount so small it floors to zero atomic units,
143
+ // which Jupiter can't swap. (The old code rounded this UP to 1 unit instead.)
144
+ if (atomic === 0n) {
145
+ throw new Error(`amount ${amount} is below the minimum atomic unit for a ${decimals}-decimal token — too small to swap`);
146
+ }
147
+ return atomic.toString();
122
148
  }
123
149
  function fromAtomicUnits(atomic, decimals) {
124
150
  const value = typeof atomic === 'string' ? Number(atomic) : atomic;
@@ -205,7 +231,16 @@ async function executeJupiterQuote(input) {
205
231
  const inputMint = resolveMint(input.input_mint);
206
232
  const outputMint = resolveMint(input.output_mint);
207
233
  const inDec = decimalsFor(inputMint);
208
- const amountAtomic = toAtomicUnits(input.amount, inDec);
234
+ let amountAtomic;
235
+ try {
236
+ amountAtomic = toAtomicUnits(input.amount, inDec);
237
+ }
238
+ catch (err) {
239
+ return {
240
+ output: `Invalid Jupiter amount: ${err instanceof Error ? err.message : String(err)}`,
241
+ isError: true,
242
+ };
243
+ }
209
244
  try {
210
245
  const order = await ultraOrder({ inputMint, outputMint, amount: amountAtomic });
211
246
  if (order.errorMessage) {
@@ -234,7 +269,16 @@ async function executeJupiterSwap(input, ctx) {
234
269
  const inputMint = resolveMint(input.input_mint);
235
270
  const outputMint = resolveMint(input.output_mint);
236
271
  const inDec = decimalsFor(inputMint);
237
- const amountAtomic = toAtomicUnits(input.amount, inDec);
272
+ let amountAtomic;
273
+ try {
274
+ amountAtomic = toAtomicUnits(input.amount, inDec);
275
+ }
276
+ catch (err) {
277
+ return {
278
+ output: `Invalid Jupiter amount: ${err instanceof Error ? err.message : String(err)}`,
279
+ isError: true,
280
+ };
281
+ }
238
282
  // Load wallet — `getOrCreateSolanaWallet` auto-creates on first run, so this
239
283
  // path firing means the file is corrupt or the .blockrun dir is unreadable.
240
284
  let keypair;
@@ -19,6 +19,7 @@ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, creat
19
19
  import { loadChain, API_URLS, VERSION } from '../config.js';
20
20
  import { logger } from '../logger.js';
21
21
  import { findModel, estimateCostUsd } from '../gateway-models.js';
22
+ import { recordUsage } from '../stats/tracker.js';
22
23
  const DEFAULT_MODEL = 'minimax/music-2.5+';
23
24
  // Flat per-track price for the default model — already margin-inclusive
24
25
  // ($0.15/track × 1.05 gateway margin). Fallback when the catalog is unavailable.
@@ -94,6 +95,7 @@ function buildExecute(deps) {
94
95
  const timeout = setTimeout(() => controller.abort(), GEN_TIMEOUT_MS);
95
96
  const onAbort = () => controller.abort();
96
97
  ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
98
+ const callStartedAt = Date.now();
97
99
  try {
98
100
  let response = await fetch(endpoint, {
99
101
  method: 'POST',
@@ -125,6 +127,13 @@ function buildExecute(deps) {
125
127
  if (!track?.url) {
126
128
  return { output: 'No track URL returned from API', isError: true };
127
129
  }
130
+ // Record the settled x402 spend so MusicGen lands in franklin stats /
131
+ // insights AND counts against the --max-spend ceiling — image/video gen
132
+ // already do this; music was the lone media tool that bypassed recordUsage.
133
+ try {
134
+ recordUsage(musicModel, 0, 0, trackCostUsd, Date.now() - callStartedAt);
135
+ }
136
+ catch { /* best-effort */ }
128
137
  // CDN URLs expire in ~24h — download NOW.
129
138
  const dlCtrl = new AbortController();
130
139
  const dlTimeout = setTimeout(() => dlCtrl.abort(), DOWNLOAD_TIMEOUT_MS);
@@ -155,6 +155,16 @@ export const buyPhoneNumberCapability = {
155
155
  body.country = input.country;
156
156
  if (typeof input.area_code === 'string')
157
157
  body.areaCode = input.area_code;
158
+ // Confirm the $5 spend before charging — this is the most expensive single
159
+ // autonomous action, so it gets the same gate as a $0.05 ModalCreate. Direct
160
+ // callers (FRANKLIN_MEDIA_AUTO_APPROVE_ALL=1 or no onAskUser bridge) proceed.
161
+ const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
162
+ if (!autoApprove && ctx.onAskUser) {
163
+ const answer = await ctx.onAskUser(`Buy a new ${body.country || 'US'} phone number for $5.00 USDC? No USDC is spent if you cancel.`, ['Buy', 'Cancel']);
164
+ if (answer !== 'Buy') {
165
+ return { output: `## Phone number purchase cancelled\n\nNo USDC was spent.` };
166
+ }
167
+ }
158
168
  try {
159
169
  const res = await postWithPayment('/v1/phone/numbers/buy', body, ctx, { tool: 'BuyPhoneNumber', priceUsd: 5.0 });
160
170
  return {
@@ -185,6 +195,14 @@ export const renewPhoneNumberCapability = {
185
195
  if (typeof input.phone_number !== 'string') {
186
196
  return { output: 'phone_number (E.164) required', isError: true };
187
197
  }
198
+ // Confirm the $5 spend before charging (parity with BuyPhoneNumber / ModalCreate).
199
+ const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
200
+ if (!autoApprove && ctx.onAskUser) {
201
+ const answer = await ctx.onAskUser(`Renew ${input.phone_number} for 30 days at $5.00 USDC? No USDC is spent if you cancel.`, ['Renew', 'Cancel']);
202
+ if (answer !== 'Renew') {
203
+ return { output: `## Renewal cancelled\n\nNo USDC was spent.` };
204
+ }
205
+ }
188
206
  try {
189
207
  const res = await postWithPayment('/v1/phone/numbers/renew', { phoneNumber: input.phone_number }, ctx, { tool: 'RenewPhoneNumber', priceUsd: 5.0 });
190
208
  return {
@@ -36,6 +36,7 @@ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, creat
36
36
  import { loadChain, API_URLS, VERSION } from '../config.js';
37
37
  import { logger } from '../logger.js';
38
38
  import { recordFetch } from '../trading/providers/telemetry.js';
39
+ import { recordUsage } from '../stats/tracker.js';
39
40
  const TIMEOUT_MS = 30_000;
40
41
  const DEFAULT_LIMIT = 20;
41
42
  const MAX_LIMIT = 50;
@@ -111,6 +112,13 @@ async function getWithPayment(path, query, ctx) {
111
112
  latencyMs: Date.now() - startedAt,
112
113
  costUsd: costRecorded > 0 ? costRecorded : undefined,
113
114
  });
115
+ // ALSO persist to franklin-stats (recordFetch is in-memory only, lost on
116
+ // restart). Without this, Predexon spend is absent from `franklin stats`
117
+ // and invisible to the --max-spend ceiling (parity with surf.ts).
118
+ try {
119
+ recordUsage(`PredictionMarket:${path}`, 0, 0, costRecorded, Date.now() - startedAt);
120
+ }
121
+ catch { /* best-effort */ }
114
122
  return (await response.json());
115
123
  }
116
124
  finally {
package/dist/tools/rpc.js CHANGED
@@ -19,6 +19,7 @@
19
19
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
20
20
  import { loadChain, API_URLS, VERSION } from '../config.js';
21
21
  import { logger } from '../logger.js';
22
+ import { recordUsage } from '../stats/tracker.js';
22
23
  const TIMEOUT_MS = 30_000;
23
24
  // Curated chains the gateway exposes (for the agent + validation). Unknown but
24
25
  // well-formed slugs still pass through — the gateway resolves them — so this is
@@ -57,6 +58,8 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
57
58
  const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
58
59
  const onAbort = () => controller.abort();
59
60
  ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
61
+ const startedAt = Date.now();
62
+ let paidUsd = 0;
60
63
  try {
61
64
  let response = await fetch(endpoint, {
62
65
  method: 'POST',
@@ -65,14 +68,15 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
65
68
  body: bodyStr,
66
69
  });
67
70
  if (response.status === 402) {
68
- const paymentHeaders = await signPayment(response, chain, endpoint);
69
- if (!paymentHeaders) {
71
+ const signed = await signPayment(response, chain, endpoint);
72
+ if (!signed) {
70
73
  throw new Error('Payment signing failed — check wallet balance');
71
74
  }
75
+ paidUsd = signed.amountUsd;
72
76
  response = await fetch(endpoint, {
73
77
  method: 'POST',
74
78
  signal: controller.signal,
75
- headers: { ...headers, ...paymentHeaders },
79
+ headers: { ...headers, ...signed.headers },
76
80
  body: bodyStr,
77
81
  });
78
82
  }
@@ -80,6 +84,12 @@ async function postRpcWithPayment(network, jsonRpcBody, ctx) {
80
84
  const errText = await response.text().catch(() => '');
81
85
  throw new Error(`RPC ${network} failed (${response.status}): ${errText.slice(0, 200)}`);
82
86
  }
87
+ // Record the settled x402 spend so RPC calls show up in franklin stats /
88
+ // audit AND count against the --max-spend ceiling (parity with surf.ts).
89
+ try {
90
+ recordUsage(`MultiChainRPC:${network}`, 0, 0, paidUsd, Date.now() - startedAt);
91
+ }
92
+ catch { /* best-effort */ }
83
93
  return {
84
94
  body: await response.json(),
85
95
  network: response.headers.get('x-network') || network,
@@ -109,7 +119,7 @@ async function signPayment(response, chain, endpoint) {
109
119
  maxTimeoutSeconds: details.maxTimeoutSeconds || 60,
110
120
  extra: details.extra,
111
121
  });
112
- return { 'PAYMENT-SIGNATURE': payload };
122
+ return { headers: { 'PAYMENT-SIGNATURE': payload }, amountUsd: Number(details.amount) / 1_000_000 };
113
123
  }
114
124
  const wallet = await getOrCreateWallet();
115
125
  const paymentRequired = parsePaymentRequired(paymentHeader);
@@ -120,7 +130,7 @@ async function signPayment(response, chain, endpoint) {
120
130
  maxTimeoutSeconds: details.maxTimeoutSeconds || 60,
121
131
  extra: details.extra,
122
132
  });
123
- return { 'PAYMENT-SIGNATURE': payload };
133
+ return { headers: { 'PAYMENT-SIGNATURE': payload }, amountUsd: Number(details.amount) / 1_000_000 };
124
134
  }
125
135
  catch (err) {
126
136
  logger.warn(`[franklin] RPC payment error: ${err.message}`);
@@ -103,7 +103,7 @@ async function postWithPayment(path, body, ctx, meta) {
103
103
  ctx.abortSignal.removeEventListener('abort', onAbort);
104
104
  }
105
105
  }
106
- async function getNoPayment(path, ctx, meta) {
106
+ async function getNoPayment(path, ctx, meta, record = true) {
107
107
  const startMs = Date.now();
108
108
  const chain = loadChain();
109
109
  const apiUrl = API_URLS[chain];
@@ -124,10 +124,14 @@ async function getNoPayment(path, ctx, meta) {
124
124
  }
125
125
  const data = (await resp.json());
126
126
  // Record even free calls so the audit tab shows the activity (cost 0).
127
- try {
128
- recordUsage(meta.tool, 0, 0, meta.priceUsd, Date.now() - startMs);
127
+ // `record: false` for internal poll loops — recording one row PER poll (up to
128
+ // 420 for VoiceStatus) would evict real spend history (capped at 1000 rows).
129
+ if (record) {
130
+ try {
131
+ recordUsage(meta.tool, 0, 0, meta.priceUsd, Date.now() - startMs);
132
+ }
133
+ catch { /* telemetry best-effort */ }
129
134
  }
130
- catch { /* telemetry best-effort */ }
131
135
  return data;
132
136
  }
133
137
  finally {
@@ -433,6 +437,14 @@ export const voiceStatusCapability = {
433
437
  }
434
438
  const callId = input.call_id;
435
439
  const deadline = Date.now() + VOICE_POLL_MAX_WAIT_MS;
440
+ const statusStartedAt = Date.now();
441
+ // Record ONE telemetry row per VoiceStatus invocation, not one per poll.
442
+ const recordStatusOnce = () => {
443
+ try {
444
+ recordUsage('VoiceStatus', 0, 0, 0, Date.now() - statusStartedAt);
445
+ }
446
+ catch { /* best-effort */ }
447
+ };
436
448
  // Internal poll-until-terminal loop — mirrors videogen.ts pollUntilReady
437
449
  // and imagegen.ts pollImageJob. The agent emits one VoiceStatus tool_use
438
450
  // and gets back the final transcript when the call ends. Without this
@@ -444,7 +456,7 @@ export const voiceStatusCapability = {
444
456
  return { output: 'VoiceStatus aborted by user', isError: true };
445
457
  }
446
458
  try {
447
- lastRes = await getNoPayment(`/v1/voice/call/${encodeURIComponent(callId)}`, ctx, { tool: 'VoiceStatus', priceUsd: 0 });
459
+ lastRes = await getNoPayment(`/v1/voice/call/${encodeURIComponent(callId)}`, ctx, { tool: 'VoiceStatus', priceUsd: 0 }, false);
448
460
  }
449
461
  catch (err) {
450
462
  return { output: `VoiceStatus failed: ${err.message}`, isError: true };
@@ -452,6 +464,7 @@ export const voiceStatusCapability = {
452
464
  patchCallJournal(callId, lastRes);
453
465
  const status = String(lastRes.status ?? lastRes.queue_status ?? '').toLowerCase();
454
466
  if (VOICE_TERMINAL_STATUSES.has(status)) {
467
+ recordStatusOnce();
455
468
  return {
456
469
  output: `## Voice call status (terminal: ${status})\n\n` +
457
470
  '```json\n' + JSON.stringify(lastRes, null, 2) + '\n```',
@@ -467,6 +480,7 @@ export const voiceStatusCapability = {
467
480
  // Hit the 35-min ceiling without seeing a terminal state — return the
468
481
  // latest snapshot we have so the agent + journal still have partial
469
482
  // context, but flag it as still in progress.
483
+ recordStatusOnce();
470
484
  return {
471
485
  output: `## Voice call status (still in progress after ${Math.round(VOICE_POLL_MAX_WAIT_MS / 60_000)} min)\n\n` +
472
486
  `Bland.ai upstream caps any single call at 30 min, so a call this long ` +
@@ -50,7 +50,11 @@ export class TradingEngine {
50
50
  if (!existing) {
51
51
  return { status: 'noop', reason: `No open ${req.symbol} position` };
52
52
  }
53
- const qty = req.qty ?? existing.qty;
53
+ // Clamp to the held size: an over-sized partial close just flattens the
54
+ // position rather than throwing 'only X held' out of applyFill (which the
55
+ // tool layer surfaced as a confusing generic error). You can never sell more
56
+ // than you hold, so flatten-on-over-size is the sensible interpretation.
57
+ const qty = Math.min(req.qty ?? existing.qty, existing.qty);
54
58
  const price = (await exchange.getPrice(req.symbol));
55
59
  if (price == null) {
56
60
  return { status: 'blocked', reason: `Exchange returned no price for ${req.symbol}` };
@@ -35,9 +35,12 @@ export class RiskEngine {
35
35
  reason: `Insufficient cash: order needs $${notional.toFixed(2)} but only $${portfolio.cashUsd.toFixed(2)} available`,
36
36
  };
37
37
  }
38
- // Projected position value after fill.
38
+ // Projected position value after fill. Value the existing holding at its
39
+ // cost basis (avgPriceUsd), consistent with the total-exposure loop below —
40
+ // valuing it at the incoming order price let a buy slip the cap after a
41
+ // price drop (and over-block after a rise).
39
42
  const existing = portfolio.getPosition(order.symbol);
40
- const projectedPositionUsd = (existing ? existing.qty * order.priceUsd : 0) + notional;
43
+ const projectedPositionUsd = (existing ? existing.qty * existing.avgPriceUsd : 0) + notional;
41
44
  if (projectedPositionUsd > this.config.maxPositionUsd) {
42
45
  return {
43
46
  allowed: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.29.7",
3
+ "version": "3.29.8",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {