@blockrun/franklin 3.49.1 → 3.49.2

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.
@@ -9,6 +9,7 @@
9
9
  import type { ModelClient } from './llm.js';
10
10
  import type { AgentConfig, Dialogue, StreamEvent } from './types.js';
11
11
  import type { Registry } from '../skills/registry.js';
12
+ import type { ParsedSkill } from '../skills/types.js';
12
13
  type EventEmitter = (event: StreamEvent) => void;
13
14
  interface CommandContext {
14
15
  history: Dialogue[];
@@ -24,6 +25,7 @@ interface CommandContext {
24
25
  interface CommandResult {
25
26
  handled: boolean;
26
27
  rewritten?: string;
28
+ skill?: ParsedSkill;
27
29
  }
28
30
  /**
29
31
  * Handle a slash command. Returns result indicating what happened.
@@ -1334,7 +1334,7 @@ export async function handleSlashCommand(input, ctx) {
1334
1334
  if (ctx.skillRegistry) {
1335
1335
  const skillResult = matchSkill(input, ctx.skillRegistry, ctx.skillVars ?? {});
1336
1336
  if (skillResult) {
1337
- return { handled: false, rewritten: skillResult.rewritten };
1337
+ return { handled: false, rewritten: skillResult.rewritten, skill: skillResult.skill };
1338
1338
  }
1339
1339
  }
1340
1340
  // Not a recognized command — suggest closest match
@@ -32,7 +32,7 @@ import { ToolCallRepair } from './repair/index.js';
32
32
  import { resetToolSessionState } from '../tools/index.js';
33
33
  import { CORE_TOOL_NAMES, dynamicToolsEnabled } from '../tools/tool-categories.js';
34
34
  import { createActivateToolCapability } from '../tools/activate.js';
35
- import { recordUsage, getLiveSpendUsd } from '../stats/tracker.js';
35
+ import { recordUsage, getLiveSpendUsd, runWithSpendScope } from '../stats/tracker.js';
36
36
  import { recordSessionUsage } from '../stats/session-tracker.js';
37
37
  import { appendAudit, extractLastUserPrompt } from '../stats/audit.js';
38
38
  import { logger, setDebugMode } from '../logger.js';
@@ -500,6 +500,11 @@ export function isWeakModel(model) {
500
500
  * Returns the accumulated conversation history.
501
501
  */
502
502
  export async function interactiveSession(config, getUserInput, onEvent, onAbortReady) {
503
+ // Each session gets its own live-spend counter so concurrent sessions in one
504
+ // serve process never count each other's USDC against their --max-spend.
505
+ return runWithSpendScope(() => runInteractiveSession(config, getUserInput, onEvent, onAbortReady));
506
+ }
507
+ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady) {
503
508
  // Clear module-level tool caches left over from a prior session in the same
504
509
  // process. Matters when Franklin is used as a library or driven by tests
505
510
  // that call interactiveSession() more than once — stale fileReadTracker /
@@ -594,6 +599,9 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
594
599
  const inputMux = createInputMultiplexer(getUserInput);
595
600
  const history = [];
596
601
  let lastUserInput = ''; // For /retry
602
+ // budget-cap-usd of the skill that kicked off this turn (`/name` invocation);
603
+ // kept across /retry, which replays the same skill prompt.
604
+ let turnSkillBudgetUsd;
597
605
  config.baseModel = config.model; // User's intended model — /model command updates this
598
606
  let turnFailedModels = new Set(); // Models that failed this turn (cleared each new turn)
599
607
  // ── Skills (file-loaded SKILL.md prompt-rewrite slash commands) ──
@@ -792,6 +800,8 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
792
800
  if (input === '')
793
801
  continue; // Empty input → re-prompt
794
802
  // ── Slash command dispatch ──
803
+ if (!input.startsWith('/'))
804
+ turnSkillBudgetUsd = undefined;
795
805
  if (input.startsWith('/')) {
796
806
  // /retry re-sends the last user message
797
807
  if (input === '/retry') {
@@ -814,6 +824,7 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
814
824
  });
815
825
  if (cmdResult.handled)
816
826
  continue;
827
+ turnSkillBudgetUsd = cmdResult.skill?.budgetCapUsd;
817
828
  if (cmdResult.rewritten)
818
829
  input = cmdResult.rewritten;
819
830
  }
@@ -1348,6 +1359,15 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1348
1359
  onAskUser: config.onAskUser,
1349
1360
  onApproval: config.approvalPromptFn,
1350
1361
  sessionId,
1362
+ maxSpendRemainingUsd: (() => {
1363
+ const cap = config.maxSpendUsd;
1364
+ const left = [];
1365
+ if (typeof cap === 'number' && Number.isFinite(cap) && cap > 0)
1366
+ left.push(cap - sessionCostUsd);
1367
+ if (turnSkillBudgetUsd !== undefined)
1368
+ left.push(turnSkillBudgetUsd - turnCostUsd);
1369
+ return left.length > 0 ? Math.max(0, Math.min(...left)) : undefined;
1370
+ })(),
1351
1371
  parentContext: {
1352
1372
  goal: lastUserInput?.slice(0, 200),
1353
1373
  recentFiles: [...readFileCache].slice(-10),
@@ -2693,6 +2713,18 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
2693
2713
  onEvent({ kind: 'turn_done', reason: 'cap_exceeded' });
2694
2714
  break;
2695
2715
  }
2716
+ // Skill budget: a `/name` skill with budget-cap-usd bounds the turn it
2717
+ // started. Checked after the tool results are in history, so stopping
2718
+ // here leaves a well-formed transcript.
2719
+ if (turnSkillBudgetUsd !== undefined && turnCostUsd >= turnSkillBudgetUsd) {
2720
+ logger.warn(`[franklin] Skill budget reached: $${turnCostUsd.toFixed(4)} ≥ $${turnSkillBudgetUsd.toFixed(2)} — ending turn`);
2721
+ onEvent({
2722
+ kind: 'text_delta',
2723
+ text: `\n\n_Skill budget reached: ${spendNote} ≥ cap $${turnSkillBudgetUsd.toFixed(2)}. Stopping this turn._\n`,
2724
+ });
2725
+ onEvent({ kind: 'turn_done', reason: 'budget' });
2726
+ break;
2727
+ }
2696
2728
  // Signature-based hard stop (3.15.30). The original 3.15.28 fired
2697
2729
  // on count alone (Bash 6× → break), which incorrectly killed
2698
2730
  // legitimate data-engineering work — the same Opus-4.7 session
@@ -134,13 +134,14 @@ export class StreamingExecutor {
134
134
  }
135
135
  return results;
136
136
  }
