@blockrun/franklin 3.29.3 → 3.29.7
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 +54 -17
- 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/serve/cloud-sync.js +5 -1
- package/dist/storage/atomic.d.ts +13 -0
- package/dist/storage/atomic.js +64 -0
- package/dist/tools/exa.js +10 -7
- package/dist/tools/imagegen.d.ts +17 -0
- package/dist/tools/imagegen.js +57 -74
- package/dist/tools/musicgen.d.ts +10 -0
- package/dist/tools/musicgen.js +28 -4
- package/dist/tools/videogen.d.ts +11 -0
- package/dist/tools/videogen.js +52 -74
- package/dist/tools/voice.js +29 -21
- package/dist/trading/providers/telemetry.d.ts +7 -0
- package/dist/trading/providers/telemetry.js +9 -0
- package/dist/trading/store.js +11 -5
- package/dist/ui/terminal.js +13 -3
- package/package.json +3 -3
|
@@ -104,6 +104,9 @@ export function classifyAgentError(message) {
|
|
|
104
104
|
if (includesAny(err, [
|
|
105
105
|
'prompt is too long',
|
|
106
106
|
'context length',
|
|
107
|
+
'context_length_exceeded', // OpenAI-style code, leaks via gateway for non-Anthropic models
|
|
108
|
+
'context window',
|
|
109
|
+
'context_window',
|
|
107
110
|
'maximum context',
|
|
108
111
|
'prompt too long',
|
|
109
112
|
'token limit exceeded',
|
|
@@ -53,6 +53,19 @@ export interface PrefetchResult {
|
|
|
53
53
|
}
|
|
54
54
|
/** Run the prefetch for an intent. Concurrent fan-out for price + news. */
|
|
55
55
|
export declare function prefetchForIntent(intent: Intent, client: ModelClient): Promise<PrefetchResult | null>;
|
|
56
|
+
/**
|
|
57
|
+
* Read an ExaAnswer response through BOTH wire shapes — the live BlockRun
|
|
58
|
+
* gateway returns `{ answer, costDollars }` at the TOP level, while older or
|
|
59
|
+
* proxied deployments nest them under `data`. This mirrors the `res.data ?? res`
|
|
60
|
+
* read in src/tools/exa.ts; this prefetch path is the twin of the ExaAnswer
|
|
61
|
+
* tool and historically drifted out of sync, paying the USDC then dropping the
|
|
62
|
+
* answer. Exported for regression tests. `paid` records whether a real x402
|
|
63
|
+
* charge settled, so a paid-but-empty answer still counts against spend.
|
|
64
|
+
*/
|
|
65
|
+
export declare function readExaAnswer(raw: unknown, paid: boolean): {
|
|
66
|
+
text: string | null;
|
|
67
|
+
costUsd: number;
|
|
68
|
+
};
|
|
56
69
|
/**
|
|
57
70
|
* Augment a user message with the prefetch context block prepended. The
|
|
58
71
|
* final model sees the data as part of the "incoming" user turn — no
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
* coordination gap (harness fetches, model synthesizes)."
|
|
27
27
|
*/
|
|
28
28
|
import { getStockPrice, getPrice } from '../trading/data.js';
|
|
29
|
+
import { blockrunSpendUsdToday } from '../trading/providers/telemetry.js';
|
|
29
30
|
// ─── Intent source ──────────────────────────────────────────────────────
|
|
30
31
|
//
|
|
31
32
|
// Historical note: this file used to host its own LLM classifier
|
|
@@ -54,16 +55,24 @@ export async function prefetchForIntent(intent, client) {
|
|
|
54
55
|
if (intent.kind === 'ticker') {
|
|
55
56
|
if (intent.assetClass === 'stock') {
|
|
56
57
|
const market = intent.market || 'us';
|
|
57
|
-
tasks.push(
|
|
58
|
+
tasks.push((async () => {
|
|
59
|
+
// The stock price is a paid x402 call ($0.001) BUT cached for 5 min,
|
|
60
|
+
// so a repeat ticker within the window pays nothing. Book the REAL
|
|
61
|
+
// spend by diffing telemetry around the call (recordFetch fires only
|
|
62
|
+
// on a fresh paid fetch, never a cache hit) instead of hardcoding
|
|
63
|
+
// $0.001 — otherwise a cached hit over-reports the prefetch cost.
|
|
64
|
+
const before = blockrunSpendUsdToday();
|
|
65
|
+
const r = await getStockPrice(intent.symbol, market);
|
|
66
|
+
const paidUsd = Math.max(0, blockrunSpendUsdToday() - before);
|
|
58
67
|
if (typeof r === 'string') {
|
|
59
|
-
return { ok: false, line: `- ${intent.symbol} (${market}): lookup failed — ${r.slice(0, 80)}`, cost:
|
|
68
|
+
return { ok: false, line: `- ${intent.symbol} (${market}): lookup failed — ${r.slice(0, 80)}`, cost: paidUsd };
|
|
60
69
|
}
|
|
61
70
|
return {
|
|
62
71
|
ok: true,
|
|
63
72
|
line: `- ${intent.symbol} (${market}) live price: ${formatUsd(r.price)} (BlockRun Gateway / Pyth)`,
|
|
64
|
-
cost:
|
|
73
|
+
cost: paidUsd,
|
|
65
74
|
};
|
|
66
|
-
}));
|
|
75
|
+
})());
|
|
67
76
|
}
|
|
68
77
|
else {
|
|
69
78
|
// crypto
|
|
@@ -85,14 +94,16 @@ export async function prefetchForIntent(intent, client) {
|
|
|
85
94
|
const query = intent.assetClass === 'stock'
|
|
86
95
|
? `Why did ${intent.symbol} stock move over the past week? Recent news and catalysts for ${intent.symbol} as of today.`
|
|
87
96
|
: `What are the most important recent news events affecting ${intent.symbol} cryptocurrency in the past week?`;
|
|
88
|
-
tasks.push(exaAnswerTry(query, client).then(
|
|
89
|
-
if (!
|
|
90
|
-
|
|
97
|
+
tasks.push(exaAnswerTry(query, client).then(({ text, costUsd }) => {
|
|
98
|
+
if (!text) {
|
|
99
|
+
// costUsd is non-zero only when a paid call actually settled but came
|
|
100
|
+
// back empty — count it so spend telemetry never under-reports USDC.
|
|
101
|
+
return { ok: false, line: `- Recent ${intent.symbol} news: ExaAnswer lookup failed`, cost: costUsd };
|
|
91
102
|
}
|
|
92
103
|
return {
|
|
93
104
|
ok: true,
|
|
94
|
-
line: `- Recent ${intent.symbol} news (ExaAnswer synthesized):\n ${
|
|
95
|
-
cost:
|
|
105
|
+
line: `- Recent ${intent.symbol} news (ExaAnswer synthesized):\n ${text.replace(/\n/g, '\n ')}`,
|
|
106
|
+
cost: costUsd,
|
|
96
107
|
};
|
|
97
108
|
}));
|
|
98
109
|
}
|
|
@@ -112,7 +123,30 @@ export async function prefetchForIntent(intent, client) {
|
|
|
112
123
|
const statusLine = `*Prefetched ${lines.length} source${lines.length === 1 ? '' : 's'} · cost ${formatUsd(cost)}*`;
|
|
113
124
|
return { contextBlock, statusLine, costUsd: cost, anyOk };
|
|
114
125
|
}
|
|
115
|
-
/**
|
|
126
|
+
/** Fallback per-call ExaAnswer estimate when the gateway omits costDollars. */
|
|
127
|
+
const EXA_ANSWER_EST_USD = 0.01;
|
|
128
|
+
/**
|
|
129
|
+
* Read an ExaAnswer response through BOTH wire shapes — the live BlockRun
|
|
130
|
+
* gateway returns `{ answer, costDollars }` at the TOP level, while older or
|
|
131
|
+
* proxied deployments nest them under `data`. This mirrors the `res.data ?? res`
|
|
132
|
+
* read in src/tools/exa.ts; this prefetch path is the twin of the ExaAnswer
|
|
133
|
+
* tool and historically drifted out of sync, paying the USDC then dropping the
|
|
134
|
+
* answer. Exported for regression tests. `paid` records whether a real x402
|
|
135
|
+
* charge settled, so a paid-but-empty answer still counts against spend.
|
|
136
|
+
*/
|
|
137
|
+
export function readExaAnswer(raw, paid) {
|
|
138
|
+
// Defensive against a drifted/malformed wire shape: a non-object body or a
|
|
139
|
+
// non-string `answer` must degrade to null text (NOT throw), otherwise the
|
|
140
|
+
// throw is swallowed by exaAnswerTry's catch and a settled paid call is
|
|
141
|
+
// mis-booked as $0 — the exact under-report this function exists to prevent.
|
|
142
|
+
const body = (raw && typeof raw === 'object' ? raw : {});
|
|
143
|
+
const b = (body.data && typeof body.data === 'object' ? body.data : body);
|
|
144
|
+
const text = (typeof b.answer === 'string' ? b.answer : '').slice(0, 600).trim() || null;
|
|
145
|
+
const reported = typeof b.costDollars?.total === 'number' ? b.costDollars.total : undefined;
|
|
146
|
+
const costUsd = reported ?? (paid ? EXA_ANSWER_EST_USD : 0);
|
|
147
|
+
return { text, costUsd };
|
|
148
|
+
}
|
|
149
|
+
/** Thin wrapper: call ExaAnswer via the gateway, return parsed text + real cost. */
|
|
116
150
|
async function exaAnswerTry(query, client) {
|
|
117
151
|
try {
|
|
118
152
|
// Reuse the BlockRun gateway chat endpoint the ExaAnswer tool already uses.
|
|
@@ -131,7 +165,7 @@ async function exaAnswerTry(query, client) {
|
|
|
131
165
|
if (res.status === 402) {
|
|
132
166
|
const payHdr = await extractPaymentReq(res);
|
|
133
167
|
if (!payHdr)
|
|
134
|
-
return null;
|
|
168
|
+
return { text: null, costUsd: 0 };
|
|
135
169
|
const { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK } = await import('@blockrun/llm');
|
|
136
170
|
const paymentRequired = parsePaymentRequired(payHdr);
|
|
137
171
|
let headers = { 'Content-Type': 'application/json' };
|
|
@@ -163,17 +197,16 @@ async function exaAnswerTry(query, client) {
|
|
|
163
197
|
method: 'POST', headers, body: JSON.stringify({ query }),
|
|
164
198
|
});
|
|
165
199
|
if (!res2.ok)
|
|
166
|
-
return null;
|
|
167
|
-
|
|
168
|
-
return (
|
|
200
|
+
return { text: null, costUsd: 0 };
|
|
201
|
+
// A 200 here means the x402 charge settled — count it even if empty.
|
|
202
|
+
return readExaAnswer(await res2.json(), true);
|
|
169
203
|
}
|
|
170
204
|
if (!res.ok)
|
|
171
|
-
return null;
|
|
172
|
-
|
|
173
|
-
return (body.data?.answer || '').slice(0, 600).trim() || null;
|
|
205
|
+
return { text: null, costUsd: 0 };
|
|
206
|
+
return readExaAnswer(await res.json(), false);
|
|
174
207
|
}
|
|
175
208
|
catch {
|
|
176
|
-
return null;
|
|
209
|
+
return { text: null, costUsd: 0 };
|
|
177
210
|
}
|
|
178
211
|
}
|
|
179
212
|
async function extractPaymentReq(response) {
|
package/dist/agent/loop.js
CHANGED
|
@@ -1531,15 +1531,17 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
1531
1531
|
}
|
|
1532
1532
|
}
|
|
1533
1533
|
if (classified.isTransient && recoveryAttempts < effectiveMaxRetries) {
|
|
1534
|
-
// Server
|
|
1535
|
-
// it's almost always an upstream
|
|
1536
|
-
//
|
|
1537
|
-
// dead provider — same idea
|
|
1538
|
-
//
|
|
1539
|
-
// transients (rate limits, network blips) where retry is
|
|
1540
|
-
// call
|
|
1541
|
-
// explicitly chose this one, so we shouldn't silently swap.
|
|
1542
|
-
|
|
1534
|
+
// Server/overloaded streak guard: if the same model 5xx's or stays
|
|
1535
|
+
// overloaded (529) twice in a row it's almost always an upstream
|
|
1536
|
+
// incident, not a blip. Switch to the next routing fallback instead
|
|
1537
|
+
// of waiting out the backoffs on a dead/busy provider — same idea
|
|
1538
|
+
// as the payment-failure auto-fallback below. Skipped for other
|
|
1539
|
+
// transients (rate limits, network blips) where in-place retry is
|
|
1540
|
+
// the right call, and skipped when the user picked a concrete model
|
|
1541
|
+
// — they explicitly chose this one, so we shouldn't silently swap.
|
|
1542
|
+
// (An overloaded model's own suggestion text already says "/model
|
|
1543
|
+
// to switch"; this does it automatically when routing is in auto.)
|
|
1544
|
+
if ((classified.category === 'server' || classified.category === 'overloaded') && parseRoutingProfile(config.model)) {
|
|
1543
1545
|
const streak = (serverErrorsByModel.get(resolvedModel) ?? 0) + 1;
|
|
1544
1546
|
serverErrorsByModel.set(resolvedModel, streak);
|
|
1545
1547
|
if (streak >= SERVER_ERROR_STREAK_BEFORE_SWITCH) {
|
|
@@ -1549,9 +1551,10 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
1549
1551
|
config.model = nextModel;
|
|
1550
1552
|
config.onModelChange?.(nextModel, 'system');
|
|
1551
1553
|
recoveryAttempts = 0;
|
|
1554
|
+
const failKind = classified.category === 'overloaded' ? 'is overloaded' : "keeps 5xx'ing";
|
|
1552
1555
|
onEvent({
|
|
1553
1556
|
kind: 'text_delta',
|
|
1554
|
-
text: `\n*${resolvedModel}
|
|
1557
|
+
text: `\n*${resolvedModel} ${failKind} (${streak} in a row) — switching to ${nextModel}*\n`,
|
|
1555
1558
|
});
|
|
1556
1559
|
continue;
|
|
1557
1560
|
}
|
|
@@ -1863,21 +1866,55 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
|
|
|
1863
1866
|
continue; // Retry with higher limit
|
|
1864
1867
|
}
|
|
1865
1868
|
// ── Gateway error masquerading as text (BlockRun → Anthropic TPM) ──
|
|
1866
|
-
// Some upstreams swallow rate-limit / quota errors and emit
|
|
1867
|
-
// single bracketed text block on a 200 OK.
|
|
1868
|
-
//
|
|
1869
|
-
//
|
|
1870
|
-
//
|
|
1871
|
-
// the
|
|
1869
|
+
// Some upstreams swallow rate-limit / quota / overload errors and emit
|
|
1870
|
+
// them as a single bracketed text block on a 200 OK. responseParts has
|
|
1871
|
+
// NOT been appended to history yet, so we never persist the transport
|
|
1872
|
+
// error as a real assistant reply (which would poison the next turn and
|
|
1873
|
+
// trigger grounding-check retries against the same wall). When the leaked
|
|
1874
|
+
// error is recoverable by switching providers, retry the turn on a free
|
|
1875
|
+
// model — mirroring the classifier's HTTP-error path: rate_limit always
|
|
1876
|
+
// falls back; overloaded only under a routing profile, so a user-pinned
|
|
1877
|
+
// concrete model is respected (matching the 529 streak-guard) rather than
|
|
1878
|
+
// silently demoted. Otherwise surface a terminal turn error and break.
|
|
1872
1879
|
const gatewayErr = looksLikeGatewayErrorAsText(responseParts);
|
|
1873
1880
|
if (gatewayErr.match) {
|
|
1874
1881
|
logger.error(`[franklin] Gateway returned an error text in lieu of an answer (${resolvedModel}): ${gatewayErr.message}`);
|
|
1882
|
+
const leaked = classifyAgentError(gatewayErr.message);
|
|
1883
|
+
const canFallback = leaked.category === 'rate_limit'
|
|
1884
|
+
|| (leaked.category === 'overloaded' && !!parseRoutingProfile(config.model));
|
|
1885
|
+
if (canFallback) {
|
|
1886
|
+
// Exclude BOTH the alias (config.model may be a profile like
|
|
1887
|
+
// "blockrun/free") AND the concrete model that actually leaked, so
|
|
1888
|
+
// pickFreeFallback can't hand back the same model and waste a retry.
|
|
1889
|
+
turnFailedModels.add(config.model);
|
|
1890
|
+
turnFailedModels.add(resolvedModel);
|
|
1891
|
+
if (leaked.category === 'rate_limit' && lastRoutedCategory) {
|
|
1892
|
+
recordOutcome(lastRoutedCategory, resolvedModel, 'rate_limit');
|
|
1893
|
+
}
|
|
1894
|
+
const nextFree = pickFreeFallback(lastRoutedCategory, turnFailedModels);
|
|
1895
|
+
if (nextFree && nextFree !== resolvedModel) {
|
|
1896
|
+
const oldModel = config.model;
|
|
1897
|
+
config.model = nextFree;
|
|
1898
|
+
config.onModelChange?.(nextFree, 'system');
|
|
1899
|
+
recoveryAttempts = 0; // new model gets its own retry budget
|
|
1900
|
+
onEvent({
|
|
1901
|
+
kind: 'text_delta',
|
|
1902
|
+
text: `\n*${formatModelSwitch(oldModel, resolvedModel, leaked.category === 'overloaded' ? 'overloaded' : 'rate-limited', nextFree)}*\n`,
|
|
1903
|
+
});
|
|
1904
|
+
continue; // Retry the turn on a different provider
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1875
1907
|
lastSessionActivity = Date.now();
|
|
1876
1908
|
persistSessionMeta();
|
|
1909
|
+
// Mirror the real-429 terminal path: if free models were exhausted this
|
|
1910
|
+
// turn, point a funded-wallet user at paid models as the escape hatch.
|
|
1911
|
+
const exhaustedHint = turnFailedModels.size > 0
|
|
1912
|
+
? `\nTip: All free models tried this turn are rate-limited. Switch to a paid model with /model anthropic/claude-sonnet-4.6 and retry — your wallet handles it.`
|
|
1913
|
+
: '';
|
|
1877
1914
|
onEvent({
|
|
1878
1915
|
kind: 'turn_done',
|
|
1879
1916
|
reason: 'error',
|
|
1880
|
-
error: gatewayErr.message
|
|
1917
|
+
error: `${gatewayErr.message}${exhaustedHint}`,
|
|
1881
1918
|
});
|
|
1882
1919
|
break;
|
|
1883
1920
|
}
|
|
@@ -18,6 +18,14 @@ export interface RecordImageAssetInput {
|
|
|
18
18
|
imagePath: string;
|
|
19
19
|
model: string;
|
|
20
20
|
size: string;
|
|
21
|
+
/**
|
|
22
|
+
* Authoritative per-image USD cost resolved by the caller (e.g. from the
|
|
23
|
+
* live gateway catalog). When omitted, falls back to the static estimate
|
|
24
|
+
* table — which returns 0 for models it doesn't list, so callers spending
|
|
25
|
+
* real USDC on a paid model MUST pass this or the spend bypasses the
|
|
26
|
+
* content budget cap.
|
|
27
|
+
*/
|
|
28
|
+
costUsd?: number;
|
|
21
29
|
}
|
|
22
30
|
export type RecordImageDecision = {
|
|
23
31
|
ok: true;
|
|
@@ -34,7 +42,7 @@ export type RecordImageDecision = {
|
|
|
34
42
|
* estimated cost fits; `{ ok: false, reason }` when it doesn't or the
|
|
35
43
|
* content doesn't exist. Non-mutating.
|
|
36
44
|
*/
|
|
37
|
-
export declare function checkImageBudget(library: ContentLibrary, contentId: string, model: string, size: string, count?: number): {
|
|
45
|
+
export declare function checkImageBudget(library: ContentLibrary, contentId: string, model: string, size: string, count?: number, costUsdOverride?: number): {
|
|
38
46
|
ok: true;
|
|
39
47
|
} | {
|
|
40
48
|
ok: false;
|
|
@@ -20,12 +20,15 @@ import { estimateImageCostUsd } from './image-pricing.js';
|
|
|
20
20
|
* estimated cost fits; `{ ok: false, reason }` when it doesn't or the
|
|
21
21
|
* content doesn't exist. Non-mutating.
|
|
22
22
|
*/
|
|
23
|
-
export function checkImageBudget(library, contentId, model, size, count = 1
|
|
23
|
+
export function checkImageBudget(library, contentId, model, size, count = 1,
|
|
24
|
+
// Total USD the caller already resolved for `count` images (live catalog).
|
|
25
|
+
// Falls back to the static estimate when omitted — see RecordImageAssetInput.
|
|
26
|
+
costUsdOverride) {
|
|
24
27
|
const content = library.get(contentId);
|
|
25
28
|
if (!content) {
|
|
26
29
|
return { ok: false, reason: `Content ${contentId} not found` };
|
|
27
30
|
}
|
|
28
|
-
const cost = estimateImageCostUsd(model, size, count);
|
|
31
|
+
const cost = costUsdOverride ?? estimateImageCostUsd(model, size, count);
|
|
29
32
|
if (content.spentUsd + cost > content.budgetUsd + 1e-9) {
|
|
30
33
|
return {
|
|
31
34
|
ok: false,
|
|
@@ -36,7 +39,7 @@ export function checkImageBudget(library, contentId, model, size, count = 1) {
|
|
|
36
39
|
return { ok: true };
|
|
37
40
|
}
|
|
38
41
|
export function recordImageAsset(library, input) {
|
|
39
|
-
const costUsd = estimateImageCostUsd(input.model, input.size);
|
|
42
|
+
const costUsd = input.costUsd ?? estimateImageCostUsd(input.model, input.size);
|
|
40
43
|
const result = library.addAsset(input.contentId, {
|
|
41
44
|
kind: 'image',
|
|
42
45
|
source: input.model,
|
package/dist/content/store.js
CHANGED
|
@@ -10,14 +10,15 @@
|
|
|
10
10
|
* best-effort, load returns `null` on any error so the agent falls back
|
|
11
11
|
* to a fresh in-memory library rather than refusing to start.
|
|
12
12
|
*/
|
|
13
|
-
import { existsSync,
|
|
14
|
-
import { dirname } from 'node:path';
|
|
13
|
+
import { existsSync, readFileSync, } from 'node:fs';
|
|
15
14
|
import { ContentLibrary } from './library.js';
|
|
15
|
+
import { atomicWriteFileSync } from '../storage/atomic.js';
|
|
16
16
|
export function saveLibrary(lib, filePath) {
|
|
17
17
|
try {
|
|
18
|
-
mkdirSync(dirname(filePath), { recursive: true });
|
|
19
18
|
const payload = { version: 1, contents: lib.list() };
|
|
20
|
-
|
|
19
|
+
// Atomic write so a crash mid-save can't truncate the library and lose
|
|
20
|
+
// the budget-load-bearing spentUsd (see storage/atomic.ts).
|
|
21
|
+
atomicWriteFileSync(filePath, JSON.stringify(payload, null, 2));
|
|
21
22
|
}
|
|
22
23
|
catch {
|
|
23
24
|
// Persistence is best-effort; never block a capability call on disk
|
|
@@ -26,6 +27,11 @@ export function saveLibrary(lib, filePath) {
|
|
|
26
27
|
}
|
|
27
28
|
}
|
|
28
29
|
export function loadLibrary(filePath) {
|
|
30
|
+
// Prefer the live file; fall back to the atomic-write backup if it's
|
|
31
|
+
// missing or corrupt rather than starting empty.
|
|
32
|
+
return readLibraryFile(filePath) ?? readLibraryFile(`${filePath}.bak`);
|
|
33
|
+
}
|
|
34
|
+
function readLibraryFile(filePath) {
|
|
29
35
|
if (!existsSync(filePath))
|
|
30
36
|
return null;
|
|
31
37
|
try {
|
package/dist/serve/cloud-sync.js
CHANGED
|
@@ -17,7 +17,11 @@ const NONCE_COOKIE = 'franklin_try_nonce';
|
|
|
17
17
|
const SESSION_COOKIE = 'franklin_try_session';
|
|
18
18
|
const TIMEOUT = 8000;
|
|
19
19
|
export function isCloudSyncEnabled() {
|
|
20
|
-
|
|
20
|
+
// Local-first by default (matches Claude Code / Codex): conversation history
|
|
21
|
+
// stays on disk and is NOT uploaded to franklin.run unless the user opts in
|
|
22
|
+
// with FRANKLIN_CLOUD_SYNC=on. Cross-device sync is a deliberate choice, not
|
|
23
|
+
// the default.
|
|
24
|
+
return process.env.FRANKLIN_CLOUD_SYNC === 'on';
|
|
21
25
|
}
|
|
22
26
|
let sessionCookie = null;
|
|
23
27
|
// Track what we've pushed so save only sends changed/removed conversations.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crash-safe file writes.
|
|
3
|
+
*
|
|
4
|
+
* `writeFileSync` truncates the target before writing its bytes, so a crash
|
|
5
|
+
* or kill mid-write leaves a half-written (often empty) file. For Franklin
|
|
6
|
+
* that means a wiped portfolio (cross-session P&L — the Trading vertical's
|
|
7
|
+
* headline feature) or a wiped content library (budget `spentUsd`). We
|
|
8
|
+
* instead write to a sibling temp file and `renameSync` it into place:
|
|
9
|
+
* rename is atomic on the same filesystem, so a reader ever sees only the
|
|
10
|
+
* complete old file or the complete new one — never a torn write. The
|
|
11
|
+
* previous good copy is preserved as `<file>.bak` for recovery.
|
|
12
|
+
*/
|
|
13
|
+
export declare function atomicWriteFileSync(filePath: string, data: string): void;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crash-safe file writes.
|
|
3
|
+
*
|
|
4
|
+
* `writeFileSync` truncates the target before writing its bytes, so a crash
|
|
5
|
+
* or kill mid-write leaves a half-written (often empty) file. For Franklin
|
|
6
|
+
* that means a wiped portfolio (cross-session P&L — the Trading vertical's
|
|
7
|
+
* headline feature) or a wiped content library (budget `spentUsd`). We
|
|
8
|
+
* instead write to a sibling temp file and `renameSync` it into place:
|
|
9
|
+
* rename is atomic on the same filesystem, so a reader ever sees only the
|
|
10
|
+
* complete old file or the complete new one — never a torn write. The
|
|
11
|
+
* previous good copy is preserved as `<file>.bak` for recovery.
|
|
12
|
+
*/
|
|
13
|
+
import { writeFileSync, renameSync, copyFileSync, existsSync, mkdirSync, openSync, fsyncSync, closeSync, unlinkSync, } from 'node:fs';
|
|
14
|
+
import { dirname } from 'node:path';
|
|
15
|
+
export function atomicWriteFileSync(filePath, data) {
|
|
16
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
17
|
+
const tmp = `${filePath}.tmp`;
|
|
18
|
+
// Write AND fsync the temp file before renaming it into place. rename is
|
|
19
|
+
// atomic w.r.t. concurrent readers, but it is not durable across a hard
|
|
20
|
+
// crash/power loss on its own: the filesystem can persist the rename while
|
|
21
|
+
// the temp file's data blocks are still in the page cache, leaving a
|
|
22
|
+
// zero-length target after reboot — exactly the wiped-state failure this
|
|
23
|
+
// module exists to prevent. fsync forces the bytes down first.
|
|
24
|
+
const fd = openSync(tmp, 'w');
|
|
25
|
+
try {
|
|
26
|
+
writeFileSync(fd, data, 'utf-8');
|
|
27
|
+
fsyncSync(fd);
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
closeSync(fd);
|
|
31
|
+
}
|
|
32
|
+
// Snapshot the last good file before swapping, so an interrupted future
|
|
33
|
+
// write (or a corrupt new payload) is still recoverable from <file>.bak.
|
|
34
|
+
if (existsSync(filePath)) {
|
|
35
|
+
try {
|
|
36
|
+
copyFileSync(filePath, `${filePath}.bak`);
|
|
37
|
+
}
|
|
38
|
+
catch { /* best-effort */ }
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
renameSync(tmp, filePath);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
// Don't litter a half-written temp file on a failed swap (callers treat
|
|
45
|
+
// persistence as best-effort and swallow the throw, so nothing else reaps it).
|
|
46
|
+
try {
|
|
47
|
+
unlinkSync(tmp);
|
|
48
|
+
}
|
|
49
|
+
catch { /* ignore */ }
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
// fsync the directory so the rename itself survives a crash. Some platforms
|
|
53
|
+
// (and Windows) reject directory fsync — best-effort.
|
|
54
|
+
try {
|
|
55
|
+
const dfd = openSync(dirname(filePath), 'r');
|
|
56
|
+
try {
|
|
57
|
+
fsyncSync(dfd);
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
closeSync(dfd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch { /* best-effort */ }
|
|
64
|
+
}
|
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,10 +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 {
|
|
11
|
-
import { analyzeMediaRequest, renderProposalForAskUser } from '../agent/media-router.js';
|
|
10
|
+
import { estimateImageCostUsd } from '../content/image-pricing.js';
|
|
12
11
|
import { recordUsage } from '../stats/tracker.js';
|
|
13
|
-
import { findModel, estimateCostUsd } from '../gateway-models.js';
|
|
12
|
+
import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
|
|
14
13
|
import { logger } from '../logger.js';
|
|
15
14
|
/**
|
|
16
15
|
* Models that accept a reference image via /v1/images/image2image. Mirrors the
|
|
@@ -57,6 +56,26 @@ export const IMAGE_MODEL_SIZES = {
|
|
|
57
56
|
'google/nano-banana-pro': ['1024x1024', '2048x2048', '4096x4096'],
|
|
58
57
|
};
|
|
59
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
|
+
}
|
|
60
79
|
/**
|
|
61
80
|
* Normalize a reference image into a base64 data URI for the gateway. The
|
|
62
81
|
* /v1/images/image2image endpoint validates `image` against /^data:image\//,
|
|
@@ -140,21 +159,8 @@ function buildExecute(deps) {
|
|
|
140
159
|
isError: true,
|
|
141
160
|
};
|
|
142
161
|
}
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
// and pass skipRefine through to the router.
|
|
146
|
-
let prompt = rawInput.prompt;
|
|
147
|
-
let skipRefine = false;
|
|
148
|
-
if (prompt.trimStart().startsWith('///')) {
|
|
149
|
-
prompt = prompt.replace(/^\s*\/\/\/\s?/, '');
|
|
150
|
-
skipRefine = true;
|
|
151
|
-
}
|
|
152
|
-
// ── Media router + AskUser flow ────────────────────────────────────
|
|
153
|
-
// If the caller explicitly named a model, or the env auto-approves, or
|
|
154
|
-
// no AskUser bridge exists (batch / --prompt mode), skip the proposal
|
|
155
|
-
// step and use the old default. Otherwise: classifier picks a fitting
|
|
156
|
-
// model + rewrites the prompt, the preview goes to AskUser, user
|
|
157
|
-
// chooses or cancels.
|
|
162
|
+
// Pure tool: use exactly the prompt the caller gave — no LLM rewriting.
|
|
163
|
+
const prompt = rawInput.prompt;
|
|
158
164
|
// Reference-image mode forces an edit-capable model. If the caller named
|
|
159
165
|
// an unsupported one, fail loudly so we don't silently downgrade their
|
|
160
166
|
// request to text-only generation.
|
|
@@ -165,9 +171,9 @@ function buildExecute(deps) {
|
|
|
165
171
|
isError: true,
|
|
166
172
|
};
|
|
167
173
|
}
|
|
168
|
-
|
|
174
|
+
const imageModel = model || (editMode ? 'openai/gpt-image-2' : 'openai/gpt-image-1');
|
|
169
175
|
let imageSize = size || '1024x1024';
|
|
170
|
-
|
|
176
|
+
const chosenPrompt = prompt;
|
|
171
177
|
// ── Edit-mode constraint checks (mirror the gateway, fail before paying) ──
|
|
172
178
|
if (editMode) {
|
|
173
179
|
// Mask inpainting is OpenAI-only.
|
|
@@ -198,57 +204,6 @@ function buildExecute(deps) {
|
|
|
198
204
|
};
|
|
199
205
|
}
|
|
200
206
|
}
|
|
201
|
-
// Skip the proposal flow when a reference image is set: the media router
|
|
202
|
-
// doesn't know which models support image-to-image, so its suggestions
|
|
203
|
-
// would frequently be unusable (text-only models). Default to gpt-image-1
|
|
204
|
-
// for now; a future router upgrade can pick between the four edit-capable
|
|
205
|
-
// models based on the prompt.
|
|
206
|
-
const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
|
|
207
|
-
if (!model && !autoApprove && ctx.onAskUser && !editMode) {
|
|
208
|
-
try {
|
|
209
|
-
const chain = loadChain();
|
|
210
|
-
const client = new ModelClient({ apiUrl: API_URLS[chain], chain });
|
|
211
|
-
const proposal = await analyzeMediaRequest({
|
|
212
|
-
kind: 'image',
|
|
213
|
-
prompt,
|
|
214
|
-
quantity: n,
|
|
215
|
-
client,
|
|
216
|
-
signal: ctx.abortSignal,
|
|
217
|
-
skipRefine,
|
|
218
|
-
});
|
|
219
|
-
if (proposal) {
|
|
220
|
-
const { question, options } = renderProposalForAskUser(proposal, prompt);
|
|
221
|
-
const labels = options.map(o => o.label);
|
|
222
|
-
const answer = await ctx.onAskUser(question, labels);
|
|
223
|
-
// Map the user's returned label back to an option id
|
|
224
|
-
const chosen = options.find(o => o.label === answer) ?? { id: 'cancel' };
|
|
225
|
-
switch (chosen.id) {
|
|
226
|
-
case 'cheaper':
|
|
227
|
-
imageModel = proposal.cheaper?.model ?? proposal.recommended.model;
|
|
228
|
-
break;
|
|
229
|
-
case 'premium':
|
|
230
|
-
imageModel = proposal.premium?.model ?? proposal.recommended.model;
|
|
231
|
-
break;
|
|
232
|
-
case 'cancel':
|
|
233
|
-
return {
|
|
234
|
-
output: `## Image generation cancelled\n\nNo USDC was spent. Ask again when ready, or pass an explicit \`model\` to skip the confirmation step.`,
|
|
235
|
-
};
|
|
236
|
-
case 'use-raw':
|
|
237
|
-
imageModel = proposal.recommended.model;
|
|
238
|
-
// chosenPrompt stays as the raw input
|
|
239
|
-
break;
|
|
240
|
-
case 'recommended':
|
|
241
|
-
default:
|
|
242
|
-
imageModel = proposal.recommended.model;
|
|
243
|
-
if (proposal.refinedPrompt)
|
|
244
|
-
chosenPrompt = proposal.refinedPrompt;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
catch {
|
|
249
|
-
// Router / AskUser failed — fall back to default model silently.
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
207
|
// gpt-image-2 reliably serves 1024x1024 only — other sizes time out at
|
|
253
208
|
// the gateway. Force the supported size regardless of caller / router
|
|
254
209
|
// input so we never burn USDC on a request that's going to abort.
|
|
@@ -267,8 +222,22 @@ function buildExecute(deps) {
|
|
|
267
222
|
isError: true,
|
|
268
223
|
};
|
|
269
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);
|
|
270
239
|
if (contentId && deps.library) {
|
|
271
|
-
const decision = checkImageBudget(deps.library, contentId, imageModel, imageSize, n);
|
|
240
|
+
const decision = checkImageBudget(deps.library, contentId, imageModel, imageSize, n, perImageUsd * n);
|
|
272
241
|
if (!decision.ok) {
|
|
273
242
|
// Normal text output, not isError — the agent should adapt (smaller
|
|
274
243
|
// size, different model, raise budget) rather than trigger retry.
|
|
@@ -280,6 +249,20 @@ function buildExecute(deps) {
|
|
|
280
249
|
};
|
|
281
250
|
}
|
|
282
251
|
}
|
|
252
|
+
// Confirm the spend before the paid call (parity with VideoGen). Pure price
|
|
253
|
+
// math — no LLM. Interactive callers (CLI / agent) get a prompt via
|
|
254
|
+
// onAskUser; direct callers (e.g. the desktop media path) pass no onAskUser
|
|
255
|
+
// and generate straight away — the explicit "generate" action is consent.
|
|
256
|
+
const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
|
|
257
|
+
if (!autoApprove && ctx.onAskUser) {
|
|
258
|
+
const est = perImageUsd * n;
|
|
259
|
+
const priceNote = est > 0 ? ` for ~$${est.toFixed(2)}` : '';
|
|
260
|
+
const countNote = n > 1 ? `${n} images` : 'an image';
|
|
261
|
+
const answer = await ctx.onAskUser(`Generate ${countNote} with ${imageModel}${priceNote}? No USDC is spent if you cancel.`, ['Generate', 'Cancel']);
|
|
262
|
+
if (answer !== 'Generate') {
|
|
263
|
+
return { output: `## Image generation cancelled\n\nNo USDC was spent.` };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
283
266
|
// Resolve all reference images + the mask into base64 data URIs now, right
|
|
284
267
|
// before the paid call. Done after the cheap validations so bad paths /
|
|
285
268
|
// oversize attachments / unsupported combinations fail without any network
|
|
@@ -463,8 +446,7 @@ function buildExecute(deps) {
|
|
|
463
446
|
const latencyMs = Date.now() - callStartedAt;
|
|
464
447
|
void (async () => {
|
|
465
448
|
try {
|
|
466
|
-
const
|
|
467
|
-
const estCost = m ? estimateCostUsd(m, { quantity: items.length }) : 0;
|
|
449
|
+
const estCost = perImageUsd * items.length;
|
|
468
450
|
recordUsage(imageModel, 0, 0, estCost, latencyMs);
|
|
469
451
|
}
|
|
470
452
|
catch { /* ignore stats errors */ }
|
|
@@ -482,6 +464,7 @@ function buildExecute(deps) {
|
|
|
482
464
|
imagePath: p,
|
|
483
465
|
model: imageModel,
|
|
484
466
|
size: imageSize,
|
|
467
|
+
costUsd: perImageUsd,
|
|
485
468
|
});
|
|
486
469
|
if (rec.ok) {
|
|
487
470
|
attached++;
|
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,23 @@ 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';
|
|
21
22
|
const DEFAULT_MODEL = 'minimax/music-2.5+';
|
|
23
|
+
// Flat per-track price for the default model — already margin-inclusive
|
|
24
|
+
// ($0.15/track × 1.05 gateway margin). Fallback when the catalog is unavailable.
|
|
22
25
|
const PRICE_USD = 0.1575;
|
|
26
|
+
/**
|
|
27
|
+
* Resolve the per-track USD cost for the budget check + asset record. The `model`
|
|
28
|
+
* param is caller-selectable, so a pricier non-default music model would be
|
|
29
|
+
* charged its real price by the gateway but counted at the flat default
|
|
30
|
+
* otherwise — the same undercount class the ImageGen/VideoGen fixes close. Take
|
|
31
|
+
* the higher of the live catalog price (already margin-inclusive via
|
|
32
|
+
* estimateCostUsd) and the flat PRICE_USD. Exported for tests.
|
|
33
|
+
*/
|
|
34
|
+
export function resolveMusicUnitCost(catalogModel) {
|
|
35
|
+
const catalogUsd = catalogModel ? estimateCostUsd(catalogModel, {}) : 0;
|
|
36
|
+
return Math.max(catalogUsd, PRICE_USD);
|
|
37
|
+
}
|
|
23
38
|
// MiniMax generation is 1-3 minutes + small buffer for payment + download.
|
|
24
39
|
const GEN_TIMEOUT_MS = 240_000;
|
|
25
40
|
const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
@@ -35,16 +50,25 @@ function buildExecute(deps) {
|
|
|
35
50
|
};
|
|
36
51
|
}
|
|
37
52
|
const musicModel = model || DEFAULT_MODEL;
|
|
53
|
+
// Resolve the per-track cost ONCE (catalog price if available, else the flat
|
|
54
|
+
// default) — reused by the budget check and the asset record so a pricier
|
|
55
|
+
// non-default model can't undercount the content budget. Best-effort lookup.
|
|
56
|
+
let musicCatalogModel = null;
|
|
57
|
+
try {
|
|
58
|
+
musicCatalogModel = await findModel(musicModel);
|
|
59
|
+
}
|
|
60
|
+
catch { /* catalog unreachable — resolveMusicUnitCost falls back to PRICE_USD */ }
|
|
61
|
+
const trackCostUsd = resolveMusicUnitCost(musicCatalogModel);
|
|
38
62
|
if (contentId && deps.library) {
|
|
39
63
|
const content = deps.library.get(contentId);
|
|
40
64
|
if (!content) {
|
|
41
65
|
return { output: `Content ${contentId} not found. No USDC was spent.` };
|
|
42
66
|
}
|
|
43
|
-
if (content.spentUsd +
|
|
67
|
+
if (content.spentUsd + trackCostUsd > content.budgetUsd + 1e-9) {
|
|
44
68
|
return {
|
|
45
69
|
output: `## Music generation skipped\n` +
|
|
46
70
|
`- Would exceed budget: spent $${content.spentUsd.toFixed(2)} + fixed ` +
|
|
47
|
-
`$${
|
|
71
|
+
`$${trackCostUsd.toFixed(2)} > cap $${content.budgetUsd.toFixed(2)}\n\n` +
|
|
48
72
|
`No USDC was spent.`,
|
|
49
73
|
};
|
|
50
74
|
}
|
|
@@ -126,7 +150,7 @@ function buildExecute(deps) {
|
|
|
126
150
|
const rec = deps.library.addAsset(contentId, {
|
|
127
151
|
kind: 'audio',
|
|
128
152
|
source: musicModel,
|
|
129
|
-
costUsd:
|
|
153
|
+
costUsd: trackCostUsd,
|
|
130
154
|
data: outPath,
|
|
131
155
|
});
|
|
132
156
|
if (rec.ok) {
|
|
@@ -135,7 +159,7 @@ function buildExecute(deps) {
|
|
|
135
159
|
const c = deps.library.get(contentId);
|
|
136
160
|
contentSummary =
|
|
137
161
|
`\n\n## Content updated\n` +
|
|
138
|
-
`- Attached to \`${contentId}\` at est. $${
|
|
162
|
+
`- Attached to \`${contentId}\` at est. $${trackCostUsd.toFixed(2)}\n` +
|
|
139
163
|
(c
|
|
140
164
|
? `- Spent: $${c.spentUsd.toFixed(2)} / $${c.budgetUsd.toFixed(2)} cap ` +
|
|
141
165
|
`(remaining $${(c.budgetUsd - c.spentUsd).toFixed(2)})`
|
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;
|
package/dist/tools/videogen.js
CHANGED
|
@@ -24,10 +24,8 @@ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, creat
|
|
|
24
24
|
import { loadChain, API_URLS, VERSION } from '../config.js';
|
|
25
25
|
import { logger } from '../logger.js';
|
|
26
26
|
import { resolveReferenceImage } from './imagegen.js';
|
|
27
|
-
import { ModelClient } from '../agent/llm.js';
|
|
28
|
-
import { analyzeMediaRequest, renderProposalForAskUser } from '../agent/media-router.js';
|
|
29
27
|
import { recordUsage } from '../stats/tracker.js';
|
|
30
|
-
import { findModel, estimateCostUsd } from '../gateway-models.js';
|
|
28
|
+
import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
|
|
31
29
|
// BytePlus RealFace asset IDs from the RealFace tool (after H5 liveness +
|
|
32
30
|
// enrollment). Format: `ta_` + alphanumeric.
|
|
33
31
|
const REAL_FACE_ASSET_ID_REGEX = /^ta_[A-Za-z0-9]+$/;
|
|
@@ -48,6 +46,20 @@ const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
|
48
46
|
function estimateVideoCostUsd(durationSeconds = DEFAULT_DURATION) {
|
|
49
47
|
return Math.max(1, durationSeconds) * PRICE_PER_SECOND_USD;
|
|
50
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* Resolve the per-clip USD cost used for the spend confirm, budget check, usage
|
|
51
|
+
* stats, AND the content-budget asset record — one value so they can never
|
|
52
|
+
* disagree. The flat $0.05/s estimate is the fallback for an unknown model, but
|
|
53
|
+
* a catalog-priced per-second model (e.g. Seedance at $0.15/s) costs far more,
|
|
54
|
+
* so take the HIGHER of the catalog price and the (margin-adjusted) flat
|
|
55
|
+
* estimate. Without this the budget check + asset record undercount the cap ~3x
|
|
56
|
+
* for Seedance. Mirrors ImageGen's resolveImageUnitCost. Exported for tests.
|
|
57
|
+
*/
|
|
58
|
+
export function resolveVideoUnitCost(catalogModel, durationSeconds) {
|
|
59
|
+
const catalogUsd = catalogModel ? estimateCostUsd(catalogModel, { duration_seconds: durationSeconds }) : 0;
|
|
60
|
+
const flatUsd = +(estimateVideoCostUsd(durationSeconds) * GATEWAY_MARGIN).toFixed(6);
|
|
61
|
+
return Math.max(catalogUsd, flatUsd);
|
|
62
|
+
}
|
|
51
63
|
function buildExecute(deps) {
|
|
52
64
|
return async function execute(input, ctx) {
|
|
53
65
|
const rawInput = input;
|
|
@@ -100,68 +112,38 @@ function buildExecute(deps) {
|
|
|
100
112
|
};
|
|
101
113
|
}
|
|
102
114
|
}
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
115
|
+
// Pure tool: use exactly the model + prompt + duration the caller gave.
|
|
116
|
+
// No LLM prompt-rewriting or model "routing" — the UI / agent decides those
|
|
117
|
+
// upstream. (This removes a second, flaky free-model call that used to time
|
|
118
|
+
// out and made "video generation" appear broken.)
|
|
119
|
+
const prompt = rawInput.prompt;
|
|
120
|
+
const videoModel = model || DEFAULT_MODEL;
|
|
121
|
+
const duration = duration_seconds ?? DEFAULT_DURATION;
|
|
122
|
+
const chosenPrompt = prompt;
|
|
123
|
+
// Video bills per second — confirm the cost before spending. This is pure
|
|
124
|
+
// price math (no LLM). Interactive callers (CLI / agent) get a prompt via
|
|
125
|
+
// onAskUser; direct callers (e.g. the desktop media path) pass no onAskUser
|
|
126
|
+
// and generate straight away — the explicit "generate" action is consent.
|
|
127
|
+
// Resolve the per-clip cost ONCE — reused below by the confirm quote, the
|
|
128
|
+
// budget pre-check, usage stats, and the asset record so none can disagree
|
|
129
|
+
// or undercount a catalog-priced model. Best-effort catalog lookup: a cold
|
|
130
|
+
// fetch failure degrades to the flat estimate, never aborts a generation.
|
|
131
|
+
let videoCatalogModel = null;
|
|
132
|
+
try {
|
|
133
|
+
videoCatalogModel = await findModel(videoModel);
|
|
110
134
|
}
|
|
111
|
-
|
|
112
|
-
let duration = duration_seconds ?? DEFAULT_DURATION;
|
|
113
|
-
let chosenPrompt = prompt;
|
|
114
|
-
// ── Media router + AskUser flow (video bills per second, always ask) ──
|
|
135
|
+
catch { /* catalog unreachable — resolveVideoUnitCost falls back to the estimate */ }
|
|
115
136
|
const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
|
|
116
|
-
if (!
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
durationSeconds: duration_seconds,
|
|
124
|
-
client,
|
|
125
|
-
signal: ctx.abortSignal,
|
|
126
|
-
skipRefine,
|
|
127
|
-
});
|
|
128
|
-
if (proposal) {
|
|
129
|
-
const { question, options } = renderProposalForAskUser(proposal, prompt);
|
|
130
|
-
const labels = options.map(o => o.label);
|
|
131
|
-
const answer = await ctx.onAskUser(question, labels);
|
|
132
|
-
const chosen = options.find(o => o.label === answer) ?? { id: 'cancel' };
|
|
133
|
-
switch (chosen.id) {
|
|
134
|
-
case 'cheaper':
|
|
135
|
-
videoModel = proposal.cheaper?.model ?? proposal.recommended.model;
|
|
136
|
-
break;
|
|
137
|
-
case 'premium':
|
|
138
|
-
videoModel = proposal.premium?.model ?? proposal.recommended.model;
|
|
139
|
-
break;
|
|
140
|
-
case 'cancel':
|
|
141
|
-
return {
|
|
142
|
-
output: `## Video generation cancelled\n\nNo USDC was spent.`,
|
|
143
|
-
};
|
|
144
|
-
case 'use-raw':
|
|
145
|
-
videoModel = proposal.recommended.model;
|
|
146
|
-
// chosenPrompt stays as the raw input
|
|
147
|
-
break;
|
|
148
|
-
case 'recommended':
|
|
149
|
-
default:
|
|
150
|
-
videoModel = proposal.recommended.model;
|
|
151
|
-
if (proposal.refinedPrompt)
|
|
152
|
-
chosenPrompt = proposal.refinedPrompt;
|
|
153
|
-
}
|
|
154
|
-
// Use the proposal's duration — the router honored the user's
|
|
155
|
-
// duration_seconds or filled in the model's default.
|
|
156
|
-
if (proposal.durationSeconds)
|
|
157
|
-
duration = proposal.durationSeconds;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
catch {
|
|
161
|
-
// Router / AskUser failed — fall through to legacy default.
|
|
137
|
+
if (!autoApprove && ctx.onAskUser) {
|
|
138
|
+
// Model-aware estimate so the quoted price matches the model we name in
|
|
139
|
+
// the prompt (flat per-second fallback only when the model is unknown).
|
|
140
|
+
const est = resolveVideoUnitCost(videoCatalogModel, duration);
|
|
141
|
+
const answer = await ctx.onAskUser(`Generate a ${duration}s video with ${videoModel} for ~$${est.toFixed(2)}? No USDC is spent if you cancel.`, ['Generate', 'Cancel']);
|
|
142
|
+
if (answer !== 'Generate') {
|
|
143
|
+
return { output: `## Video generation cancelled\n\nNo USDC was spent.` };
|
|
162
144
|
}
|
|
163
145
|
}
|
|
164
|
-
const estCost =
|
|
146
|
+
const estCost = resolveVideoUnitCost(videoCatalogModel, duration);
|
|
165
147
|
if (contentId && deps.library) {
|
|
166
148
|
const content = deps.library.get(contentId);
|
|
167
149
|
if (!content) {
|
|
@@ -334,28 +316,24 @@ function buildExecute(deps) {
|
|
|
334
316
|
const fileSize = fs.statSync(outPath).size;
|
|
335
317
|
const sizeMB = (fileSize / 1_048_576).toFixed(1);
|
|
336
318
|
const dur = videoData.duration_seconds ?? duration;
|
|
319
|
+
// Single authoritative cost for the actual generated duration — same
|
|
320
|
+
// value for stats and the content-budget record (no undercount).
|
|
321
|
+
const recCostUsd = resolveVideoUnitCost(videoCatalogModel, dur);
|
|
337
322
|
// Stats: record this generation so it shows up in `franklin insights`
|
|
338
323
|
// alongside chat spend. Before this, media generations bypassed
|
|
339
324
|
// recordUsage entirely, so the insights panel under-reported total
|
|
340
325
|
// spend and never surfaced video models in its "top models" list.
|
|
341
|
-
// Prefer the live gateway price when the model is in the catalog;
|
|
342
|
-
// fall back to the legacy $0.05/s estimate otherwise. Fire-and-
|
|
343
|
-
// forget — stats write must not fail a user-visible generation.
|
|
344
326
|
const latencyMs = Date.now() - callStartedAt;
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
recordUsage(videoModel, 0, 0, estCost, latencyMs);
|
|
350
|
-
}
|
|
351
|
-
catch { /* ignore stats errors */ }
|
|
352
|
-
})();
|
|
327
|
+
try {
|
|
328
|
+
recordUsage(videoModel, 0, 0, recCostUsd, latencyMs);
|
|
329
|
+
}
|
|
330
|
+
catch { /* ignore stats errors */ }
|
|
353
331
|
let contentSummary = '';
|
|
354
332
|
if (contentId && deps.library) {
|
|
355
333
|
const rec = deps.library.addAsset(contentId, {
|
|
356
334
|
kind: 'video',
|
|
357
335
|
source: videoModel,
|
|
358
|
-
costUsd:
|
|
336
|
+
costUsd: recCostUsd,
|
|
359
337
|
data: outPath,
|
|
360
338
|
});
|
|
361
339
|
if (rec.ok) {
|
|
@@ -364,7 +342,7 @@ function buildExecute(deps) {
|
|
|
364
342
|
const c = deps.library.get(contentId);
|
|
365
343
|
contentSummary =
|
|
366
344
|
`\n\n## Content updated\n` +
|
|
367
|
-
`- Attached to \`${contentId}\` at est. $${
|
|
345
|
+
`- Attached to \`${contentId}\` at est. $${recCostUsd.toFixed(2)}\n` +
|
|
368
346
|
(c
|
|
369
347
|
? `- Spent: $${c.spentUsd.toFixed(2)} / $${c.budgetUsd.toFixed(2)} cap ` +
|
|
370
348
|
`(remaining $${(c.budgetUsd - c.spentUsd).toFixed(2)})`
|
package/dist/tools/voice.js
CHANGED
|
@@ -307,32 +307,40 @@ export const voiceCallCapability = {
|
|
|
307
307
|
try {
|
|
308
308
|
const res = await postWithPayment('/v1/voice/call', body, ctx, { tool: 'VoiceCall', priceUsd: 0.54 });
|
|
309
309
|
const callId = (res.call_id || res.id);
|
|
310
|
+
// No call_id on a 200 means the call didn't actually start — surface it
|
|
311
|
+
// as an error instead of reporting "initiated" after the $0.54 charge,
|
|
312
|
+
// otherwise the agent tells the user it worked but can never poll it
|
|
313
|
+
// (parity with the missing-identifier guards in imagegen/videogen).
|
|
314
|
+
if (!callId) {
|
|
315
|
+
return {
|
|
316
|
+
output: `VoiceCall: the gateway returned no call_id, so the call may not have started ` +
|
|
317
|
+
`(you may still have been charged $0.54 — check VoiceStatus / your balance).\n\n` +
|
|
318
|
+
'```json\n' + JSON.stringify(res, null, 2) + '\n```',
|
|
319
|
+
isError: true,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
310
322
|
// Persist a "queued" row so the panel sees the call before VoiceStatus polls.
|
|
311
323
|
// Best-effort — if disk write fails we still surface the call_id to the agent.
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
catch { /* best-effort */ }
|
|
324
|
+
try {
|
|
325
|
+
callLog().append({
|
|
326
|
+
timestamp: Date.now(),
|
|
327
|
+
call_id: callId,
|
|
328
|
+
to: String(input.to),
|
|
329
|
+
from: String(input.from),
|
|
330
|
+
task: String(input.task),
|
|
331
|
+
voice: typeof input.voice === 'string' ? input.voice : undefined,
|
|
332
|
+
max_duration_min: typeof input.max_duration === 'number' ? input.max_duration : undefined,
|
|
333
|
+
language: typeof input.language === 'string' ? input.language : undefined,
|
|
334
|
+
status: normalizeStatus(res.status),
|
|
335
|
+
paid_usd: 0.54,
|
|
336
|
+
tx_hash: typeof res.tx_hash === 'string' ? res.tx_hash : undefined,
|
|
337
|
+
});
|
|
329
338
|
}
|
|
339
|
+
catch { /* best-effort */ }
|
|
330
340
|
return {
|
|
331
341
|
output: `## Voice call initiated ($0.54 USDC charged)\n\n` +
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
`transcript and disposition. The call typically completes in 1–6 minutes.\n\n`
|
|
335
|
-
: '') +
|
|
342
|
+
`**call_id:** \`${callId}\`\n\nPoll with VoiceStatus call_id="${callId}" to get the ` +
|
|
343
|
+
`transcript and disposition. The call typically completes in 1–6 minutes.\n\n` +
|
|
336
344
|
'```json\n' + JSON.stringify(res, null, 2) + '\n```',
|
|
337
345
|
};
|
|
338
346
|
}
|
|
@@ -46,6 +46,13 @@ export interface TelemetrySnapshot {
|
|
|
46
46
|
recentPaidCalls: PaidCallRow[];
|
|
47
47
|
}
|
|
48
48
|
export declare function snapshot(): TelemetrySnapshot;
|
|
49
|
+
/**
|
|
50
|
+
* Real BlockRun spend recorded so far today (USD). `recordFetch` only adds to
|
|
51
|
+
* this on an actual paid fetch — a short-TTL cache hit records nothing — so a
|
|
52
|
+
* caller can measure the true cost of a single paid call by diffing this around
|
|
53
|
+
* the call (delta 0 on a cache hit, $0.001 on a fresh stock-price fetch).
|
|
54
|
+
*/
|
|
55
|
+
export declare function blockrunSpendUsdToday(): number;
|
|
49
56
|
/** Test helper: reset all counters. Do not call in production code paths. */
|
|
50
57
|
export declare function resetTelemetry(): void;
|
|
51
58
|
export {};
|
|
@@ -107,6 +107,15 @@ export function snapshot() {
|
|
|
107
107
|
recentPaidCalls: [...paidRecent].reverse(),
|
|
108
108
|
};
|
|
109
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Real BlockRun spend recorded so far today (USD). `recordFetch` only adds to
|
|
112
|
+
* this on an actual paid fetch — a short-TTL cache hit records nothing — so a
|
|
113
|
+
* caller can measure the true cost of a single paid call by diffing this around
|
|
114
|
+
* the call (delta 0 on a cache hit, $0.001 on a fresh stock-price fetch).
|
|
115
|
+
*/
|
|
116
|
+
export function blockrunSpendUsdToday() {
|
|
117
|
+
return rolls.blockrun.spendUsdToday;
|
|
118
|
+
}
|
|
110
119
|
/** Test helper: reset all counters. Do not call in production code paths. */
|
|
111
120
|
export function resetTelemetry() {
|
|
112
121
|
rolls.coingecko = newRoll();
|
package/dist/trading/store.js
CHANGED
|
@@ -4,14 +4,20 @@
|
|
|
4
4
|
* errors never throw — a missing or corrupt file just returns `null` so the
|
|
5
5
|
* agent can fall back to a fresh portfolio rather than refusing to start.
|
|
6
6
|
*/
|
|
7
|
-
import { existsSync, readFileSync
|
|
8
|
-
import { dirname } from 'node:path';
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
9
8
|
import { Portfolio } from './portfolio.js';
|
|
9
|
+
import { atomicWriteFileSync } from '../storage/atomic.js';
|
|
10
10
|
export function savePortfolio(pf, filePath) {
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
// Atomic write so a crash mid-save can't truncate portfolio.json and
|
|
12
|
+
// silently reset cross-session P&L (see storage/atomic.ts).
|
|
13
|
+
atomicWriteFileSync(filePath, JSON.stringify(pf.snapshot(), null, 2));
|
|
13
14
|
}
|
|
14
15
|
export function loadPortfolio(filePath) {
|
|
16
|
+
// Prefer the live file; fall back to the atomic-write backup if it's
|
|
17
|
+
// missing or corrupt rather than zeroing the portfolio.
|
|
18
|
+
return readPortfolioFile(filePath) ?? readPortfolioFile(`${filePath}.bak`);
|
|
19
|
+
}
|
|
20
|
+
function readPortfolioFile(filePath) {
|
|
15
21
|
if (!existsSync(filePath))
|
|
16
22
|
return null;
|
|
17
23
|
try {
|
|
@@ -26,7 +32,7 @@ export function loadPortfolio(filePath) {
|
|
|
26
32
|
return pf;
|
|
27
33
|
}
|
|
28
34
|
catch {
|
|
29
|
-
// Corrupt JSON —
|
|
35
|
+
// Corrupt JSON — caller falls back to .bak, then to a fresh portfolio.
|
|
30
36
|
return null;
|
|
31
37
|
}
|
|
32
38
|
}
|
package/dist/ui/terminal.js
CHANGED
|
@@ -278,9 +278,19 @@ export class TerminalUI {
|
|
|
278
278
|
}
|
|
279
279
|
}
|
|
280
280
|
else if (output.trim()) {
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
281
|
+
if (process.env.FRANKLIN_E2E_FULL_TOOL_OUTPUT === '1') {
|
|
282
|
+
// e2e: emit the full tool output so tests can assert on
|
|
283
|
+
// tool-rendered markers (e.g. Exa's `_Cost: $` footer) that prove
|
|
284
|
+
// the live payload actually parsed — not just the model's
|
|
285
|
+
// narrative, which it can fabricate from training data.
|
|
286
|
+
for (const line of output.split('\n'))
|
|
287
|
+
console.error(chalk.dim(` ⎿ ${line}`));
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
// Other tools: show first line as preview
|
|
291
|
+
const preview = truncateOutput(output, 120);
|
|
292
|
+
console.error(chalk.dim(` ⎿ ${preview}`));
|
|
293
|
+
}
|
|
284
294
|
}
|
|
285
295
|
}
|
|
286
296
|
break;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blockrun/franklin",
|
|
3
|
-
"version": "3.29.
|
|
3
|
+
"version": "3.29.7",
|
|
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": {
|
|
@@ -31,11 +31,11 @@
|
|
|
31
31
|
"build": "tsc && node scripts/copy-plugin-assets.mjs",
|
|
32
32
|
"dev": "tsc --watch",
|
|
33
33
|
"start": "node dist/index.js",
|
|
34
|
-
"test": "npm run build && node --test --test-reporter=spec test/local.mjs test/skills.local.mjs test/repair.mjs",
|
|
34
|
+
"test": "npm run build && node --test --test-reporter=spec test/local.mjs test/skills.local.mjs test/repair.mjs test/exa.local.mjs test/audit-batch.local.mjs",
|
|
35
35
|
"test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
|
|
36
36
|
"test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",
|
|
37
37
|
"test:all": "npm run test && npm run test:e2e",
|
|
38
|
-
"test:watch": "node --test --watch test/local.mjs test/skills.local.mjs",
|
|
38
|
+
"test:watch": "node --test --watch test/local.mjs test/skills.local.mjs test/exa.local.mjs test/audit-batch.local.mjs",
|
|
39
39
|
"test:e2e:watch": "node --test --watch test/e2e.mjs"
|
|
40
40
|
},
|
|
41
41
|
"keywords": [
|