@blockrun/franklin 3.49.4 → 3.49.6

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.
@@ -19,6 +19,9 @@ import crypto from 'node:crypto';
19
19
  import { BLOCKRUN_DIR } from '../config.js';
20
20
  import { appendApprovalRecord } from '../audit/approvals.js';
21
21
  import { estimateSpendUsd, TRADE_EXECUTION_TOOLS } from '../tools/spend-tools.js';
22
+ import { resolveMint } from '../tools/jupiter.js';
23
+ import { resolveTokenAddress as resolveBaseToken } from '../tools/zerox-base.js';
24
+ import { resolveTokenAddress as resolveGaslessToken } from '../tools/zerox-gasless.js';
22
25
  import { captureTradeEvent } from '../memory/capture.js';
23
26
  import { getAddress } from '../wallet/manager.js';
24
27
  export const TRADE_PLAN_TTL_MS = 15 * 60 * 1000;
@@ -36,6 +39,7 @@ function planPath(id) {
36
39
  return path.join(tradePlansDir(), `${id}.json`);
37
40
  }
38
41
  export function saveTradePlan(plan) {
42
+ // TODO: protect read/modify/write with a cross-process lock.
39
43
  fs.mkdirSync(tradePlansDir(), { recursive: true });
40
44
  const tmp = path.join(tradePlansDir(), `.${plan.id}.tmp`);
41
45
  fs.writeFileSync(tmp, JSON.stringify(plan, null, 2));
@@ -111,7 +115,7 @@ export function createTradePlan(opts) {
111
115
  expiresAt: Date.now() + (opts.ttlMs ?? TRADE_PLAN_TTL_MS),
112
116
  status: 'pending',
113
117
  trades: opts.trades,
114
- totalSpendUsd: opts.trades.reduce((sum, t) => sum + t.amountUsd, 0),
118
+ totalSpendUsd: opts.trades.reduce((sum, t) => sum + usdUnits(t.amountUsd), 0) / 1e6,
115
119
  rationale: opts.rationale,
116
120
  consumedUsd: 0,
117
121
  };
@@ -119,11 +123,15 @@ export function createTradePlan(opts) {
119
123
  return plan;
120
124
  }
121
125
  export function decideTradePlan(plan, decision, by, reason) {
126
+ // Start from the stored plan, not the caller's copy: a plan object held
127
+ // across an execution would otherwise write back stale consumption and
128
+ // hand an already reserved or spent line its budget again.
129
+ const current = loadTradePlan(plan.id) ?? plan;
122
130
  const updated = {
123
- ...plan,
131
+ ...current,
124
132
  status: decision,
125
133
  decidedBy: by,
126
- changeRequest: decision === 'rejected' ? reason : plan.changeRequest,
134
+ changeRequest: decision === 'rejected' ? reason : current.changeRequest,
127
135
  };
128
136
  saveTradePlan(updated);
129
137
  appendApprovalRecord({
@@ -162,23 +170,91 @@ export function setTradePlanSessionId(id) {
162
170
  gateSessionId = id;
163
171
  }
164
172
  function planIsLive(plan) {
165
- return plan.status === 'approved' && plan.expiresAt > Date.now() && plan.consumedUsd < plan.totalSpendUsd;
173
+ return plan.status === 'approved' && plan.expiresAt > Date.now() && usdUnits(plan.consumedUsd) < usdUnits(plan.totalSpendUsd);
166
174
  }
167
175
  /** The session's live (approved, unexpired, unconsumed) plan, if any. */
168
176
  export function activeTradePlan(sessionId = gateSessionId) {
169
177
  return listTradePlans().find(p => p.sessionId === sessionId && planIsLive(p)) ?? null;
170
178
  }
171
- /** Does the tool input plausibly reference the planned asset? Lenient by design:
172
- * symbols vs mint addresses vs market ids all count as a mention anywhere in
173
- * the input values. A mismatch denies, so false negatives (blocking a covered
174
- * trade) are worse than false positives here — the budget cap still binds. */
175
- function assetMentioned(asset, input) {
176
- const needle = asset.toLowerCase();
177
- for (const value of Object.values(input)) {
178
- if (typeof value === 'string' && value.toLowerCase().includes(needle))
179
- return true;
179
+ // Integer micro-dollars avoid granting an extra cent on each execution.
180
+ function usdUnits(usd) {
181
+ return Math.round(usd * 1e6);
182
+ }
183
+ const authorizations = new WeakMap();
184
+ // Same reservations by invocation id, for denials that only know the id
185
+ // (permission prompt refused, PreSpend hook veto) before the tool ever ran.
186
+ const authorizationsById = new Map();
187
+ /**
188
+ * Move a plan's consumption by `deltaUnits` on one line, re-reading the plan
189
+ * from disk so the write starts from the latest state. Reservation (+) can
190
+ * mark the plan consumed; a release (-) can only reopen a plan that a
191
+ * reservation closed, never a cancelled/expired/rejected one.
192
+ */
193
+ function adjustPlanConsumption(planId, line, deltaUnits) {
194
+ const plan = loadTradePlan(planId);
195
+ if (!plan)
196
+ return null;
197
+ const consumedUnits = Math.max(0, usdUnits(plan.consumedUsd) + deltaUnits);
198
+ const consumedLineUsd = plan.trades.map((_, i) => Math.max(0, usdUnits(plan.consumedLineUsd?.[i] ?? 0) + (i === line ? deltaUnits : 0)) / 1e6);
199
+ const full = consumedUnits >= usdUnits(plan.totalSpendUsd);
200
+ const status = full && plan.status === 'approved' ? 'consumed'
201
+ : !full && plan.status === 'consumed' ? 'approved'
202
+ : plan.status;
203
+ const updated = { ...plan, consumedUsd: consumedUnits / 1e6, consumedLineUsd, status };
204
+ saveTradePlan(updated);
205
+ return updated;
206
+ }
207
+ /**
208
+ * Release a reservation for a call that was denied before it executed.
209
+ * Safe to call for any invocation id; a no-op when nothing was reserved.
210
+ */
211
+ export function releaseTradeReservation(invocationId) {
212
+ const invocation = authorizationsById.get(invocationId);
213
+ if (!invocation)
214
+ return;
215
+ authorizationsById.delete(invocationId);
216
+ const authorization = authorizations.get(invocation);
217
+ authorizations.delete(invocation);
218
+ if (authorization)
219
+ adjustPlanConsumption(authorization.planId, authorization.line, -authorization.units);
220
+ }
221
+ function matchesTrade(trade, invocation) {
222
+ const { name, input } = invocation;
223
+ const equal = (value, resolve = s => s.trim()) => typeof value === 'string' && resolve(value).toLowerCase() === resolve(trade.asset).toLowerCase();
224
+ if (name === 'PolymarketBet') {
225
+ if ((trade.action === 'bet' ? 'buy' : trade.action) !== input.action)
226
+ return false;
227
+ // token_id takes precedence in the tool; unused condition/outcome fields
228
+ // cannot authorize a different token or claim an unverified direction.
229
+ if (input.token_id)
230
+ return !trade.direction && equal(input.token_id);
231
+ if (!input.condition_id || !input.outcome)
232
+ return false;
233
+ if (trade.direction && String(input.outcome).toLowerCase() !== trade.direction)
234
+ return false;
235
+ // The market is identified by condition_id alone. An outcome label such as
236
+ // "Yes" exists in every market, so it can never stand in for the asset.
237
+ return equal(input.condition_id);
238
+ }
239
+ if (trade.action === 'bet')
240
+ return false;
241
+ if (name === 'JupiterSwap') {
242
+ return equal(input[trade.action === 'sell' ? 'input_mint' : 'output_mint'], resolveMint);
243
+ }
244
+ return equal(input[trade.action === 'sell' ? 'sell_token' : 'buy_token'], name === 'Base0xGaslessSwap' ? resolveGaslessToken : resolveBaseToken);
245
+ }
246
+ function tradeAmount(invocation) {
247
+ // Sells do not count as spend in hooks, but still consume their approved line.
248
+ if (invocation.name === 'PolymarketBet') {
249
+ const { price, size, action } = invocation.input;
250
+ if (typeof size === 'number' && Number.isFinite(size) && size > 0) {
251
+ if (action === 'sell')
252
+ return size; // a share can fill above its limit, up to $1
253
+ if (typeof price === 'number' && Number.isFinite(price) && price > 0 && price <= 1)
254
+ return price * size;
255
+ }
180
256
  }
181
- return false;
257
+ return estimateSpendUsd(invocation.name, invocation.input);
182
258
  }
183
259
  function isGatedInvocation(invocation) {
184
260
  if (!TRADE_EXECUTION_TOOLS.has(invocation.name))
@@ -202,11 +278,15 @@ function isGatedInvocation(invocation) {
202
278
  * skips its redundant per-swap confirm (the plan approval IS the confirm).
203
279
  */
204
280
  export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
281
+ // A re-check of the same invocation must not stack a second reservation.
282
+ if (authorizations.has(invocation))
283
+ releaseTradeReservation(invocation.id);
284
+ authorizations.delete(invocation);
205
285
  if (!isGatedInvocation(invocation))
206
286
  return null;
207
287
  const plan = activeTradePlan(sessionId);
208
288
  const venue = VENUE_BY_TOOL[invocation.name];
209
- const estimate = estimateSpendUsd(invocation.name, invocation.input);
289
+ const estimate = tradeAmount(invocation);
210
290
  if (!plan) {
211
291
  appendApprovalRecord({
212
292
  ts: Date.now(),
@@ -225,24 +305,56 @@ export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
225
305
  isError: true,
226
306
  };
227
307
  }
228
- const remaining = plan.totalSpendUsd - plan.consumedUsd;
229
- const matched = plan.trades.find(t => t.venue === venue && assetMentioned(t.asset, invocation.input));
230
- if (!matched) {
308
+ // Plans saved before per-line accounting carry spend that cannot be
309
+ // attributed to a line; treating their lines as unused would let an already
310
+ // consumed line run again. Require a fresh plan instead.
311
+ if (usdUnits(plan.consumedUsd) > 0 && !Array.isArray(plan.consumedLineUsd)) {
312
+ return {
313
+ output: `Trade blocked: plan ${plan.id} predates per-line budget tracking and has already been drawn on, ` +
314
+ 'so its remaining lines cannot be verified. Propose a new plan via the TradePlan tool.',
315
+ isError: true,
316
+ };
317
+ }
318
+ const remaining = usdUnits(plan.totalSpendUsd) - usdUnits(plan.consumedUsd);
319
+ const matching = plan.trades.map((trade, line) => ({ trade, line }))
320
+ .filter(({ trade }) => trade.venue === venue && matchesTrade(trade, invocation));
321
+ if (matching.length === 0) {
231
322
  return {
232
- output: `Trade blocked: approved plan ${plan.id} does not include a ${venue} trade matching this call's asset. ` +
323
+ output: `Trade blocked: approved plan ${plan.id} does not include a ${venue} trade matching this call's asset, action and direction. ` +
233
324
  'Either execute only the planned trades, or propose a new plan via the TradePlan tool.',
234
325
  isError: true,
235
326
  };
236
327
  }
237
- const spendNeeded = estimate ?? matched.amountUsd;
238
- if (spendNeeded > remaining + 0.01) {
328
+ if (estimate === null || !Number.isSafeInteger(usdUnits(estimate)) || usdUnits(estimate) <= 0) {
329
+ return { output: 'Trade blocked: cannot determine a USD amount for this call to enforce the approved line budget.', isError: true };
330
+ }
331
+ const units = usdUnits(estimate);
332
+ const matched = matching.find(({ trade, line }) => units <= usdUnits(trade.amountUsd) - usdUnits(plan.consumedLineUsd?.[line] ?? 0));
333
+ if (!matched || units > remaining) {
239
334
  return {
240
- output: `Trade blocked: this call needs ~$${spendNeeded.toFixed(2)} but plan ${plan.id} has only ` +
241
- `$${remaining.toFixed(2)} of its approved $${plan.totalSpendUsd.toFixed(2)} budget left. ` +
335
+ output: `Trade blocked: this call needs ~$${estimate.toFixed(2)} but plan ${plan.id} has insufficient per-line or total budget left. ` +
242
336
  'Propose a new plan for the additional spend.',
243
337
  isError: true,
244
338
  };
245
339
  }
340
+ // Reserve BEFORE execution. Debiting only after a clean result let an order
341
+ // that was accepted upstream but answered with an error (lost
342
+ // acknowledgement) leave its line unspent, so a retry placed it twice. The
343
+ // reservation is released only when the tool proves nothing was submitted.
344
+ try {
345
+ if (!adjustPlanConsumption(plan.id, matched.line, units))
346
+ throw new Error('plan vanished');
347
+ }
348
+ catch (err) {
349
+ return {
350
+ output: `Trade blocked: could not reserve budget on plan ${plan.id} (${err instanceof Error ? err.message : String(err)}).`,
351
+ isError: true,
352
+ };
353
+ }
354
+ // Keep authorization out of tool inputs and transcripts, and retain the
355
+ // exact plan even if another approval/cancellation occurs while executing.
356
+ authorizations.set(invocation, { planId: plan.id, line: matched.line, units });
357
+ authorizationsById.set(invocation.id, invocation);
246
358
  // Covered: the plan approval already carried the human decision — skip the
247
359
  // tool's own per-swap AskUser confirm (all swap tools honor auto_approve).
248
360
  if (invocation.name !== 'PolymarketBet') {
@@ -251,25 +363,30 @@ export function checkTradePlanGate(invocation, sessionId = gateSessionId) {
251
363
  return null;
252
364
  }
253
365
  /**
254
- * Draw down the plan budget after a successful gated execution. Called from
366
+ * Settle the reservation made at the gate. Called from
255
367
  * SessionToolGuard.afterExecute for every invocation (no-op for non-trades).
368
+ * The budget stays spent unless the tool reports `notSubmitted`; an error
369
+ * without that signal may be an accepted order whose response was lost.
256
370
  */
257
371
  export function recordTradeExecution(invocation, result, sessionId = gateSessionId) {
258
- if (result.isError || !isGatedInvocation(invocation))
372
+ void sessionId;
373
+ const authorization = authorizations.get(invocation);
374
+ authorizations.delete(invocation);
375
+ authorizationsById.delete(invocation.id);
376
+ if (!authorization)
259
377
  return;
260
- const plan = activeTradePlan(sessionId);
378
+ if (result.notSubmitted) {
379
+ adjustPlanConsumption(authorization.planId, authorization.line, -authorization.units);
380
+ return;
381
+ }
382
+ if (result.isError)
383
+ return;
384
+ const plan = loadTradePlan(authorization.planId);
261
385
  if (!plan)
262
386
  return;
263
- const venue = VENUE_BY_TOOL[invocation.name];
264
- const matched = plan.trades.find(t => t.venue === venue && assetMentioned(t.asset, invocation.input));
265
- const spent = estimateSpendUsd(invocation.name, invocation.input) ?? matched?.amountUsd ?? 0;
266
- const consumedUsd = plan.consumedUsd + spent;
267
- const updated = {
268
- ...plan,
269
- consumedUsd,
270
- status: consumedUsd >= plan.totalSpendUsd - 0.01 ? 'consumed' : plan.status,
271
- };
272
- saveTradePlan(updated);
387
+ const matched = plan.trades[authorization.line];
388
+ const venue = matched.venue;
389
+ const spent = authorization.units / 1e6;
273
390
  // Journal the real-money execution into wallet-keyed document memory —
274
391
  // the trade journal follows the wallet, not the working directory.
275
392
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.4",
3
+ "version": "3.49.6",
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": {
@@ -38,7 +38,7 @@
38
38
  "desktop:package:win": "npm run dist:win --workspace @blockrun/franklin-desktop",
39
39
  "dev": "tsc --watch",
40
40
  "start": "node dist/index.js",
41
- "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs test/arc.local.mjs",
41
+ "test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs test/arc.local.mjs test/subprocess-env.local.mjs test/withdraw.local.mjs test/orders.local.mjs",
42
42
  "test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
43
43
  "e2e:polymarket:readonly": "npm run build && node scripts/polymarket-e2e-readonly.mjs",
44
44
  "test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",