137
- async executeWithPermissions(invocation, pendingCount = 1, callStart = true // false for concurrent tools (already called in onToolReceived)
137
+ async executeWithPermissions(invocation, pendingCount = 1, callStart = true, // false for concurrent tools (already called in onToolReceived)
138
+ handlerOverride // nested (sub-agent) calls bring their own handler
138
139
  ) {
139
140
  // Canonicalize the tool name and normalize schema-typed values before any
140
141
  // hook, guard, or permission boundary. Otherwise an alias such as
141
142
  // `detach` or a boolean-like value such as `confirm: "true"` could be
142
143
  // authorized under a different shape than the handler later executes.
143
- let handler = this.handlers.get(invocation.name);
144
+ let handler = handlerOverride ?? this.handlers.get(invocation.name);
144
145
  if (!handler) {
145
146
  const attempted = invocation.name;
146
147
  const lower = attempted.toLowerCase();
@@ -234,13 +235,14 @@ export class StreamingExecutor {
234
235
  const preview = this.inputPreview(invocation);
235
236
  this.onStart(invocation.id, invocation.name, preview);
236
237
  }
237
- // Wire per-invocation progress to onProgress callback
238
- const progressScope = this.onProgress
239
- ? {
240
- ...this.scope,
241
- onProgress: (text) => this.onProgress(invocation.id, text),
242
- }
243
- : this.scope;
238
+ // Wire per-invocation progress to onProgress callback, and hand nested
239
+ // callers (sub-agents) this same pipeline so they cannot bypass it.
240
+ const progressScope = {
241
+ ...this.scope,
242
+ ...(this.onProgress ? { onProgress: (text) => this.onProgress(invocation.id, text) } : {}),
243
+ // callStart=false: nested calls report through the sub-agent, not as top-level UI rows.
244
+ runTool: (inv, h) => this.executeWithPermissions(inv, 1, false, h),
245
+ };
244
246
  try {
245
247
  // Track elapsed for slow-tool forensics. Verified 2026-05-04
246
248
  // from a real session: a 337.6s Bash error left no trace in
@@ -103,6 +103,14 @@ export interface ExecutionScope {
103
103
  * module-global session then.
104
104
  */
105
105
  sessionId?: string;
106
+ /**
107
+ * Run a nested tool call (sub-agent) through the SAME pipeline as a
108
+ * top-level call: hooks, SessionToolGuard (trade-plan gate), permissions,
109
+ * PreSpend, redaction and large-result persistence. Set by StreamingExecutor.
110
+ */
111
+ runTool?: (invocation: CapabilityInvocation, handler: CapabilityHandler) => Promise<CapabilityResult>;
112
+ /** USDC left under the session's --max-spend when this tool started. Absent = no cap. */
113
+ maxSpendRemainingUsd?: number;
106
114
  /** Context from parent agent — helps sub-agents avoid duplicate work */
107
115
  parentContext?: {
108
116
  goal?: string;
@@ -11,8 +11,11 @@
11
11
  */
12
12
  export declare function substituteVariables(body: string, vars: Record<string, string>, args: string): string;
13
13
  import type { Registry } from './registry.js';
14
+ import type { ParsedSkill } from './types.js';
14
15
  export interface SkillMatch {
15
16
  rewritten: string;
17
+ /** The invoked skill — its budget-cap-usd bounds the turn it kicks off. */
18
+ skill: ParsedSkill;
16
19
  }
17
20
  /**
18
21
  * Pure dispatch: given a slash-command input line, look up the skill in the
@@ -34,5 +34,5 @@ export function matchSkill(input, registry, vars) {
34
34
  return null;
35
35
  const args = space < 0 ? '' : input.slice(space + 1).trim();
36
36
  const rewritten = substituteVariables(skill.skill.body, vars, args);
37
- return { rewritten };
37
+ return { rewritten, skill: skill.skill };
38
38
  }
@@ -51,7 +51,9 @@ export declare function saveStats(stats: Stats): void;
51
51
  export declare function clearStats(): void;
52
52
  /** Flush stats to disk immediately (call on process exit) */
53
53
  export declare function flushStats(): void;
54
- /** Cumulative USDC recorded via recordUsage this process. */
54
+ /** Run `fn` with its own live-spend counter (one per agent session). */
55
+ export declare function runWithSpendScope<T>(fn: () => T): T;
56
+ /** USDC recorded via recordUsage in the current session scope (process-wide outside one). */
55
57
  export declare function getLiveSpendUsd(): number;
56
58
  /** Test helper: reset the live-spend accumulator. */
57
59
  export declare function resetLiveSpend(): void;
@@ -3,6 +3,7 @@
3
3
  * Records all requests with cost, tokens, and latency for stats display
4
4
  */
5
5
  import fs from 'node:fs';
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
7
  import path from 'node:path';
7
8
  import os from 'node:os';
8
9
  import { OPUS_PRICING } from '../pricing.js';
@@ -181,9 +182,19 @@ export function flushStats() {
181
182
  // execution to fold paid-tool spend into the --max-spend session ceiling, which
182
183
  // would otherwise only see LLM token cost. See src/agent/loop.ts.
183
184
  let liveSpendUsd = 0;
184
- /** Cumulative USDC recorded via recordUsage this process. */
185
+ // One serve process hosts many concurrent sessions (AgentHost). A single
186
+ // process-global counter made each session's deltas include the others'
187
+ // spend, so concurrent agents tripped each other's --max-spend caps. Each
188
+ // session runs inside its own scope; reads inside a scope see only that
189
+ // session's spend (including sub-agents and background calls it awaits).
190
+ const spendScope = new AsyncLocalStorage();
191
+ /** Run `fn` with its own live-spend counter (one per agent session). */
192
+ export function runWithSpendScope(fn) {
193
+ return spendScope.run({ usd: 0 }, fn);
194
+ }
195
+ /** USDC recorded via recordUsage in the current session scope (process-wide outside one). */
185
196
  export function getLiveSpendUsd() {
186
- return liveSpendUsd;
197
+ return spendScope.getStore()?.usd ?? liveSpendUsd;
187
198
  }
188
199
  /** Test helper: reset the live-spend accumulator. */
189
200
  export function resetLiveSpend() {
@@ -205,8 +216,12 @@ estimated = isKeyMode(),
205
216
  requestId) {
206
217
  // Count real spend BEFORE the test/audit gates — the --max-spend ceiling must
207
218
  // see every paid tool call even when history persistence is suppressed.
208
- if (Number.isFinite(costUsd) && costUsd > 0)
219
+ if (Number.isFinite(costUsd) && costUsd > 0) {
209
220
  liveSpendUsd += costUsd;
221
+ const scope = spendScope.getStore();
222
+ if (scope)
223
+ scope.usd += costUsd;
224
+ }
210
225
  // Same rationale as appendAudit — tests run in-process with
211
226
  // local/test* models and would otherwise mix into franklin-stats.json
212
227
  // history (verified: 8.4% of a real user's 1000-entry history was
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { Keypair, VersionedTransaction } from '@solana/web3.js';
19
19
  import { getOrCreateSolanaWallet, solanaKeyToBytes, } from '@blockrun/llm';
20
+ import { liveSwapCap, getLiveSwapCount, recordLiveSwap, largeSwapThresholdUsd } from './live-swap-cap.js';
20
21
  // ─── BlockRun Referral identity ───────────────────────────────────────────
21
22
  // Set up via referral.jup.ag. Owns ATAs for USDC, wSOL, JUP, USDT, etc. Every
22
23
  // swap routed through these tools deposits 20 bps of output to this wallet's
@@ -27,38 +28,8 @@ const BLOCKRUN_REFERRAL_FEE_BPS = 20; // 0.2% — Jupiter docs default; well bel
27
28
  const ULTRA_BASE = 'https://lite-api.jup.ag/ultra/v1';
28
29
  const ORDER_TIMEOUT_MS = 15_000;
29
30
  const EXECUTE_TIMEOUT_MS = 30_000;
30
- // ─── Session safety: cumulative live-swap counter ─────────────────────────
31
- // We removed the per-turn $-cap in v3.11.0 because it kept firing on legit
32
- // LLM workloads — but a live on-chain swap is irreversible, so a cap here is
33
- // different in kind. Default 10 swaps per Franklin process; user can override
34
- // via FRANKLIN_LIVE_SWAP_CAP env (set to 0 to disable). Resets on restart.
35
- const DEFAULT_LIVE_SWAP_CAP = 10;
36
- const liveSwapCap = (() => {
37
- const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
38
- if (!raw)
39
- return DEFAULT_LIVE_SWAP_CAP;
40
- const n = Number(raw);
41
- if (!Number.isFinite(n))
42
- return DEFAULT_LIVE_SWAP_CAP;
43
- if (n <= 0)
44
- return Infinity;
45
- return Math.floor(n);
46
- })();
47
- let liveSwapCount = 0;
48
- // ─── Large-swap warning threshold ────────────────────────────────────────
49
- // USD value above which we surface a "Large swap" line in the AskUser
50
- // confirm — only computable when input is a known stablecoin. Override via
51
- // FRANKLIN_LIVE_SWAP_WARN_USD env (default $20).
52
- const DEFAULT_LARGE_SWAP_USD = 20;
53
- const largeSwapThresholdUsd = (() => {
54
- const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
55
- if (!raw)
56
- return DEFAULT_LARGE_SWAP_USD;
57
- const n = Number(raw);
58
- if (!Number.isFinite(n) || n < 0)
59
- return DEFAULT_LARGE_SWAP_USD;
60
- return n;
61
- })();
31
+ // Live-swap session cap + large-swap warning threshold live in ./live-swap-cap.ts
32
+ // (one counter shared by every swap venue).
62
33
  const STABLECOIN_MINTS = new Set([
63
34
  'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
64
35
  'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB', // USDT
@@ -257,9 +228,9 @@ async function executeJupiterQuote(input) {
257
228
  }
258
229
  async function executeJupiterSwapUnsafeReference(input, ctx) {
259
230
  // Session-cap pre-check (cheapest, fail fast).
260
- if (liveSwapCount >= liveSwapCap) {
231
+ if (getLiveSwapCount() >= liveSwapCap) {
261
232
  return {
262
- output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). ` +
233
+ output: `Live-swap session cap reached (${getLiveSwapCount()}/${liveSwapCap}). ` +
263
234
  `Stopping to protect your wallet — this is a deliberate guardrail, not an error in your prompt.\n\n` +
264
235
  `To raise: \`FRANKLIN_LIVE_SWAP_CAP=20 franklin\` (or 0 to disable).\n` +
265
236
  `To continue with a fresh count: restart Franklin (\`exit\` then re-launch).`,
@@ -329,7 +300,7 @@ async function executeJupiterSwapUnsafeReference(input, ctx) {
329
300
  else if (usdEst == null) {
330
301
  sections.push('', `Note: input is not a stablecoin, so I cannot price-check this in USD before signing. Verify the output amount matches your intent.`);
331
302
  }
332
- sections.push('', `Wallet: ${walletAddress}`, `Live-swap session count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
303
+ sections.push('', `Wallet: ${walletAddress}`, `Live-swap session count: ${getLiveSwapCount()}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
333
304
  const answer = await ctx.onAskUser(sections.join('\n'), ['Confirm', 'Cancel']);
334
305
  if (answer.toLowerCase() !== 'confirm') {
335
306
  return { output: 'Swap cancelled by user.' };
@@ -376,7 +347,7 @@ async function executeJupiterSwapUnsafeReference(input, ctx) {
376
347
  isError: true,
377
348
  };
378
349
  }
379
- liveSwapCount += 1;
350
+ recordLiveSwap();
380
351
  const sig = exec.signature ?? '<unknown>';
381
352
  const explorer = `https://solscan.io/tx/${sig}`;
382
353
  return {
@@ -385,7 +356,7 @@ async function executeJupiterSwapUnsafeReference(input, ctx) {
385
356
  formatQuote(order),
386
357
  `Signature: ${sig}`,
387
358
  explorer,
388
- `(Session live-swap count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`,
359
+ `(Session live-swap count: ${getLiveSwapCount()}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`,
389
360
  ].join('\n'),
390
361
  };
391
362
  }
@@ -0,0 +1,7 @@
1
+ export declare const liveSwapCap: number;
2
+ export declare function getLiveSwapCount(): number;
3
+ /** Call once per swap that actually submitted on-chain. */
4
+ export declare function recordLiveSwap(): void;
5
+ /** Test helper. */
6
+ export declare function resetLiveSwapCount(): void;
7
+ export declare const largeSwapThresholdUsd: number;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Process-wide live-swap safety cap, shared by every swap venue.
3
+ *
4
+ * A live on-chain swap is irreversible, so it gets a hard count cap even
5
+ * though the per-turn $-cap was removed in v3.11.0. Default 10 swaps per
6
+ * Franklin process across ALL venues (Jupiter, 0x Base, 0x gasless) —
7
+ * previously each venue kept its own counter, so the effective cap was 30.
8
+ * Override via FRANKLIN_LIVE_SWAP_CAP (0 disables). Resets on restart.
9
+ */
10
+ const DEFAULT_LIVE_SWAP_CAP = 10;
11
+ export const liveSwapCap = (() => {
12
+ const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
13
+ if (!raw)
14
+ return DEFAULT_LIVE_SWAP_CAP;
15
+ const n = Number(raw);
16
+ if (!Number.isFinite(n))
17
+ return DEFAULT_LIVE_SWAP_CAP;
18
+ if (n <= 0)
19
+ return Infinity;
20
+ return Math.floor(n);
21
+ })();
22
+ let count = 0;
23
+ export function getLiveSwapCount() {
24
+ return count;
25
+ }
26
+ /** Call once per swap that actually submitted on-chain. */
27
+ export function recordLiveSwap() {
28
+ count += 1;
29
+ }
30
+ /** Test helper. */
31
+ export function resetLiveSwapCount() {
32
+ count = 0;
33
+ }
34
+ /**
35
+ * USD value above which the confirm prompt shows a "Large swap" line (only
36
+ * computable for stablecoin inputs). Override via FRANKLIN_LIVE_SWAP_WARN_USD.
37
+ */
38
+ const DEFAULT_LARGE_SWAP_USD = 20;
39
+ export const largeSwapThresholdUsd = (() => {
40
+ const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
41
+ if (!raw)
42
+ return DEFAULT_LARGE_SWAP_USD;
43
+ const n = Number(raw);
44
+ if (!Number.isFinite(n) || n < 0)
45
+ return DEFAULT_LARGE_SWAP_USD;
46
+ return n;
47
+ })();
@@ -4,6 +4,8 @@
4
4
  import { ModelClient } from '../agent/llm.js';
5
5
  import { assembleInstructions } from '../agent/context.js';
6
6
  import { FREE_DEFAULT_MODEL, isFreeModelId } from '../free-models.js';
7
+ import { recordUsage, getLiveSpendUsd } from '../stats/tracker.js';
8
+ import { estimateCost } from '../pricing.js';
7
9
  // These will be injected at registration time
8
10
  let registeredApiUrl = '';
9
11
  let registeredChain = 'base';
@@ -76,12 +78,26 @@ async function execute(input, ctx) {
76
78
  const deadline = Date.now() + SUB_AGENT_TIMEOUT_MS;
77
79
  let turn = 0;
78
80
  let finalText = '';
81
+ // Everything the child spends (its LLM calls via recordUsage below, plus any
82
+ // paid tools it runs) lands in the session's live-spend counter, which the
83
+ // parent loop folds into --max-spend. This bounds the child mid-run too.
84
+ const spendAtStart = getLiveSpendUsd();
85
+ const label = description || 'sub-agent';
79
86
  while (turn < maxTurns) {
80
87
  if (Date.now() > deadline) {
81
- return { output: `[${description || 'sub-agent'}] timed out after 5 minutes (${turn} turns completed).`, isError: true };
88
+ return { output: `[${label}] timed out after 5 minutes (${turn} turns completed).`, isError: true };
89
+ }
90
+ const spent = getLiveSpendUsd() - spendAtStart;
91
+ if (ctx.maxSpendRemainingUsd !== undefined && spent >= ctx.maxSpendRemainingUsd) {
92
+ return {
93
+ output: `[${label}] stopped: spent $${spent.toFixed(4)}, which reaches the session's remaining --max-spend budget ($${ctx.maxSpendRemainingUsd.toFixed(4)}).` +
94
+ (finalText ? `\n\nPartial result:\n${finalText}` : ''),
95
+ isError: true,
96
+ };
82
97
  }
83
98
  turn++;
84
- const { content: parts } = await client.complete({
99
+ const callStart = Date.now();
100
+ const { content: parts, usage } = await client.complete({
85
101
  model: subModel,
86
102
  messages: history,
87
103
  system: systemPrompt,
@@ -89,6 +105,8 @@ async function execute(input, ctx) {
89
105
  max_tokens: 16384,
90
106
  stream: true,
91
107
  }, ctx.abortSignal);
108
+ const paidUsd = client.getLastPaidUsd();
109
+ recordUsage(subModel, usage.inputTokens, usage.outputTokens, paidUsd > 0 ? paidUsd : estimateCost(subModel, usage.inputTokens, usage.outputTokens, 1), Date.now() - callStart, false, paidUsd <= 0);
92
110
  history.push({ role: 'assistant', content: parts });
93
111
  // Collect text and invocations
94
112
  const invocations = [];
@@ -107,9 +125,14 @@ async function execute(input, ctx) {
107
125
  for (const inv of invocations) {
108
126
  const handler = capabilityMap.get(inv.name);
109
127
  let result;
110
- if (handler) {
128
+ if (handler && !ctx.runTool) {
129
+ // Outside the agent loop there is no permission/guard pipeline to run
130
+ // through. Fail closed rather than let the child act unchecked.
131
+ result = { output: `Tool ${inv.name} unavailable: sub-agent is not running inside an agent session.`, isError: true };
132
+ }
133
+ else if (handler) {
111
134
  try {
112
- result = await handler.execute(inv.input, ctx);
135
+ result = await ctx.runTool(inv, handler);
113
136
  }
114
137
  catch (err) {
115
138
  result = {
@@ -130,7 +153,6 @@ async function execute(input, ctx) {
130
153
  }
131
154
  history.push({ role: 'user', content: outcomes });
132
155
  }
133
- const label = description || 'sub-agent';
134
156
  return {
135
157
  output: finalText || `[${label}] completed after ${turn} turn(s) with no text output.`,
136
158
  };
@@ -29,6 +29,7 @@ import { loadConfig } from '../commands/config.js';
29
29
  import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
30
30
  import { loadChain, VERSION } from '../config.js';
31
31
  import { appendSwap } from '../stats/swap-log.js';
32
+ import { liveSwapCap, getLiveSwapCount, recordLiveSwap, largeSwapThresholdUsd } from './live-swap-cap.js';
32
33
  // ─── BlockRun affiliate identity on Base ─────────────────────────────────
33
34
  // Reuses the existing BlockRun ops wallet that already receives x402
34
35
  // settlements on Base. Every swap routed through these tools deposits 20
@@ -52,30 +53,8 @@ function resolveBaseRpcUrl() {
52
53
  loadConfig()['base-rpc-url'] ||
53
54
  DEFAULT_BASE_RPC);
54
55
  }
55
- // ─── Session safety: cumulative live-swap counter ─────────────────────────
56
- const DEFAULT_LIVE_SWAP_CAP = 10;
57
- const liveSwapCap = (() => {
58
- const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
59
- if (!raw)
60
- return DEFAULT_LIVE_SWAP_CAP;
61
- const n = Number(raw);
62
- if (!Number.isFinite(n))
63
- return DEFAULT_LIVE_SWAP_CAP;
64
- if (n <= 0)
65
- return Infinity;
66
- return Math.floor(n);
67
- })();
68
- let liveSwapCount = 0;
69
- const DEFAULT_LARGE_SWAP_USD = 20;
70
- const largeSwapThresholdUsd = (() => {
71
- const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
72
- if (!raw)
73
- return DEFAULT_LARGE_SWAP_USD;
74
- const n = Number(raw);
75
- if (!Number.isFinite(n) || n < 0)
76
- return DEFAULT_LARGE_SWAP_USD;
77
- return n;
78
- })();
56
+ // Live-swap session cap + large-swap warning threshold live in ./live-swap-cap.ts
57
+ // (one counter shared by every swap venue).
79
58
  // ─── Base token map ──────────────────────────────────────────────────────
80
59
  // EVM addresses are case-sensitive in some libraries — store as checksum.
81
60
  const NATIVE_ETH = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
@@ -256,9 +235,9 @@ async function executeBase0xQuote(input, ctx) {
256
235
  }
257
236
  // ─── Swap (full execute) ─────────────────────────────────────────────────
258
237
  async function executeBase0xSwapUnsafeReference(input, ctx) {
259
- if (liveSwapCount >= liveSwapCap) {
238
+ if (getLiveSwapCount() >= liveSwapCap) {
260
239
  return {
261
- output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). Stopping to protect your wallet.\n` +
240
+ output: `Live-swap session cap reached (${getLiveSwapCount()}/${liveSwapCap}). Stopping to protect your wallet.\n` +
262
241
  `Override with FRANKLIN_LIVE_SWAP_CAP=20 (or 0 to disable), or restart Franklin to reset.`,
263
242
  isError: true,
264
243
  };
@@ -314,7 +293,7 @@ async function executeBase0xSwapUnsafeReference(input, ctx) {
314
293
  else if (usdEst == null) {
315
294
  sections.push('', `Note: input is not a stablecoin, so I cannot price-check this in USD before signing. Verify the output amount matches your intent.`);
316
295
  }
317
- sections.push('', `Wallet: ${wallet.address}`, `Live-swap session count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
296
+ sections.push('', `Wallet: ${wallet.address}`, `Live-swap session count: ${getLiveSwapCount()}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
318
297
  const answer = await ctx.onAskUser(sections.join('\n'), ['Confirm', 'Cancel']);
319
298
  if (answer.toLowerCase() !== 'confirm') {
320
299
  return { output: 'Swap cancelled by user.' };
@@ -408,7 +387,7 @@ async function executeBase0xSwapUnsafeReference(input, ctx) {
408
387
  isError: true,
409
388
  };
410
389
  }
411
- liveSwapCount += 1;
390
+ recordLiveSwap();
412
391
  const explorer = `https://basescan.org/tx/${txHash}`;
413
392
  // Confirm on-chain before recording: a submitted tx can still revert (e.g.
414
393
  // slippage floor exceeded), and the swap log feeds the desktop wallet
@@ -450,7 +429,7 @@ async function executeBase0xSwapUnsafeReference(input, ctx) {
450
429
  formatQuoteText(quote),
451
430
  `Tx hash: ${txHash}`,
452
431
  explorer,
453
- `(Session live-swap count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`,
432
+ `(Session live-swap count: ${getLiveSwapCount()}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`,
454
433
  ].join('\n'),
455
434
  };
456
435
  }
@@ -27,6 +27,7 @@ import { gatewayBase, gatewayHeaders } from '../payments/auth-mode.js';
27
27
  import { VERSION } from '../config.js';
28
28
  import { appendSwap } from '../stats/swap-log.js';
29
29
  import { logger } from '../logger.js';
30
+ import { liveSwapCap, getLiveSwapCount, recordLiveSwap, largeSwapThresholdUsd } from './live-swap-cap.js';
30
31
  // ─── Constants ────────────────────────────────────────────────────────────
31
32
  const ZEROX_GATEWAY_PATH = '/v1/zerox/gasless';
32
33
  const QUOTE_TIMEOUT_MS = 30_000;
@@ -36,30 +37,8 @@ const MAX_STATUS_POLL_MS = 60_000; // hard ceiling on confirmation wait
36
37
  const STATUS_POLL_INTERVAL_MS = 3_000;
37
38
  // 0x SignatureType.EIP712 = 2 (per @0x/utils/signature.ts)
38
39
  const SIGNATURE_TYPE_EIP712 = 2;
39
- // Session safety guards — same pattern as zerox-base.ts
40
- const DEFAULT_LIVE_SWAP_CAP = 10;
41
- const liveSwapCap = (() => {
42
- const raw = process.env.FRANKLIN_LIVE_SWAP_CAP;
43
- if (!raw)
44
- return DEFAULT_LIVE_SWAP_CAP;
45
- const n = Number(raw);
46
- if (!Number.isFinite(n))
47
- return DEFAULT_LIVE_SWAP_CAP;
48
- if (n <= 0)
49
- return Infinity;
50
- return Math.floor(n);
51
- })();
52
- let liveSwapCount = 0;
53
- const DEFAULT_LARGE_SWAP_USD = 20;
54
- const largeSwapThresholdUsd = (() => {
55
- const raw = process.env.FRANKLIN_LIVE_SWAP_WARN_USD;
56
- if (!raw)
57
- return DEFAULT_LARGE_SWAP_USD;
58
- const n = Number(raw);
59
- if (!Number.isFinite(n) || n < 0)
60
- return DEFAULT_LARGE_SWAP_USD;
61
- return n;
62
- })();
40
+ // Live-swap session cap + large-swap warning threshold live in ./live-swap-cap.ts
41
+ // (one counter shared by every swap venue).
63
42
  // ─── Base token map (mirror zerox-base.ts) ────────────────────────────────
64
43
  const SYMBOL_TO_ADDRESS = {
65
44
  WETH: '0x4200000000000000000000000000000000000006',
@@ -251,9 +230,9 @@ async function pollUntilDone(tradeHash, ctx) {
251
230
  return last;
252
231
  }
253
232
  async function executeBase0xGaslessSwapUnsafeReference(input, ctx) {
254
- if (liveSwapCount >= liveSwapCap) {
233
+ if (getLiveSwapCount() >= liveSwapCap) {
255
234
  return {
256
- output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). Stopping to protect your wallet.\n` +
235
+ output: `Live-swap session cap reached (${getLiveSwapCount()}/${liveSwapCap}). Stopping to protect your wallet.\n` +
257
236
  `Override with FRANKLIN_LIVE_SWAP_CAP=20 (or 0 to disable), or restart Franklin to reset.`,
258
237
  isError: true,
259
238
  };
@@ -324,7 +303,7 @@ async function executeBase0xGaslessSwapUnsafeReference(input, ctx) {
324
303
  else if (usdEst == null) {
325
304
  sections.push('', `Note: input is not a stablecoin, so I cannot price-check this in USD before signing. Verify the output amount matches your intent.`);
326
305
  }
327
- sections.push('', `Wallet: ${wallet.address}`, `Live-swap session count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
306
+ sections.push('', `Wallet: ${wallet.address}`, `Live-swap session count: ${getLiveSwapCount()}/${liveSwapCap === Infinity ? '∞' : liveSwapCap}`);
328
307
  const answer = await ctx.onAskUser(sections.join('\n'), ['Confirm', 'Cancel']);
329
308
  if (answer.toLowerCase() !== 'confirm') {
330
309
  return { output: 'Swap cancelled by user.' };
@@ -404,7 +383,7 @@ async function executeBase0xGaslessSwapUnsafeReference(input, ctx) {
404
383
  }
405
384
  // Step 6 — poll status until confirmed / failed / timeout.
406
385
  const final = await pollUntilDone(submitRes.tradeHash, ctx);
407
- liveSwapCount += 1;
386
+ recordLiveSwap();
408
387
  const onChainHash = final.transactions?.[0]?.hash;
409
388
  const explorer = onChainHash ? `https://basescan.org/tx/${onChainHash}` : null;
410
389
  const statusLine = final.status === 'confirmed' || final.status === 'succeeded'
@@ -437,7 +416,7 @@ async function executeBase0xGaslessSwapUnsafeReference(input, ctx) {
437
416
  lines.push(`On-chain tx: ${onChainHash}`);
438
417
  if (explorer)
439
418
  lines.push(explorer);
440
- lines.push(`(Session live-swap count: ${liveSwapCount}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`);
419
+ lines.push(`(Session live-swap count: ${getLiveSwapCount()}/${liveSwapCap === Infinity ? '∞' : liveSwapCap})`);
441
420
  return {
442
421
  output: lines.join('\n'),
443
422
  isError: final.status === 'failed',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.1",
3
+ "version": "3.49.2",
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": {