@blockrun/franklin 3.49.0 → 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.
- package/README.md +17 -8
- package/dist/agent/commands.d.ts +2 -0
- package/dist/agent/commands.js +1 -1
- package/dist/agent/loop.js +33 -1
- package/dist/agent/streaming-executor.js +11 -9
- package/dist/agent/types.d.ts +8 -0
- package/dist/skills/invoke.d.ts +3 -0
- package/dist/skills/invoke.js +1 -1
- package/dist/stats/tracker.d.ts +3 -1
- package/dist/stats/tracker.js +18 -3
- package/dist/tools/imagegen.js +4 -2
- package/dist/tools/jupiter.js +8 -37
- package/dist/tools/live-swap-cap.d.ts +7 -0
- package/dist/tools/live-swap-cap.js +47 -0
- package/dist/tools/musicgen.js +50 -4
- package/dist/tools/subagent.js +27 -5
- package/dist/tools/videogen.js +5 -2
- package/dist/tools/zerox-base.js +8 -29
- package/dist/tools/zerox-gasless.js +8 -29
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -74,7 +74,7 @@ franklin
|
|
|
74
74
|
# Pick ONE — a USDC wallet, or a prepaid API key.
|
|
75
75
|
|
|
76
76
|
# a) Wallet — no signup, no account
|
|
77
|
-
franklin setup solana # or: franklin setup base
|
|
77
|
+
franklin setup solana # or: franklin setup base / franklin setup arc
|
|
78
78
|
franklin balance # show address + USDC balance
|
|
79
79
|
|
|
80
80
|
# b) API key — sign up and top up at https://user.blockrun.ai
|
|
@@ -163,12 +163,20 @@ interchangeable. Everything else about the agent is identical.
|
|
|
163
163
|
| --- | --- | --- |
|
|
164
164
|
| Setup | `franklin setup solana` | Sign up, top up, `franklin login brk_...` |
|
|
165
165
|
| Account required | No | Yes |
|
|
166
|
-
| Crypto required | Yes — USDC on Solana or
|
|
166
|
+
| Crypto required | Yes — USDC on Solana, Base or Arc | No — top up with a card |
|
|
167
167
|
| Settlement | On-chain, per call, via [x402](https://x402.org) | Against a prepaid balance |
|
|
168
|
-
| Gateway | `sol.blockrun.ai` / `blockrun.ai` | `api.blockrun.ai` |
|
|
168
|
+
| Gateway | `sol.blockrun.ai` / `blockrun.ai` / `arc.blockrun.ai` | `api.blockrun.ai` |
|
|
169
169
|
| Where the money lives | A wallet only you hold the key to | Your BlockRun account |
|
|
170
170
|
| Spend visibility | `franklin stats` — exact settled amounts | `franklin balance` + [dashboard](https://user.blockrun.ai/dashboard); exact except chat |
|
|
171
171
|
|
|
172
|
+
**Three wallet chains.** Solana (the default), Base, or Circle's [Arc](https://arc.network)
|
|
173
|
+
(chain 5042). Switch with `franklin solana` / `franklin base` / `franklin arc`, or the chain
|
|
174
|
+
buttons on the panel's wallet page. Base and Arc share one EVM key, so the same address
|
|
175
|
+
receives USDC on both; Solana has its own key. Card purchase (Coinbase Onramp) funds Base
|
|
176
|
+
and Solana only — on Arc, send USDC to the address directly. `franklin balance` always
|
|
177
|
+
reports the active chain's USDC, so after switching to Arc it shows your Arc balance, not
|
|
178
|
+
Base's. Arc's gateway adds models after Base does; the picker lists what Arc serves today.
|
|
179
|
+
|
|
172
180
|
**The wallet is still Franklin's identity.** Memory, the trading journal and goals are
|
|
173
181
|
keyed to it, and the wallet route is the one that needs nothing from us — no signup, no
|
|
174
182
|
KYC, no account to suspend. The API key exists because not everyone wants to hold crypto
|
|
@@ -448,7 +456,7 @@ No single model is best at everything. Sonnet writes better code, Gemini handles
|
|
|
448
456
|
|
|
449
457
|
### 🔐 Wallet is identity
|
|
450
458
|
|
|
451
|
-
No email. No phone. No KYC. Your Solana or
|
|
459
|
+
No email. No phone. No KYC. Your Solana, Base or Arc address is your account — portable, permissionless, global. A wallet requires only USDC. (Prefer an account and a card? [Two ways to pay](#two-ways-to-pay) — the key route exists, it just is not the one that makes the agent sovereign.)
|
|
452
460
|
|
|
453
461
|
</td>
|
|
454
462
|
</tr>
|
|
@@ -495,7 +503,7 @@ Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result lo
|
|
|
495
503
|
Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, NVIDIA free tier. One wallet, one interface, automatic fallback.
|
|
496
504
|
|
|
497
505
|
**💳 x402 micropayments (YOPO)**
|
|
498
|
-
HTTP 402 native. Every paid action is a signed USDC micropayment
|
|
506
|
+
HTTP 402 native. Every paid action is a signed USDC micropayment — an EIP-712 authorization on Base and Arc, a signed SPL transfer on Solana. Non-custodial: your keys never leave your machine. YOPO: you pay only for outcomes.
|
|
499
507
|
|
|
500
508
|
**🧠 Learned model router**
|
|
501
509
|
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->82<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
|
|
@@ -569,7 +577,7 @@ like `opus`, `gpt` and `grok` keep their current targets.
|
|
|
569
577
|
│ <!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
|
|
570
578
|
├──────────────────────────────────────────────────────────────┤
|
|
571
579
|
│ x402 Micropayment Protocol │
|
|
572
|
-
│ HTTP 402 · USDC on Solana &
|
|
580
|
+
│ HTTP 402 · USDC on Solana, Base & Arc · signed payloads │
|
|
573
581
|
└──────────────────────────────────────────────────────────────┘
|
|
574
582
|
│
|
|
575
583
|
▼
|
|
@@ -611,7 +619,7 @@ src/
|
|
|
611
619
|
├── ui/ Ink-based terminal UI
|
|
612
620
|
├── proxy/ Payment proxy for external tools
|
|
613
621
|
├── router/ Learned model router (<!-- br:models.chatVisible@live -->82<!-- /br:models.chatVisible@live --> models, Elo scoring)
|
|
614
|
-
├── wallet/ Wallet management (Base + Solana)
|
|
622
|
+
├── wallet/ Wallet management (Base/Arc + Solana)
|
|
615
623
|
├── mcp/ MCP server auto-discovery
|
|
616
624
|
└── commands/ CLI subcommands
|
|
617
625
|
```
|
|
@@ -727,7 +735,8 @@ Franklin uses [BlockRun Model Core](https://github.com/BlockRunAI/model-catalog)
|
|
|
727
735
|
for model metadata, picker policy and price estimates. The runtime dependency
|
|
728
736
|
is pinned to an immutable commit. On refresh, Franklin reads the public policy
|
|
729
737
|
snapshot and the active gateway's catalog, so new models and prices can appear
|
|
730
|
-
without a Franklin release. Base, Solana and API accounts have separate caches.
|
|
738
|
+
without a Franklin release. Base, Solana, Arc and API accounts have separate caches.
|
|
739
|
+
Arc reads Base's policy and offline snapshot, with live rows from `arc.blockrun.ai`.
|
|
731
740
|
The default picker shows Auto and curated groups; other available chat models
|
|
732
741
|
remain accessible through +more / Ctrl+A.
|
|
733
742
|
|
package/dist/agent/commands.d.ts
CHANGED
|
@@ -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.
|
package/dist/agent/commands.js
CHANGED
|
@@ -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
|
package/dist/agent/loop.js
CHANGED
|
@@ -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
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
: this.
|
|
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
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -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;
|
package/dist/skills/invoke.d.ts
CHANGED
|
@@ -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
|
package/dist/skills/invoke.js
CHANGED
|
@@ -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
|
}
|
package/dist/stats/tracker.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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;
|
package/dist/stats/tracker.js
CHANGED
|
@@ -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
|
-
|
|
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
|
package/dist/tools/imagegen.js
CHANGED
|
@@ -527,7 +527,7 @@ function buildExecute(deps) {
|
|
|
527
527
|
? `\n\nOpen with: open ${savedPaths[0]}`
|
|
528
528
|
: `\n\nOpen with: open ${savedPaths.join(' ')}`;
|
|
529
529
|
return {
|
|
530
|
-
output: `${header}${revisedPrompt}${openHint}${contentSummary}`,
|
|
530
|
+
output: `${header}\nPrompt sent: ${chosenPrompt}${revisedPrompt}${openHint}${contentSummary}`,
|
|
531
531
|
};
|
|
532
532
|
}
|
|
533
533
|
catch (err) {
|
|
@@ -662,7 +662,9 @@ export function createImageGenCapability(deps = {}) {
|
|
|
662
662
|
input_schema: {
|
|
663
663
|
type: 'object',
|
|
664
664
|
properties: {
|
|
665
|
-
prompt: { type: 'string', description: '
|
|
665
|
+
prompt: { type: 'string', description: 'Self-contained text description of the image to generate, or edit instructions when a reference image is provided. ' +
|
|
666
|
+
'The image model sees ONLY this text, never the conversation: when the user refers to earlier messages ("these numbers", "that chart"), ' +
|
|
667
|
+
'write those details (figures, names, labels, quoted text) into the prompt verbatim. Never invent data the user did not give.' },
|
|
666
668
|
output_path: { type: 'string', description: 'Where to save the image. Default: generated-<timestamp>.png in working directory. With n>1, a -1/-2/... suffix is appended before the extension.' },
|
|
667
669
|
size: { type: 'string', description: 'Image size. gpt-image-1/2: 1024x1024, 1536x1024, 1024x1536. google/nano-banana: 1024x1024. google/nano-banana-pro: 1024x1024, 2048x2048, 4096x4096. Default: 1024x1024. Note: openai/gpt-image-2 is forced to 1024x1024 (other sizes time out at the gateway).' },
|
|
668
670
|
model: { type: 'string', description: 'Image model to use. Default: openai/gpt-image-1 (text-to-image) / openai/gpt-image-2 (image-to-image).' },
|
package/dist/tools/jupiter.js
CHANGED
|
@@ -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
|
-
//
|
|
31
|
-
//
|
|
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 (
|
|
231
|
+
if (getLiveSwapCount() >= liveSwapCap) {
|
|
261
232
|
return {
|
|
262
|
-
output: `Live-swap session cap reached (${
|
|
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: ${
|
|
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
|
-
|
|
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: ${
|
|
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
|
+
})();
|
package/dist/tools/musicgen.js
CHANGED
|
@@ -23,6 +23,7 @@ import { isWalletKeyPath } from './sensitive-paths.js';
|
|
|
23
23
|
import { findModel, estimateCostUsd } from '../gateway-models.js';
|
|
24
24
|
import { recordUsage } from '../stats/tracker.js';
|
|
25
25
|
import { noChargeNote } from '../payments/billing-copy.js';
|
|
26
|
+
import { pollImageJob } from './imagegen.js';
|
|
26
27
|
const DEFAULT_MODEL = 'minimax/music-2.5+';
|
|
27
28
|
// Flat per-track price for the default model — already margin-inclusive
|
|
28
29
|
// ($0.15/track × 1.05 gateway margin). Fallback when the catalog is unavailable.
|
|
@@ -111,8 +112,9 @@ function buildExecute(deps) {
|
|
|
111
112
|
headers,
|
|
112
113
|
body,
|
|
113
114
|
});
|
|
115
|
+
let paymentHeaders = null;
|
|
114
116
|
if (response.status === 402 && walletMayPay(headers)) {
|
|
115
|
-
|
|
117
|
+
paymentHeaders = await signPayment(response, chain, endpoint);
|
|
116
118
|
if (!paymentHeaders) {
|
|
117
119
|
return { output: 'Payment failed. Check wallet balance with: franklin balance', isError: true };
|
|
118
120
|
}
|
|
@@ -130,7 +132,48 @@ function buildExecute(deps) {
|
|
|
130
132
|
isError: true,
|
|
131
133
|
};
|
|
132
134
|
}
|
|
133
|
-
|
|
135
|
+
let result = (await response.json());
|
|
136
|
+
// Slow tracks outrun the gateway's inline window: it answers 202 +
|
|
137
|
+
// poll_url and settles on the first completed poll, so nothing is charged
|
|
138
|
+
// until then. Same contract (and same signed header on each poll) as the
|
|
139
|
+
// ImageGen async path.
|
|
140
|
+
if (response.status === 202 && result.poll_url) {
|
|
141
|
+
const pollEndpoint = result.poll_url.startsWith('http')
|
|
142
|
+
? result.poll_url
|
|
143
|
+
: `${new URL(apiUrl).origin}${result.poll_url}`;
|
|
144
|
+
clearTimeout(timeout);
|
|
145
|
+
let outcome = await pollImageJob(pollEndpoint, paymentHeaders ? { ...headers, ...paymentHeaders } : headers, controller.signal);
|
|
146
|
+
// The poll may refuse the POST's authorization: the gateway builds the
|
|
147
|
+
// poll's requirements with a longer timeout than the music POST's, and a
|
|
148
|
+
// strict facilitator (Circle, on Arc) rejects the mismatch as
|
|
149
|
+
// invalid_payment_requirements. The poll publishes its own 402 challenge
|
|
150
|
+
// and accepts a fresh signature from the same wallet, so sign that one.
|
|
151
|
+
// The job settles once, on the first completed poll: no double charge.
|
|
152
|
+
if (outcome.kind === 'poll_http_error' && outcome.status === 402 && paymentHeaders && walletMayPay(headers)) {
|
|
153
|
+
const challenge = await fetch(pollEndpoint, { method: 'GET', headers, signal: controller.signal });
|
|
154
|
+
const fresh = challenge.status === 402 ? await signPayment(challenge, chain, pollEndpoint) : null;
|
|
155
|
+
if (fresh) {
|
|
156
|
+
outcome = await pollImageJob(pollEndpoint, { ...headers, ...fresh }, controller.signal);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (outcome.kind === 'failed') {
|
|
160
|
+
return {
|
|
161
|
+
output: `Music generation failed upstream: ${JSON.stringify(outcome.error ?? '').slice(0, 240)}. ${noChargeNote()}`,
|
|
162
|
+
isError: true,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
if (outcome.kind === 'poll_http_error') {
|
|
166
|
+
return { output: `Music poll failed (${outcome.status}): ${outcome.bodyPreview}`, isError: true };
|
|
167
|
+
}
|
|
168
|
+
if (outcome.kind === 'timed_out') {
|
|
169
|
+
return {
|
|
170
|
+
output: 'Music generation was queued but did not complete within 5 minutes. ' +
|
|
171
|
+
'The gateway only charges when a poll sees the finished track.',
|
|
172
|
+
isError: true,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
result = outcome.body;
|
|
176
|
+
}
|
|
134
177
|
const track = result.data?.[0];
|
|
135
178
|
if (!track?.url) {
|
|
136
179
|
return { output: 'No track URL returned from API', isError: true };
|
|
@@ -189,7 +232,8 @@ function buildExecute(deps) {
|
|
|
189
232
|
}
|
|
190
233
|
}
|
|
191
234
|
return {
|
|
192
|
-
output: `Track saved to ${outPath} (${sizeMB}MB, ${dur}s, ${musicModel})\n
|
|
235
|
+
output: `Track saved to ${outPath} (${sizeMB}MB, ${dur}s, ${musicModel})\n` +
|
|
236
|
+
`Prompt sent: ${prompt}\n\n` +
|
|
193
237
|
`Open with: open ${outPath}${lyricsPreview}${contentSummary}`,
|
|
194
238
|
};
|
|
195
239
|
}
|
|
@@ -272,7 +316,9 @@ export function createMusicGenCapability(deps = {}) {
|
|
|
272
316
|
input_schema: {
|
|
273
317
|
type: 'object',
|
|
274
318
|
properties: {
|
|
275
|
-
prompt: { type: 'string', description: '
|
|
319
|
+
prompt: { type: 'string', description: 'Self-contained music style / mood / description. ' +
|
|
320
|
+
'The music model sees ONLY this text, never the conversation: when the user refers to earlier messages, ' +
|
|
321
|
+
'write those details into the prompt.' },
|
|
276
322
|
output_path: { type: 'string', description: 'Where to save the MP3. Default: generated-<timestamp>.mp3' },
|
|
277
323
|
model: { type: 'string', description: 'Music model. Default: minimax/music-2.5+' },
|
|
278
324
|
instrumental: { type: 'boolean', description: 'No vocals. Cannot combine with `lyrics`.' },
|
package/dist/tools/subagent.js
CHANGED
|
@@ -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: `[${
|
|
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
|
|
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
|
|
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
|
};
|
package/dist/tools/videogen.js
CHANGED
|
@@ -366,7 +366,8 @@ function buildExecute(deps) {
|
|
|
366
366
|
}
|
|
367
367
|
}
|
|
368
368
|
return {
|
|
369
|
-
output: `Video saved to ${outPath} (${sizeMB}MB, ${dur}s, ${videoModel})\n
|
|
369
|
+
output: `Video saved to ${outPath} (${sizeMB}MB, ${dur}s, ${videoModel})\n` +
|
|
370
|
+
`Prompt sent: ${prompt}\n\n` +
|
|
370
371
|
`Open with: open ${outPath}${contentSummary}`,
|
|
371
372
|
};
|
|
372
373
|
}
|
|
@@ -503,7 +504,9 @@ export function createVideoGenCapability(deps = {}) {
|
|
|
503
504
|
input_schema: {
|
|
504
505
|
type: 'object',
|
|
505
506
|
properties: {
|
|
506
|
-
prompt: { type: 'string', description: '
|
|
507
|
+
prompt: { type: 'string', description: 'Self-contained text description of the video to generate. ' +
|
|
508
|
+
'The video model sees ONLY this text, never the conversation: when the user refers to earlier messages, ' +
|
|
509
|
+
'write those details (scenes, names, quoted text) into the prompt verbatim.' },
|
|
507
510
|
output_path: { type: 'string', description: 'Where to save the MP4. Default: generated-<timestamp>.mp4 in working directory' },
|
|
508
511
|
model: {
|
|
509
512
|
type: 'string',
|
package/dist/tools/zerox-base.js
CHANGED
|
@@ -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
|
-
//
|
|
56
|
-
|
|
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 (
|
|
238
|
+
if (getLiveSwapCount() >= liveSwapCap) {
|
|
260
239
|
return {
|
|
261
|
-
output: `Live-swap session cap reached (${
|
|
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: ${
|
|
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
|
-
|
|
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: ${
|
|
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
|
-
//
|
|
40
|
-
|
|
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 (
|
|
233
|
+
if (getLiveSwapCount() >= liveSwapCap) {
|
|
255
234
|
return {
|
|
256
|
-
output: `Live-swap session cap reached (${
|
|
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: ${
|
|
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
|
-
|
|
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: ${
|
|
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.
|
|
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": {
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"@solana/spl-token": "^0.4.14",
|
|
88
88
|
"@solana/web3.js": "^1.98.4",
|
|
89
89
|
"@types/react": "^19.2.14",
|
|
90
|
-
"axios": "^1.
|
|
90
|
+
"axios": "^1.20.0",
|
|
91
91
|
"bs58": "^6.0.0",
|
|
92
92
|
"chalk": "^5.4.0",
|
|
93
93
|
"commander": "^15.0.0",
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
"playwright-core": "^1.49.1",
|
|
99
99
|
"qrcode": "^1.5.4",
|
|
100
100
|
"react": "^19.2.4",
|
|
101
|
-
"sharp": "^0.35.
|
|
101
|
+
"sharp": "^0.35.5",
|
|
102
102
|
"viem": "^2.48.1",
|
|
103
103
|
"ws": "^8.21.1"
|
|
104
104
|
},
|
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
"ws@>=8.0.0 <=8.20.1": "^8.21.1",
|
|
113
113
|
"@polymarket/builder-signing-sdk": "1.0.0",
|
|
114
114
|
"@polymarket/builder-relayer-client": {
|
|
115
|
-
"axios": "^1.
|
|
115
|
+
"axios": "^1.20.0"
|
|
116
116
|
},
|
|
117
117
|
"qs": "^6.16.0"
|
|
118
118
|
}
|