@blockrun/franklin 3.29.4 → 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.
- package/dist/agent/error-classifier.js +3 -0
- package/dist/agent/intent-prefetch.d.ts +13 -0
- package/dist/agent/intent-prefetch.js +51 -18
- package/dist/agent/loop.js +115 -18
- package/dist/content/record-image.d.ts +9 -1
- package/dist/content/record-image.js +6 -3
- package/dist/content/store.js +10 -4
- package/dist/phone/client.js +22 -0
- package/dist/stats/tracker.d.ts +4 -0
- package/dist/stats/tracker.js +19 -0
- package/dist/storage/atomic.d.ts +13 -0
- package/dist/storage/atomic.js +64 -0
- package/dist/tools/defillama.js +15 -5
- package/dist/tools/exa.js +10 -7
- package/dist/tools/imagegen.d.ts +17 -0
- package/dist/tools/imagegen.js +40 -6
- package/dist/tools/jupiter.d.ts +1 -0
- package/dist/tools/jupiter.js +52 -8
- package/dist/tools/musicgen.d.ts +10 -0
- package/dist/tools/musicgen.js +37 -4
- package/dist/tools/phone.js +18 -0
- package/dist/tools/prediction.js +8 -0
- package/dist/tools/rpc.js +15 -5
- package/dist/tools/videogen.d.ts +11 -0
- package/dist/tools/videogen.js +35 -17
- package/dist/tools/voice.js +48 -26
- package/dist/trading/engine.js +5 -1
- package/dist/trading/providers/telemetry.d.ts +7 -0
- package/dist/trading/providers/telemetry.js +9 -0
- package/dist/trading/risk.js +5 -2
- package/dist/trading/store.js +11 -5
- package/dist/ui/terminal.js +13 -3
- package/package.json +3 -3
package/dist/tools/defillama.js
CHANGED
|
@@ -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
|
|
43
|
-
if (!
|
|
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, ...
|
|
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}`);
|
package/dist/tools/exa.js
CHANGED
|
@@ -145,7 +145,8 @@ export const exaSearchCapability = {
|
|
|
145
145
|
return { output: 'Error: query is required', isError: true };
|
|
146
146
|
try {
|
|
147
147
|
const res = await postWithPayment('/v1/exa/search', params, ctx);
|
|
148
|
-
const
|
|
148
|
+
const body = res.data ?? res;
|
|
149
|
+
const hits = body.results ?? [];
|
|
149
150
|
if (hits.length === 0) {
|
|
150
151
|
return { output: `No Exa results for "${params.query}".` };
|
|
151
152
|
}
|
|
@@ -155,7 +156,7 @@ export const exaSearchCapability = {
|
|
|
155
156
|
const score = h.score ? ` · score ${h.score.toFixed(2)}` : '';
|
|
156
157
|
lines.push(`\n**${h.title}**${date}${score}\n${h.url}`);
|
|
157
158
|
}
|
|
158
|
-
const cost =
|
|
159
|
+
const cost = body.costDollars?.total;
|
|
159
160
|
if (cost)
|
|
160
161
|
lines.push(`\n_Cost: $${cost.toFixed(4)}_`);
|
|
161
162
|
return { output: lines.join('\n') };
|
|
@@ -189,15 +190,16 @@ export const exaAnswerCapability = {
|
|
|
189
190
|
return { output: 'Error: query is required', isError: true };
|
|
190
191
|
try {
|
|
191
192
|
const res = await postWithPayment('/v1/exa/answer', params, ctx);
|
|
192
|
-
const
|
|
193
|
-
const
|
|
193
|
+
const body = res.data ?? res;
|
|
194
|
+
const ans = body.answer ?? '';
|
|
195
|
+
const cites = body.citations ?? [];
|
|
194
196
|
const lines = [ans];
|
|
195
197
|
if (cites.length > 0) {
|
|
196
198
|
lines.push('\n**Sources**');
|
|
197
199
|
for (const c of cites)
|
|
198
200
|
lines.push(`- [${c.title}](${c.url})`);
|
|
199
201
|
}
|
|
200
|
-
const cost =
|
|
202
|
+
const cost = body.costDollars?.total;
|
|
201
203
|
if (cost)
|
|
202
204
|
lines.push(`\n_Cost: $${cost.toFixed(4)}_`);
|
|
203
205
|
return { output: lines.join('\n') };
|
|
@@ -238,7 +240,8 @@ export const exaReadUrlsCapability = {
|
|
|
238
240
|
}
|
|
239
241
|
try {
|
|
240
242
|
const res = await postWithPayment('/v1/exa/contents', params, ctx);
|
|
241
|
-
const
|
|
243
|
+
const body = res.data ?? res;
|
|
244
|
+
const results = body.results ?? [];
|
|
242
245
|
if (results.length === 0) {
|
|
243
246
|
return { output: `No readable content returned for the ${params.urls.length} URL(s).` };
|
|
244
247
|
}
|
|
@@ -246,7 +249,7 @@ export const exaReadUrlsCapability = {
|
|
|
246
249
|
for (const r of results) {
|
|
247
250
|
lines.push(`\n### ${r.title ?? r.url}\n_Source: ${r.url}_\n\n${r.text}`);
|
|
248
251
|
}
|
|
249
|
-
const cost =
|
|
252
|
+
const cost = body.costDollars?.total;
|
|
250
253
|
if (cost)
|
|
251
254
|
lines.push(`\n_Cost: $${cost.toFixed(4)}_`);
|
|
252
255
|
return { output: lines.join('\n') };
|
package/dist/tools/imagegen.d.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import type { CapabilityHandler } from '../agent/types.js';
|
|
6
6
|
import type { ContentLibrary } from '../content/library.js';
|
|
7
|
+
import { type GatewayModel } from '../gateway-models.js';
|
|
7
8
|
/**
|
|
8
9
|
* Models that accept a reference image via /v1/images/image2image. Mirrors the
|
|
9
10
|
* gateway's EDIT_SUPPORTED_MODELS (src/app/api/v1/images/image2image/route.ts):
|
|
@@ -28,6 +29,22 @@ export declare const MAX_OUTPUT_IMAGES = 4;
|
|
|
28
29
|
*/
|
|
29
30
|
export declare const IMAGE_MODEL_SIZES: Record<string, string[]>;
|
|
30
31
|
export declare const REFERENCE_IMAGE_MAX_BYTES = 4000000;
|
|
32
|
+
/**
|
|
33
|
+
* Resolve the per-image USD cost used for the budget check, spend confirm, and
|
|
34
|
+
* asset record. Two sources, neither sufficient alone:
|
|
35
|
+
* - the live catalog price is authoritative for models the static table omits
|
|
36
|
+
* (closing the $0-budget bypass), but it is SIZE-BLIND — a single flat
|
|
37
|
+
* per_image figure that ignores the larger, pricier tiers;
|
|
38
|
+
* - the static table is SIZE-AWARE (e.g. gpt-image-1 is $0.02 at 1024x1024 but
|
|
39
|
+
* $0.04 at 1536x1024) but only covers a handful of models.
|
|
40
|
+
* Take the HIGHER of the two so none of the three consumers ever undercounts the
|
|
41
|
+
* real charge for a large, non-1024 size. The static figures are base prices with
|
|
42
|
+
* NO gateway margin, whereas estimateCostUsd already applies GATEWAY_MARGIN — so
|
|
43
|
+
* we margin-adjust the static operand before the Math.max, keeping both on the
|
|
44
|
+
* realized-charge basis (otherwise the size-aware path would undercount by ~5%).
|
|
45
|
+
* Exported for regression tests.
|
|
46
|
+
*/
|
|
47
|
+
export declare function resolveImageUnitCost(catalogModel: GatewayModel | null, model: string, size: string): number;
|
|
31
48
|
/**
|
|
32
49
|
* Normalize a reference image into a base64 data URI for the gateway. The
|
|
33
50
|
* /v1/images/image2image endpoint validates `image` against /^data:image\//,
|
package/dist/tools/imagegen.js
CHANGED
|
@@ -7,8 +7,9 @@ import path from 'node:path';
|
|
|
7
7
|
import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
|
|
8
8
|
import { loadChain, API_URLS, VERSION } from '../config.js';
|
|
9
9
|
import { checkImageBudget, recordImageAsset } from '../content/record-image.js';
|
|
10
|
+
import { estimateImageCostUsd } from '../content/image-pricing.js';
|
|
10
11
|
import { recordUsage } from '../stats/tracker.js';
|
|
11
|
-
import { findModel, estimateCostUsd } from '../gateway-models.js';
|
|
12
|
+
import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
|
|
12
13
|
import { logger } from '../logger.js';
|
|
13
14
|
/**
|
|
14
15
|
* Models that accept a reference image via /v1/images/image2image. Mirrors the
|
|
@@ -55,6 +56,26 @@ export const IMAGE_MODEL_SIZES = {
|
|
|
55
56
|
'google/nano-banana-pro': ['1024x1024', '2048x2048', '4096x4096'],
|
|
56
57
|
};
|
|
57
58
|
export const REFERENCE_IMAGE_MAX_BYTES = 4_000_000;
|
|
59
|
+
/**
|
|
60
|
+
* Resolve the per-image USD cost used for the budget check, spend confirm, and
|
|
61
|
+
* asset record. Two sources, neither sufficient alone:
|
|
62
|
+
* - the live catalog price is authoritative for models the static table omits
|
|
63
|
+
* (closing the $0-budget bypass), but it is SIZE-BLIND — a single flat
|
|
64
|
+
* per_image figure that ignores the larger, pricier tiers;
|
|
65
|
+
* - the static table is SIZE-AWARE (e.g. gpt-image-1 is $0.02 at 1024x1024 but
|
|
66
|
+
* $0.04 at 1536x1024) but only covers a handful of models.
|
|
67
|
+
* Take the HIGHER of the two so none of the three consumers ever undercounts the
|
|
68
|
+
* real charge for a large, non-1024 size. The static figures are base prices with
|
|
69
|
+
* NO gateway margin, whereas estimateCostUsd already applies GATEWAY_MARGIN — so
|
|
70
|
+
* we margin-adjust the static operand before the Math.max, keeping both on the
|
|
71
|
+
* realized-charge basis (otherwise the size-aware path would undercount by ~5%).
|
|
72
|
+
* Exported for regression tests.
|
|
73
|
+
*/
|
|
74
|
+
export function resolveImageUnitCost(catalogModel, model, size) {
|
|
75
|
+
const catalogUsd = catalogModel ? estimateCostUsd(catalogModel, { quantity: 1 }) : 0;
|
|
76
|
+
const staticUsd = +(estimateImageCostUsd(model, size, 1) * GATEWAY_MARGIN).toFixed(6);
|
|
77
|
+
return Math.max(catalogUsd, staticUsd);
|
|
78
|
+
}
|
|
58
79
|
/**
|
|
59
80
|
* Normalize a reference image into a base64 data URI for the gateway. The
|
|
60
81
|
* /v1/images/image2image endpoint validates `image` against /^data:image\//,
|
|
@@ -201,8 +222,22 @@ function buildExecute(deps) {
|
|
|
201
222
|
isError: true,
|
|
202
223
|
};
|
|
203
224
|
}
|
|
225
|
+
// Resolve the authoritative per-image cost ONCE, reused below for the
|
|
226
|
+
// budget check, spend confirm, usage stats, and asset recording. The
|
|
227
|
+
// catalog lookup is best-effort: a cold-cache fetch failure must NOT abort
|
|
228
|
+
// a consented paid generation, so degrade to the static estimate instead of
|
|
229
|
+
// letting findModel throw out of execute() (mirrors videogen's fallback).
|
|
230
|
+
let catalogModel = null;
|
|
231
|
+
try {
|
|
232
|
+
catalogModel = await findModel(imageModel);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
// Catalog momentarily unreachable — resolveImageUnitCost falls back to
|
|
236
|
+
// the size-aware static table on its own.
|
|
237
|
+
}
|
|
238
|
+
const perImageUsd = resolveImageUnitCost(catalogModel, imageModel, imageSize);
|
|
204
239
|
if (contentId && deps.library) {
|
|
205
|
-
const decision = checkImageBudget(deps.library, contentId, imageModel, imageSize, n);
|
|
240
|
+
const decision = checkImageBudget(deps.library, contentId, imageModel, imageSize, n, perImageUsd * n);
|
|
206
241
|
if (!decision.ok) {
|
|
207
242
|
// Normal text output, not isError — the agent should adapt (smaller
|
|
208
243
|
// size, different model, raise budget) rather than trigger retry.
|
|
@@ -220,8 +255,7 @@ function buildExecute(deps) {
|
|
|
220
255
|
// and generate straight away — the explicit "generate" action is consent.
|
|
221
256
|
const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
|
|
222
257
|
if (!autoApprove && ctx.onAskUser) {
|
|
223
|
-
const
|
|
224
|
-
const est = m ? estimateCostUsd(m, { quantity: n }) : 0;
|
|
258
|
+
const est = perImageUsd * n;
|
|
225
259
|
const priceNote = est > 0 ? ` for ~$${est.toFixed(2)}` : '';
|
|
226
260
|
const countNote = n > 1 ? `${n} images` : 'an image';
|
|
227
261
|
const answer = await ctx.onAskUser(`Generate ${countNote} with ${imageModel}${priceNote}? No USDC is spent if you cancel.`, ['Generate', 'Cancel']);
|
|
@@ -412,8 +446,7 @@ function buildExecute(deps) {
|
|
|
412
446
|
const latencyMs = Date.now() - callStartedAt;
|
|
413
447
|
void (async () => {
|
|
414
448
|
try {
|
|
415
|
-
const
|
|
416
|
-
const estCost = m ? estimateCostUsd(m, { quantity: items.length }) : 0;
|
|
449
|
+
const estCost = perImageUsd * items.length;
|
|
417
450
|
recordUsage(imageModel, 0, 0, estCost, latencyMs);
|
|
418
451
|
}
|
|
419
452
|
catch { /* ignore stats errors */ }
|
|
@@ -431,6 +464,7 @@ function buildExecute(deps) {
|
|
|
431
464
|
imagePath: p,
|
|
432
465
|
model: imageModel,
|
|
433
466
|
size: imageSize,
|
|
467
|
+
costUsd: perImageUsd,
|
|
434
468
|
});
|
|
435
469
|
if (rec.ok) {
|
|
436
470
|
attached++;
|
package/dist/tools/jupiter.d.ts
CHANGED
|
@@ -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;
|
package/dist/tools/jupiter.js
CHANGED
|
@@ -113,12 +113,38 @@ function symbolFor(mint) {
|
|
|
113
113
|
}
|
|
114
114
|
return mint.slice(0, 4) + '…';
|
|
115
115
|
}
|
|
116
|
-
function toAtomicUnits(amount, decimals) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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;
|
package/dist/tools/musicgen.d.ts
CHANGED
|
@@ -15,9 +15,19 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import type { CapabilityHandler } from '../agent/types.js';
|
|
17
17
|
import type { ContentLibrary } from '../content/library.js';
|
|
18
|
+
import { type GatewayModel } from '../gateway-models.js';
|
|
18
19
|
export interface MusicGenDeps {
|
|
19
20
|
library?: ContentLibrary;
|
|
20
21
|
onContentChange?: () => void | Promise<void>;
|
|
21
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Resolve the per-track USD cost for the budget check + asset record. The `model`
|
|
25
|
+
* param is caller-selectable, so a pricier non-default music model would be
|
|
26
|
+
* charged its real price by the gateway but counted at the flat default
|
|
27
|
+
* otherwise — the same undercount class the ImageGen/VideoGen fixes close. Take
|
|
28
|
+
* the higher of the live catalog price (already margin-inclusive via
|
|
29
|
+
* estimateCostUsd) and the flat PRICE_USD. Exported for tests.
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveMusicUnitCost(catalogModel: GatewayModel | null): number;
|
|
22
32
|
export declare function createMusicGenCapability(deps?: MusicGenDeps): CapabilityHandler;
|
|
23
33
|
export declare const musicGenCapability: CapabilityHandler;
|
package/dist/tools/musicgen.js
CHANGED
|
@@ -18,8 +18,24 @@ import path from 'node:path';
|
|
|
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 { findModel, estimateCostUsd } from '../gateway-models.js';
|
|
22
|
+
import { recordUsage } from '../stats/tracker.js';
|
|
21
23
|
const DEFAULT_MODEL = 'minimax/music-2.5+';
|
|
24
|
+
// Flat per-track price for the default model — already margin-inclusive
|
|
25
|
+
// ($0.15/track × 1.05 gateway margin). Fallback when the catalog is unavailable.
|
|
22
26
|
const PRICE_USD = 0.1575;
|
|
27
|
+
/**
|
|
28
|
+
* Resolve the per-track USD cost for the budget check + asset record. The `model`
|
|
29
|
+
* param is caller-selectable, so a pricier non-default music model would be
|
|
30
|
+
* charged its real price by the gateway but counted at the flat default
|
|
31
|
+
* otherwise — the same undercount class the ImageGen/VideoGen fixes close. Take
|
|
32
|
+
* the higher of the live catalog price (already margin-inclusive via
|
|
33
|
+
* estimateCostUsd) and the flat PRICE_USD. Exported for tests.
|
|
34
|
+
*/
|
|
35
|
+
export function resolveMusicUnitCost(catalogModel) {
|
|
36
|
+
const catalogUsd = catalogModel ? estimateCostUsd(catalogModel, {}) : 0;
|
|
37
|
+
return Math.max(catalogUsd, PRICE_USD);
|
|
38
|
+
}
|
|
23
39
|
// MiniMax generation is 1-3 minutes + small buffer for payment + download.
|
|
24
40
|
const GEN_TIMEOUT_MS = 240_000;
|
|
25
41
|
const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
@@ -35,16 +51,25 @@ function buildExecute(deps) {
|
|
|
35
51
|
};
|
|
36
52
|
}
|
|
37
53
|
const musicModel = model || DEFAULT_MODEL;
|
|
54
|
+
// Resolve the per-track cost ONCE (catalog price if available, else the flat
|
|
55
|
+
// default) — reused by the budget check and the asset record so a pricier
|
|
56
|
+
// non-default model can't undercount the content budget. Best-effort lookup.
|
|
57
|
+
let musicCatalogModel = null;
|
|
58
|
+
try {
|
|
59
|
+
musicCatalogModel = await findModel(musicModel);
|
|
60
|
+
}
|
|
61
|
+
catch { /* catalog unreachable — resolveMusicUnitCost falls back to PRICE_USD */ }
|
|
62
|
+
const trackCostUsd = resolveMusicUnitCost(musicCatalogModel);
|
|
38
63
|
if (contentId && deps.library) {
|
|
39
64
|
const content = deps.library.get(contentId);
|
|
40
65
|
if (!content) {
|
|
41
66
|
return { output: `Content ${contentId} not found. No USDC was spent.` };
|
|
42
67
|
}
|
|
43
|
-
if (content.spentUsd +
|
|
68
|
+
if (content.spentUsd + trackCostUsd > content.budgetUsd + 1e-9) {
|
|
44
69
|
return {
|
|
45
70
|
output: `## Music generation skipped\n` +
|
|
46
71
|
`- Would exceed budget: spent $${content.spentUsd.toFixed(2)} + fixed ` +
|
|
47
|
-
`$${
|
|
72
|
+
`$${trackCostUsd.toFixed(2)} > cap $${content.budgetUsd.toFixed(2)}\n\n` +
|
|
48
73
|
`No USDC was spent.`,
|
|
49
74
|
};
|
|
50
75
|
}
|
|
@@ -70,6 +95,7 @@ function buildExecute(deps) {
|
|
|
70
95
|
const timeout = setTimeout(() => controller.abort(), GEN_TIMEOUT_MS);
|
|
71
96
|
const onAbort = () => controller.abort();
|
|
72
97
|
ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
|
|
98
|
+
const callStartedAt = Date.now();
|
|
73
99
|
try {
|
|
74
100
|
let response = await fetch(endpoint, {
|
|
75
101
|
method: 'POST',
|
|
@@ -101,6 +127,13 @@ function buildExecute(deps) {
|
|
|
101
127
|
if (!track?.url) {
|
|
102
128
|
return { output: 'No track URL returned from API', isError: true };
|
|
103
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 */ }
|
|
104
137
|
// CDN URLs expire in ~24h — download NOW.
|
|
105
138
|
const dlCtrl = new AbortController();
|
|
106
139
|
const dlTimeout = setTimeout(() => dlCtrl.abort(), DOWNLOAD_TIMEOUT_MS);
|
|
@@ -126,7 +159,7 @@ function buildExecute(deps) {
|
|
|
126
159
|
const rec = deps.library.addAsset(contentId, {
|
|
127
160
|
kind: 'audio',
|
|
128
161
|
source: musicModel,
|
|
129
|
-
costUsd:
|
|
162
|
+
costUsd: trackCostUsd,
|
|
130
163
|
data: outPath,
|
|
131
164
|
});
|
|
132
165
|
if (rec.ok) {
|
|
@@ -135,7 +168,7 @@ function buildExecute(deps) {
|
|
|
135
168
|
const c = deps.library.get(contentId);
|
|
136
169
|
contentSummary =
|
|
137
170
|
`\n\n## Content updated\n` +
|
|
138
|
-
`- Attached to \`${contentId}\` at est. $${
|
|
171
|
+
`- Attached to \`${contentId}\` at est. $${trackCostUsd.toFixed(2)}\n` +
|
|
139
172
|
(c
|
|
140
173
|
? `- Spent: $${c.spentUsd.toFixed(2)} / $${c.budgetUsd.toFixed(2)} cap ` +
|
|
141
174
|
`(remaining $${(c.budgetUsd - c.spentUsd).toFixed(2)})`
|
package/dist/tools/phone.js
CHANGED
|
@@ -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 {
|
package/dist/tools/prediction.js
CHANGED
|
@@ -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
|
|
69
|
-
if (!
|
|
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, ...
|
|
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}`);
|
package/dist/tools/videogen.d.ts
CHANGED
|
@@ -20,9 +20,20 @@
|
|
|
20
20
|
*/
|
|
21
21
|
import type { CapabilityHandler } from '../agent/types.js';
|
|
22
22
|
import type { ContentLibrary } from '../content/library.js';
|
|
23
|
+
import { type GatewayModel } from '../gateway-models.js';
|
|
23
24
|
export interface VideoGenDeps {
|
|
24
25
|
library?: ContentLibrary;
|
|
25
26
|
onContentChange?: () => void | Promise<void>;
|
|
26
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* Resolve the per-clip USD cost used for the spend confirm, budget check, usage
|
|
30
|
+
* stats, AND the content-budget asset record — one value so they can never
|
|
31
|
+
* disagree. The flat $0.05/s estimate is the fallback for an unknown model, but
|
|
32
|
+
* a catalog-priced per-second model (e.g. Seedance at $0.15/s) costs far more,
|
|
33
|
+
* so take the HIGHER of the catalog price and the (margin-adjusted) flat
|
|
34
|
+
* estimate. Without this the budget check + asset record undercount the cap ~3x
|
|
35
|
+
* for Seedance. Mirrors ImageGen's resolveImageUnitCost. Exported for tests.
|
|
36
|
+
*/
|
|
37
|
+
export declare function resolveVideoUnitCost(catalogModel: GatewayModel | null, durationSeconds: number): number;
|
|
27
38
|
export declare function createVideoGenCapability(deps?: VideoGenDeps): CapabilityHandler;
|
|
28
39
|
export declare const videoGenCapability: CapabilityHandler;
|