@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.
@@ -25,7 +25,7 @@ import { loadChain, API_URLS, VERSION } from '../config.js';
25
25
  import { logger } from '../logger.js';
26
26
  import { resolveReferenceImage } from './imagegen.js';
27
27
  import { recordUsage } from '../stats/tracker.js';
28
- import { findModel, estimateCostUsd } from '../gateway-models.js';
28
+ import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
29
29
  // BytePlus RealFace asset IDs from the RealFace tool (after H5 liveness +
30
30
  // enrollment). Format: `ta_` + alphanumeric.
31
31
  const REAL_FACE_ASSET_ID_REGEX = /^ta_[A-Za-z0-9]+$/;
@@ -46,6 +46,20 @@ const DOWNLOAD_TIMEOUT_MS = 60_000;
46
46
  function estimateVideoCostUsd(durationSeconds = DEFAULT_DURATION) {
47
47
  return Math.max(1, durationSeconds) * PRICE_PER_SECOND_USD;
48
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
+ }
49
63
  function buildExecute(deps) {
50
64
  return async function execute(input, ctx) {
51
65
  const rawInput = input;
@@ -110,18 +124,26 @@ function buildExecute(deps) {
110
124
  // price math (no LLM). Interactive callers (CLI / agent) get a prompt via
111
125
  // onAskUser; direct callers (e.g. the desktop media path) pass no onAskUser
112
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);
134
+ }
135
+ catch { /* catalog unreachable — resolveVideoUnitCost falls back to the estimate */ }
113
136
  const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1';
114
137
  if (!autoApprove && ctx.onAskUser) {
115
138
  // Model-aware estimate so the quoted price matches the model we name in
116
139
  // the prompt (flat per-second fallback only when the model is unknown).
117
- const m = await findModel(videoModel);
118
- const est = m ? estimateCostUsd(m, { duration_seconds: duration }) : estimateVideoCostUsd(duration);
140
+ const est = resolveVideoUnitCost(videoCatalogModel, duration);
119
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']);
120
142
  if (answer !== 'Generate') {
121
143
  return { output: `## Video generation cancelled\n\nNo USDC was spent.` };
122
144
  }
123
145
  }
124
- const estCost = estimateVideoCostUsd(duration);
146
+ const estCost = resolveVideoUnitCost(videoCatalogModel, duration);
125
147
  if (contentId && deps.library) {
126
148
  const content = deps.library.get(contentId);
127
149
  if (!content) {
@@ -294,28 +316,24 @@ function buildExecute(deps) {
294
316
  const fileSize = fs.statSync(outPath).size;
295
317
  const sizeMB = (fileSize / 1_048_576).toFixed(1);
296
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);
297
322
  // Stats: record this generation so it shows up in `franklin insights`
298
323
  // alongside chat spend. Before this, media generations bypassed
299
324
  // recordUsage entirely, so the insights panel under-reported total
300
325
  // spend and never surfaced video models in its "top models" list.
301
- // Prefer the live gateway price when the model is in the catalog;
302
- // fall back to the legacy $0.05/s estimate otherwise. Fire-and-
303
- // forget — stats write must not fail a user-visible generation.
304
326
  const latencyMs = Date.now() - callStartedAt;
305
- void (async () => {
306
- try {
307
- const m = await findModel(videoModel);
308
- const estCost = m ? estimateCostUsd(m, { duration_seconds: dur }) : estimateVideoCostUsd(dur);
309
- recordUsage(videoModel, 0, 0, estCost, latencyMs);
310
- }
311
- catch { /* ignore stats errors */ }
312
- })();
327
+ try {
328
+ recordUsage(videoModel, 0, 0, recCostUsd, latencyMs);
329
+ }
330
+ catch { /* ignore stats errors */ }
313
331
  let contentSummary = '';
314
332
  if (contentId && deps.library) {
315
333
  const rec = deps.library.addAsset(contentId, {
316
334
  kind: 'video',
317
335
  source: videoModel,
318
- costUsd: estimateVideoCostUsd(dur),
336
+ costUsd: recCostUsd,
319
337
  data: outPath,
320
338
  });
321
339
  if (rec.ok) {
@@ -324,7 +342,7 @@ function buildExecute(deps) {
324
342
  const c = deps.library.get(contentId);
325
343
  contentSummary =
326
344
  `\n\n## Content updated\n` +
327
- `- Attached to \`${contentId}\` at est. $${estimateVideoCostUsd(dur).toFixed(2)}\n` +
345
+ `- Attached to \`${contentId}\` at est. $${recCostUsd.toFixed(2)}\n` +
328
346
  (c
329
347
  ? `- Spent: $${c.spentUsd.toFixed(2)} / $${c.budgetUsd.toFixed(2)} cap ` +
330
348
  `(remaining $${(c.budgetUsd - c.spentUsd).toFixed(2)})`
@@ -103,7 +103,7 @@ async function postWithPayment(path, body, ctx, meta) {
103
103
  ctx.abortSignal.removeEventListener('abort', onAbort);
104
104
  }
105
105
  }
106
- async function getNoPayment(path, ctx, meta) {
106
+ async function getNoPayment(path, ctx, meta, record = true) {
107
107
  const startMs = Date.now();
108
108
  const chain = loadChain();
109
109
  const apiUrl = API_URLS[chain];
@@ -124,10 +124,14 @@ async function getNoPayment(path, ctx, meta) {
124
124
  }
125
125
  const data = (await resp.json());
126
126
  // Record even free calls so the audit tab shows the activity (cost 0).
127
- try {
128
- recordUsage(meta.tool, 0, 0, meta.priceUsd, Date.now() - startMs);
127
+ // `record: false` for internal poll loops — recording one row PER poll (up to
128
+ // 420 for VoiceStatus) would evict real spend history (capped at 1000 rows).
129
+ if (record) {
130
+ try {
131
+ recordUsage(meta.tool, 0, 0, meta.priceUsd, Date.now() - startMs);
132
+ }
133
+ catch { /* telemetry best-effort */ }
129
134
  }
130
- catch { /* telemetry best-effort */ }
131
135
  return data;
132
136
  }
133
137
  finally {
@@ -307,32 +311,40 @@ export const voiceCallCapability = {
307
311
  try {
308
312
  const res = await postWithPayment('/v1/voice/call', body, ctx, { tool: 'VoiceCall', priceUsd: 0.54 });
309
313
  const callId = (res.call_id || res.id);
314
+ // No call_id on a 200 means the call didn't actually start — surface it
315
+ // as an error instead of reporting "initiated" after the $0.54 charge,
316
+ // otherwise the agent tells the user it worked but can never poll it
317
+ // (parity with the missing-identifier guards in imagegen/videogen).
318
+ if (!callId) {
319
+ return {
320
+ output: `VoiceCall: the gateway returned no call_id, so the call may not have started ` +
321
+ `(you may still have been charged $0.54 — check VoiceStatus / your balance).\n\n` +
322
+ '```json\n' + JSON.stringify(res, null, 2) + '\n```',
323
+ isError: true,
324
+ };
325
+ }
310
326
  // Persist a "queued" row so the panel sees the call before VoiceStatus polls.
311
327
  // Best-effort — if disk write fails we still surface the call_id to the agent.
312
- if (callId) {
313
- try {
314
- callLog().append({
315
- timestamp: Date.now(),
316
- call_id: callId,
317
- to: String(input.to),
318
- from: String(input.from),
319
- task: String(input.task),
320
- voice: typeof input.voice === 'string' ? input.voice : undefined,
321
- max_duration_min: typeof input.max_duration === 'number' ? input.max_duration : undefined,
322
- language: typeof input.language === 'string' ? input.language : undefined,
323
- status: normalizeStatus(res.status),
324
- paid_usd: 0.54,
325
- tx_hash: typeof res.tx_hash === 'string' ? res.tx_hash : undefined,
326
- });
327
- }
328
- catch { /* best-effort */ }
328
+ try {
329
+ callLog().append({
330
+ timestamp: Date.now(),
331
+ call_id: callId,
332
+ to: String(input.to),
333
+ from: String(input.from),
334
+ task: String(input.task),
335
+ voice: typeof input.voice === 'string' ? input.voice : undefined,
336
+ max_duration_min: typeof input.max_duration === 'number' ? input.max_duration : undefined,
337
+ language: typeof input.language === 'string' ? input.language : undefined,
338
+ status: normalizeStatus(res.status),
339
+ paid_usd: 0.54,
340
+ tx_hash: typeof res.tx_hash === 'string' ? res.tx_hash : undefined,
341
+ });
329
342
  }
343
+ catch { /* best-effort */ }
330
344
  return {
331
345
  output: `## Voice call initiated ($0.54 USDC charged)\n\n` +
332
- (callId
333
- ? `**call_id:** \`${callId}\`\n\nPoll with VoiceStatus call_id="${callId}" to get the ` +
334
- `transcript and disposition. The call typically completes in 1–6 minutes.\n\n`
335
- : '') +
346
+ `**call_id:** \`${callId}\`\n\nPoll with VoiceStatus call_id="${callId}" to get the ` +
347
+ `transcript and disposition. The call typically completes in 1–6 minutes.\n\n` +
336
348
  '```json\n' + JSON.stringify(res, null, 2) + '\n```',
337
349
  };
338
350
  }
@@ -425,6 +437,14 @@ export const voiceStatusCapability = {
425
437
  }
426
438
  const callId = input.call_id;
427
439
  const deadline = Date.now() + VOICE_POLL_MAX_WAIT_MS;
440
+ const statusStartedAt = Date.now();
441
+ // Record ONE telemetry row per VoiceStatus invocation, not one per poll.
442
+ const recordStatusOnce = () => {
443
+ try {
444
+ recordUsage('VoiceStatus', 0, 0, 0, Date.now() - statusStartedAt);
445
+ }
446
+ catch { /* best-effort */ }
447
+ };
428
448
  // Internal poll-until-terminal loop — mirrors videogen.ts pollUntilReady
429
449
  // and imagegen.ts pollImageJob. The agent emits one VoiceStatus tool_use
430
450
  // and gets back the final transcript when the call ends. Without this
@@ -436,7 +456,7 @@ export const voiceStatusCapability = {
436
456
  return { output: 'VoiceStatus aborted by user', isError: true };
437
457
  }
438
458
  try {
439
- lastRes = await getNoPayment(`/v1/voice/call/${encodeURIComponent(callId)}`, ctx, { tool: 'VoiceStatus', priceUsd: 0 });
459
+ lastRes = await getNoPayment(`/v1/voice/call/${encodeURIComponent(callId)}`, ctx, { tool: 'VoiceStatus', priceUsd: 0 }, false);
440
460
  }
441
461
  catch (err) {
442
462
  return { output: `VoiceStatus failed: ${err.message}`, isError: true };
@@ -444,6 +464,7 @@ export const voiceStatusCapability = {
444
464
  patchCallJournal(callId, lastRes);
445
465
  const status = String(lastRes.status ?? lastRes.queue_status ?? '').toLowerCase();
446
466
  if (VOICE_TERMINAL_STATUSES.has(status)) {
467
+ recordStatusOnce();
447
468
  return {
448
469
  output: `## Voice call status (terminal: ${status})\n\n` +
449
470
  '```json\n' + JSON.stringify(lastRes, null, 2) + '\n```',
@@ -459,6 +480,7 @@ export const voiceStatusCapability = {
459
480
  // Hit the 35-min ceiling without seeing a terminal state — return the
460
481
  // latest snapshot we have so the agent + journal still have partial
461
482
  // context, but flag it as still in progress.
483
+ recordStatusOnce();
462
484
  return {
463
485
  output: `## Voice call status (still in progress after ${Math.round(VOICE_POLL_MAX_WAIT_MS / 60_000)} min)\n\n` +
464
486
  `Bland.ai upstream caps any single call at 30 min, so a call this long ` +
@@ -50,7 +50,11 @@ export class TradingEngine {
50
50
  if (!existing) {
51
51
  return { status: 'noop', reason: `No open ${req.symbol} position` };
52
52
  }
53
- const qty = req.qty ?? existing.qty;
53
+ // Clamp to the held size: an over-sized partial close just flattens the
54
+ // position rather than throwing 'only X held' out of applyFill (which the
55
+ // tool layer surfaced as a confusing generic error). You can never sell more
56
+ // than you hold, so flatten-on-over-size is the sensible interpretation.
57
+ const qty = Math.min(req.qty ?? existing.qty, existing.qty);
54
58
  const price = (await exchange.getPrice(req.symbol));
55
59
  if (price == null) {
56
60
  return { status: 'blocked', reason: `Exchange returned no price for ${req.symbol}` };
@@ -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();
@@ -35,9 +35,12 @@ export class RiskEngine {
35
35
  reason: `Insufficient cash: order needs $${notional.toFixed(2)} but only $${portfolio.cashUsd.toFixed(2)} available`,
36
36
  };
37
37
  }
38
- // Projected position value after fill.
38
+ // Projected position value after fill. Value the existing holding at its
39
+ // cost basis (avgPriceUsd), consistent with the total-exposure loop below —
40
+ // valuing it at the incoming order price let a buy slip the cap after a
41
+ // price drop (and over-block after a rise).
39
42
  const existing = portfolio.getPosition(order.symbol);
40
- const projectedPositionUsd = (existing ? existing.qty * order.priceUsd : 0) + notional;
43
+ const projectedPositionUsd = (existing ? existing.qty * existing.avgPriceUsd : 0) + notional;
41
44
  if (projectedPositionUsd > this.config.maxPositionUsd) {
42
45
  return {
43
46
  allowed: false,
@@ -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, writeFileSync, mkdirSync } from 'node:fs';
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
- mkdirSync(dirname(filePath), { recursive: true });
12
- writeFileSync(filePath, JSON.stringify(pf.snapshot(), null, 2), 'utf-8');
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 — start fresh rather than crash.
35
+ // Corrupt JSON — caller falls back to .bak, then to a fresh portfolio.
30
36
  return null;
31
37
  }
32
38
  }
@@ -278,9 +278,19 @@ export class TerminalUI {
278
278
  }
279
279
  }
280
280
  else if (output.trim()) {
281
- // Other tools: show first line as preview
282
- const preview = truncateOutput(output, 120);
283
- console.error(chalk.dim(` ⎿ ${preview}`));
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.4",
3
+ "version": "3.29.8",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -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": [