@blockrun/franklin 3.49.6 → 3.49.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.
@@ -266,7 +266,8 @@ export class StreamingExecutor {
266
266
  }
267
267
  const execStart = Date.now();
268
268
  let result = await handler.execute(invocation.input, progressScope);
269
- this.guard?.afterExecute(invocation, result);
269
+ if (this.guard)
270
+ result = this.guard.afterExecute(invocation, result);
270
271
  // Notify-only hooks — never block, never delay the result.
271
272
  if (this.hooks?.hasHooks('PostToolUse')) {
272
273
  void this.hooks.dispatch('PostToolUse', this.hookInput(invocation, 'PostToolUse')).catch(() => { });
@@ -319,8 +320,14 @@ export class StreamingExecutor {
319
320
  return result;
320
321
  }
321
322
  catch (err) {
322
- this.guard?.cancelInvocation(invocation.id);
323
323
  const errMsg = err.message;
324
+ // A payment send that threw mid-run may already have broadcast: the
325
+ // guard records it as an unknown outcome before the cancel below.
326
+ const thrown = this.guard?.executionThrew(invocation, {
327
+ output: `Error executing ${invocation.name}: ${errMsg}`,
328
+ isError: true,
329
+ });
330
+ this.guard?.cancelInvocation(invocation.id);
324
331
  recordFailure({
325
332
  timestamp: Date.now(),
326
333
  model: '', // not available at tool level
@@ -334,7 +341,7 @@ export class StreamingExecutor {
334
341
  // them alongside everything else.
335
342
  const preview = this.inputPreview(invocation) || '';
336
343
  logger.warn(`[franklin] Tool error: ${invocation.name} threw "${errMsg.slice(0, 120)}"${preview ? ` — ${preview.slice(0, 80)}` : ''}`);
337
- return {
344
+ return thrown ?? {
338
345
  output: `Error executing ${invocation.name}: ${errMsg}`,
339
346
  isError: true,
340
347
  };
@@ -1,4 +1,5 @@
1
1
  import type { CapabilityInvocation, CapabilityResult, ExecutionScope } from './types.js';
2
+ import { type PaymentAttempt } from './payment-hold.js';
2
3
  export declare const BLOCKING_POLL_LOOP_RE: RegExp;
3
4
  export declare function normalizeSearchQuery(query: string): {
4
5
  normalized: string;
@@ -25,16 +26,39 @@ export declare class SessionToolGuard {
25
26
  private recentGreps;
26
27
  private recentGlobs;
27
28
  private recentBash;
29
+ private paymentAttempts;
30
+ private nextPaymentAttemptId;
31
+ private pendingPaymentSends;
32
+ private pendingReconciles;
33
+ private userAllowedPaymentSends;
28
34
  constructor(sessionId?: string);
35
+ private persistPaymentAttempts;
29
36
  startTurn(): void;
30
37
  beforeExecute(invocation: CapabilityInvocation, scope: ExecutionScope): Promise<CapabilityResult | null>;
31
38
  private beforeBash;
32
39
  private beforeGrep;
33
40
  private beforeGlob;
34
- afterExecute(invocation: CapabilityInvocation, result: CapabilityResult): void;
41
+ /**
42
+ * Post-execution bookkeeping. Returns the result the model should see —
43
+ * the same object unless a payment attempt ended ambiguously, in which case
44
+ * an OUTCOME UNKNOWN notice is appended before the model decides anything.
45
+ */
46
+ afterExecute(invocation: CapabilityInvocation, result: CapabilityResult): CapabilityResult;
47
+ /** Payment attempts this session whose outcome is still unknown. */
48
+ unresolvedPaymentAttempts(): PaymentAttempt[];
49
+ private checkPaymentHold;
50
+ private askToOverrideHold;
51
+ private afterPayment;
35
52
  private afterBash;
36
53
  private afterGrep;
37
54
  private afterGlob;
55
+ /**
56
+ * The tool threw instead of returning. A payment send that was already
57
+ * running may have broadcast before the throw, so it is recorded as an
58
+ * unknown outcome rather than silently forgotten. Returns the error result
59
+ * the model should see.
60
+ */
61
+ executionThrew(invocation: CapabilityInvocation, result: CapabilityResult): CapabilityResult;
38
62
  cancelInvocation(invocationId: string): void;
39
63
  private beforeWebSearch;
40
64
  private beforeRead;
@@ -1,6 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { checkTradePlanGate, recordTradeExecution, releaseTradeReservation } from '../trading/trade-plan.js';
4
+ import { appendApprovalRecord } from '../audit/approvals.js';
5
+ import { getAddress } from '../wallet/manager.js';
6
+ import { activeSolanaAddress } from '../wallet/solana-migration.js';
7
+ import { ambiguousOutcomeReason, analyzeBash, attemptsOverlap, commandPreview, describeAttempt, extractRecipients, extractTxHashes, isPaymentSend, isReconciliation, loadPaymentAttempts, savePaymentAttempts, codeRecordsNegativeOutcome, recordsNegativeOutcome, unknownOutcomeNotice, } from './payment-hold.js';
4
8
  const MAX_WEBSEARCHES_PER_TURN = 8;
5
9
  const MAX_SIMILAR_SEARCHES_PER_TURN = 4;
6
10
  const MAX_NO_SIGNAL_SEARCHES_PER_FAMILY = 2;
@@ -165,6 +169,89 @@ export function isToolClassFailure(name, result) {
165
169
  }
166
170
  return true;
167
171
  }
172
+ // Tools whose input can never record a payment outcome — reads, searches,
173
+ // and questions to the user (asking is exactly what an unknown outcome needs).
174
+ const OUTCOME_NEUTRAL_TOOLS = new Set([
175
+ 'Read', 'Grep', 'Glob', 'WebSearch', 'SearchX', 'WebFetch', 'AskUser', 'ActivateTool',
176
+ ]);
177
+ /**
178
+ * Every string in a tool input, checked raw as well as serialized: JSON
179
+ * escaping turns `{"status":"failed"}` inside a Write's content into
180
+ * `{\"status\":\"failed\"}`, which a pattern on the serialized form misses.
181
+ */
182
+ function inputRecordsNegativeOutcome(name, input) {
183
+ // Editing tools: only the text they introduce is a record. Removing an
184
+ // "unpaid" (Edit's old_string) is a correction, not a claim.
185
+ if (name === 'Edit')
186
+ return recordsNegativeOutcome(String(input.new_string ?? ''));
187
+ if (name === 'Write')
188
+ return recordsNegativeOutcome(String(input.content ?? ''));
189
+ const strings = [];
190
+ const walk = (v, depth) => {
191
+ if (depth > 6)
192
+ return;
193
+ if (typeof v === 'string')
194
+ strings.push(v);
195
+ else if (Array.isArray(v))
196
+ v.forEach(x => walk(x, depth + 1));
197
+ else if (v && typeof v === 'object')
198
+ Object.values(v).forEach(x => walk(x, depth + 1));
199
+ };
200
+ walk(input, 0);
201
+ return recordsNegativeOutcome(JSON.stringify(input ?? {})) || strings.some(recordsNegativeOutcome);
202
+ }
203
+ /**
204
+ * Whether a read-only lookup is about this attempt: it names one of the
205
+ * attempt's tx hashes, recipients or paying wallets (a sender nonce or
206
+ * balance check). An attempt with none of those cannot be told apart from
207
+ * any other, so any lookup counts for it.
208
+ */
209
+ function lookupAddressesAttempt(lookup, attempt) {
210
+ const keys = [...attempt.txHashes, ...attempt.recipients, ...attempt.senders].map(k => k.toLowerCase());
211
+ if (keys.length === 0)
212
+ return true;
213
+ const text = lookup.toLowerCase();
214
+ return keys.some(k => text.includes(k));
215
+ }
216
+ function negativeOutcomeBlock(unresolved) {
217
+ const pending = unresolved.filter(a => !a.reconciled);
218
+ return {
219
+ output: 'Blocked by Franklin\'s payment guard: this call records a payment as failed/unpaid, but the outcome of ' +
220
+ `${pending.length === 1 ? 'this attempt is' : 'these attempts are'} UNKNOWN and nothing has been checked yet:\n` +
221
+ pending.map(a => `- ${describeAttempt(a)}`).join('\n') +
222
+ '\n\nA timeout or 5xx after a send is not a failure — the payment may have settled. Either run a READ-ONLY ' +
223
+ 'reconciliation first (receipt for the tx hash, the sender\'s nonce, sender/recipient balances, or the ' +
224
+ 'venue\'s status endpoint), or record the outcome as UNKNOWN and tell the user exactly what is unknown.',
225
+ isError: true,
226
+ };
227
+ }
228
+ function ownWalletAddresses() {
229
+ const out = [];
230
+ try {
231
+ out.push(getAddress());
232
+ }
233
+ catch { /* no EVM wallet */ }
234
+ try {
235
+ const sol = activeSolanaAddress();
236
+ if (sol)
237
+ out.push(sol);
238
+ }
239
+ catch { /* no Solana wallet */ }
240
+ return out;
241
+ }
242
+ function paymentHoldResult(blocking) {
243
+ return {
244
+ output: 'Payment held by Franklin\'s payment guard — NOT sent. An earlier payment attempt to the same recipient ' +
245
+ 'has an UNKNOWN outcome and may already have settled:\n' +
246
+ blocking.map(a => `- ${describeAttempt(a)}`).join('\n') +
247
+ '\n\nSending again — with a rewritten script, a new nonce or a new signature — could pay the same obligation ' +
248
+ 'twice, so the user did not approve this send (or no one was available to approve it). Do not try another ' +
249
+ 'way to send it. Reconcile with READ-ONLY checks (receipt for the tx hash, sender nonce, sender/recipient ' +
250
+ 'balances, or the venue\'s status endpoint), then report every attempt to the user and say exactly what ' +
251
+ 'is still unknown. Record the outcome as UNKNOWN unless a check established it.',
252
+ isError: true,
253
+ };
254
+ }
168
255
  export class SessionToolGuard {
169
256
  /**
170
257
  * Session identity for the trade-plan gate. Explicit (not module-global)
@@ -187,8 +274,27 @@ export class SessionToolGuard {
187
274
  recentGreps = new Map();
188
275
  recentGlobs = new Map();
189
276
  recentBash = new Map();
277
+ // Payment hold (see payment-hold.ts): sends whose outcome is unknown, the
278
+ // sends and reconciliation lookups currently executing, and sends the user
279
+ // explicitly allowed past a hold (those skip the exact-command dedup too).
280
+ paymentAttempts = [];
281
+ nextPaymentAttemptId = 1;
282
+ pendingPaymentSends = new Map();
283
+ // Read-only lookups in flight: the code they run, so only the attempts it
284
+ // names (tx hash or recipient) count as checked.
285
+ pendingReconciles = new Map();
286
+ userAllowedPaymentSends = new Set();
190
287
  constructor(sessionId) {
191
288
  this.sessionId = sessionId;
289
+ if (sessionId) {
290
+ // A resumed session keeps its unknown payment outcomes and their holds.
291
+ this.paymentAttempts = loadPaymentAttempts(sessionId);
292
+ this.nextPaymentAttemptId = this.paymentAttempts.reduce((m, a) => Math.max(m, a.id), 0) + 1;
293
+ }
294
+ }
295
+ persistPaymentAttempts() {
296
+ if (this.sessionId)
297
+ savePaymentAttempts(this.sessionId, this.paymentAttempts);
192
298
  }
193
299
  startTurn() {
194
300
  this.turn++;
@@ -233,6 +339,11 @@ export class SessionToolGuard {
233
339
  const tradeGate = checkTradePlanGate(invocation, this.sessionId);
234
340
  if (tradeGate)
235
341
  return tradeGate;
342
+ // Payment hold: a send whose outcome is unknown blocks any new send that
343
+ // could pay the same recipient, whatever the script text looks like.
344
+ const paymentGate = await this.checkPaymentHold(invocation, scope);
345
+ if (paymentGate)
346
+ return paymentGate;
236
347
  switch (invocation.name) {
237
348
  case 'WebSearch':
238
349
  case 'SearchX':
@@ -308,6 +419,10 @@ export class SessionToolGuard {
308
419
  // Only dedup deterministic read-only commands. Skip anything writing/network/long-running.
309
420
  if (WRITE_KEYWORDS.test(cmd))
310
421
  return null;
422
+ // The user explicitly allowed this send past a payment hold — honor that
423
+ // even when it repeats a command that failed earlier.
424
+ if (this.userAllowedPaymentSends.delete(invocation.id))
425
+ return null;
311
426
  // Normalize whitespace so "ls -la" and "ls -la" share a cache entry.
312
427
  const key = cmd.replace(/\s+/g, ' ');
313
428
  const cached = this.recentBash.get(key);
@@ -348,6 +463,11 @@ export class SessionToolGuard {
348
463
  }
349
464
  return null;
350
465
  }
466
+ /**
467
+ * Post-execution bookkeeping. Returns the result the model should see —
468
+ * the same object unless a payment attempt ended ambiguously, in which case
469
+ * an OUTCOME UNKNOWN notice is appended before the model decides anything.
470
+ */
351
471
  afterExecute(invocation, result) {
352
472
  // Draw down the approved trade plan's budget on successful executions
353
473
  // (no-op for non-trade tools).
@@ -355,6 +475,7 @@ export class SessionToolGuard {
355
475
  recordTradeExecution(invocation, result, this.sessionId);
356
476
  }
357
477
  catch { /* budget accounting must never break tool results */ }
478
+ result = this.afterPayment(invocation, result);
358
479
  // Per-tool circuit breaker: count consecutive tool-class failures, reset on
359
480
  // any success. Agent-input errors (e.g. WebFetch 404 on a guessed URL) are
360
481
  // not tool failures and must not trip the breaker.
@@ -387,6 +508,167 @@ export class SessionToolGuard {
387
508
  default:
388
509
  break;
389
510
  }
511
+ return result;
512
+ }
513
+ /** Payment attempts this session whose outcome is still unknown. */
514
+ unresolvedPaymentAttempts() {
515
+ return this.paymentAttempts.filter(a => !a.overriddenByUser);
516
+ }
517
+ async checkPaymentHold(invocation, scope) {
518
+ const unresolved = this.unresolvedPaymentAttempts();
519
+ if (invocation.name === 'Bash') {
520
+ const cmd = String(invocation.input.command ?? '').trim();
521
+ if (!cmd)
522
+ return null;
523
+ const { code, data, detached } = analyzeBash(cmd, scope.workingDir);
524
+ const hasUncheckedAttempt = unresolved.some(a => !a.reconciled);
525
+ // Recording failed/unpaid from the shell — checked before anything
526
+ // else, so batching it with a send or a lookup changes nothing: text it
527
+ // writes to a file or passes to a CLI (`echo '{"status":"unpaid"}' >
528
+ // ledger.json`, `ledger add --status unpaid`), or code it runs that
529
+ // persists a negative outcome (`node record.mjs`). A send's own code may
530
+ // log "failed" for its own errors, so for sends only the shell-level
531
+ // writes count. A lookup that merely PRINTS "unpaid" writes nothing.
532
+ if (hasUncheckedAttempt &&
533
+ (recordsNegativeOutcome(data) || (!isPaymentSend(code) && codeRecordsNegativeOutcome(code)))) {
534
+ return negativeOutcomeBlock(unresolved);
535
+ }
536
+ if (isPaymentSend(code)) {
537
+ const own = ownWalletAddresses();
538
+ const recipients = extractRecipients(code, own);
539
+ // The wallet named in the script, or — when it loads its key some
540
+ // other way — every wallet Franklin holds.
541
+ const named = own.filter(a => code.toLowerCase().includes(a.toLowerCase()));
542
+ const senders = (named.length ? named : own).map(a => a.toLowerCase());
543
+ const blocking = unresolved.filter(a => attemptsOverlap(a.recipients, recipients));
544
+ if (blocking.length > 0) {
545
+ const allowed = await this.askToOverrideHold(blocking, cmd, scope);
546
+ if (!allowed)
547
+ return paymentHoldResult(blocking);
548
+ for (const a of blocking)
549
+ a.overriddenByUser = true;
550
+ this.persistPaymentAttempts();
551
+ this.userAllowedPaymentSends.add(invocation.id);
552
+ }
553
+ this.pendingPaymentSends.set(invocation.id, {
554
+ command: commandPreview(cmd),
555
+ recipients,
556
+ senders,
557
+ // `node pay.mjs &` or `nohup …` returns before the payment does,
558
+ // exactly like the tool's own run_in_background.
559
+ background: Boolean(invocation.input.run_in_background) || detached,
560
+ });
561
+ return null;
562
+ }
563
+ // Classified on executed code only: printing a lookup into a file is
564
+ // not a lookup.
565
+ if (isReconciliation(code)) {
566
+ // A background lookup returns before it has looked anything up, so
567
+ // it can never count as a check.
568
+ if (unresolved.length > 0 && !invocation.input.run_in_background && !detached) {
569
+ this.pendingReconciles.set(invocation.id, code);
570
+ }
571
+ }
572
+ // Bash was judged above on what it writes and runs, not on its raw text.
573
+ return null;
574
+ }
575
+ // Recording an unknown outcome as failed/unpaid before anything was
576
+ // checked. Read-only tools and questions to the user are never outcome
577
+ // records, so they pass.
578
+ if (unresolved.some(a => !a.reconciled) &&
579
+ !OUTCOME_NEUTRAL_TOOLS.has(invocation.name) &&
580
+ inputRecordsNegativeOutcome(invocation.name, invocation.input)) {
581
+ return negativeOutcomeBlock(unresolved);
582
+ }
583
+ return null;
584
+ }
585
+ async askToOverrideHold(blocking, command, scope) {
586
+ const sessionId = scope.sessionId ?? this.sessionId ?? '';
587
+ const subject = `payment attempt${blocking.length > 1 ? 's' : ''} ${blocking.map(a => `#${a.id}`).join(', ')}`;
588
+ if (!scope.onApproval) {
589
+ appendApprovalRecord({ ts: Date.now(), sessionId, kind: 'payment-hold', subject, decision: 'deny', by: 'policy', reason: 'no approval surface' });
590
+ return false;
591
+ }
592
+ let choice = 'deny';
593
+ let by = 'user';
594
+ try {
595
+ const decision = await scope.onApproval({
596
+ sessionId,
597
+ kind: 'payment-hold',
598
+ title: 'New payment while an earlier one is unresolved',
599
+ description: 'An earlier payment attempt in this session ended without a clear result, so it may already have ' +
600
+ 'settled. Sending again could pay the same obligation twice.\n\n' +
601
+ blocking.map(a => `Earlier: ${describeAttempt(a)}`).join('\n') +
602
+ `\n\nNew send: ${commandPreview(command)}\n\n` +
603
+ 'Approve ONLY if you have confirmed the earlier attempt did not settle (e.g. a reverted receipt, or ' +
604
+ 'the recipient balance and sender nonce are unchanged). Deny keeps the hold.',
605
+ options: ['approve', 'deny'],
606
+ payload: { attempts: blocking, command },
607
+ });
608
+ choice = decision.choice.toLowerCase();
609
+ if (decision.message === 'auto')
610
+ by = 'flag';
611
+ }
612
+ catch {
613
+ choice = 'deny';
614
+ by = 'policy';
615
+ }
616
+ const approved = choice === 'approve';
617
+ appendApprovalRecord({
618
+ ts: Date.now(),
619
+ sessionId,
620
+ kind: 'payment-hold',
621
+ subject,
622
+ decision: approved ? 'approve' : 'deny',
623
+ by,
624
+ });
625
+ return approved;
626
+ }
627
+ afterPayment(invocation, result, forcedReason) {
628
+ const output = String(result.output ?? '');
629
+ const lookup = this.pendingReconciles.get(invocation.id);
630
+ if (lookup !== undefined) {
631
+ this.pendingReconciles.delete(invocation.id);
632
+ // A lookup that itself failed or timed out established nothing.
633
+ if (!result.isError && !ambiguousOutcomeReason(output, result.isError, false)) {
634
+ for (const a of this.unresolvedPaymentAttempts()) {
635
+ if (lookupAddressesAttempt(lookup, a))
636
+ a.reconciled = true;
637
+ }
638
+ this.persistPaymentAttempts();
639
+ }
640
+ }
641
+ const pending = this.pendingPaymentSends.get(invocation.id);
642
+ if (!pending)
643
+ return result;
644
+ this.pendingPaymentSends.delete(invocation.id);
645
+ const reason = forcedReason ?? ambiguousOutcomeReason(output, result.isError, pending.background);
646
+ if (!reason)
647
+ return result;
648
+ const attempt = {
649
+ id: this.nextPaymentAttemptId++,
650
+ turn: this.turn,
651
+ at: Date.now(),
652
+ command: pending.command,
653
+ recipients: pending.recipients,
654
+ senders: pending.senders,
655
+ reason,
656
+ txHashes: extractTxHashes(output),
657
+ reconciled: false,
658
+ overriddenByUser: false,
659
+ };
660
+ this.paymentAttempts.push(attempt);
661
+ this.persistPaymentAttempts();
662
+ appendApprovalRecord({
663
+ ts: attempt.at,
664
+ sessionId: this.sessionId ?? '',
665
+ kind: 'payment-hold',
666
+ subject: `payment attempt #${attempt.id}`,
667
+ decision: 'deny',
668
+ by: 'policy',
669
+ reason: `outcome unknown: ${reason}`,
670
+ });
671
+ return { ...result, output: output + unknownOutcomeNotice(attempt) };
390
672
  }
391
673
  afterBash(invocation, result) {
392
674
  const cmd = String(invocation.input.command ?? '').trim();
@@ -422,6 +704,19 @@ export class SessionToolGuard {
422
704
  : output;
423
705
  this.recentGlobs.set(key, { preview, turn: this.turn });
424
706
  }
707
+ /**
708
+ * The tool threw instead of returning. A payment send that was already
709
+ * running may have broadcast before the throw, so it is recorded as an
710
+ * unknown outcome rather than silently forgotten. Returns the error result
711
+ * the model should see.
712
+ */
713
+ executionThrew(invocation, result) {
714
+ const pending = this.pendingPaymentSends.get(invocation.id);
715
+ if (!pending)
716
+ return result;
717
+ // A thrown send never produced a conclusive answer.
718
+ return this.afterPayment(invocation, result, 'the tool threw before it could report a result');
719
+ }
425
720
  cancelInvocation(invocationId) {
426
721
  // Denied before execution (permission refused, PreSpend veto): nothing
427
722
  // was submitted, so a trade-plan reservation made by the gate goes back.
@@ -432,6 +727,9 @@ export class SessionToolGuard {
432
727
  this.pendingSearches.delete(invocationId);
433
728
  this.pendingReads.delete(invocationId);
434
729
  this.pendingFetches.delete(invocationId);
730
+ this.pendingPaymentSends.delete(invocationId);
731
+ this.pendingReconciles.delete(invocationId);
732
+ this.userAllowedPaymentSends.delete(invocationId);
435
733
  }
436
734
  beforeWebSearch(invocation) {
437
735
  const query = String(invocation.input.query ?? '').trim();
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Unified approval/decision audit log — one book for every gate decision:
3
- * hook denies, permission prompts, and trade-plan verdicts. Append-only
3
+ * hook denies, permission prompts, trade-plan verdicts, and payment holds. Append-only
4
4
  * JSONL at ~/.blockrun/approvals.jsonl so `franklin panel` and post-hoc
5
5
  * forensics read a single stream instead of three.
6
6
  */
@@ -8,7 +8,7 @@ export interface ApprovalRecord {
8
8
  ts: number;
9
9
  sessionId: string;
10
10
  /** What kind of gate produced this record. */
11
- kind: 'hook' | 'permission' | 'trade-plan';
11
+ kind: 'hook' | 'permission' | 'trade-plan' | 'payment-hold';
12
12
  /** What was being decided — tool name, plan id, hook source. */
13
13
  subject: string;
14
14
  decision: 'allow' | 'deny' | 'approve' | 'reject' | 'expire' | 'cancel';
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Unified approval/decision audit log — one book for every gate decision:
3
- * hook denies, permission prompts, and trade-plan verdicts. Append-only
3
+ * hook denies, permission prompts, trade-plan verdicts, and payment holds. Append-only
4
4
  * JSONL at ~/.blockrun/approvals.jsonl so `franklin panel` and post-hoc
5
5
  * forensics read a single stream instead of three.
6
6
  */
@@ -314,8 +314,14 @@ export async function withdrawFunds(input) {
314
314
  const account = getPolymarketAccount();
315
315
  const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_WRITE_RPC_URL) });
316
316
  // franklin-local: hash the locally signed bytes and persist before any broadcast.
317
- const nonce = await getPublicClient().getTransactionCount({ address: account.address, blockTag: "pending" });
318
- const request = await wallet.prepareTransactionRequest({ to: PUSD_COLLATERAL, data, chain: polygon, account, nonce });
317
+ // franklin-local: the nonce comes from the WRITE endpoint
318
+ // (prepareTransactionRequest asks the wallet's own transport), not the
319
+ // fallback public readers, which are separate providers with their own
320
+ // pending pools. A load-balanced write URL can still answer from a
321
+ // different backend than the broadcast; safety does not rest on this —
322
+ // the bytes are persisted first and a retry re-sends only those.
323
+ const request = await wallet.prepareTransactionRequest({ to: PUSD_COLLATERAL, data, chain: polygon, account });
324
+ const nonce = request.nonce;
319
325
  const serializedTransaction = await wallet.signTransaction(request);
320
326
  txHash = keccak256(serializedTransaction);
321
327
  saveState({ pendingWithdraw: { txHash, nonce, from: account.address, serializedTransaction } });
@@ -117,8 +117,11 @@ export function createTradePlanCapability() {
117
117
  decideTradePlan(plan, 'approved', decision.message === 'auto' ? 'flag' : 'user');
118
118
  return {
119
119
  output: `Trade plan ${plan.id} APPROVED — $${plan.totalSpendUsd.toFixed(2)} authorized until ` +
120
- `${new Date(plan.expiresAt).toLocaleTimeString()}. Execute ONLY the planned trades; each ` +
121
- 'execution draws down the budget. Per-swap confirmation is skipped — the plan approval was the confirmation.',
120
+ `${new Date(plan.expiresAt).toLocaleTimeString()}. Approval executes NOTHING: no trade has been ` +
121
+ 'placed and no money has moved yet. Execute ONLY the planned trades, each with its own tool call; each ' +
122
+ 'execution draws down the budget, and only a successful execution result means money moved. Never ' +
123
+ 'report or record a trade or payment as done on the strength of this approval. Per-swap confirmation ' +
124
+ 'is skipped because this approval already covers it.',
122
125
  };
123
126
  }
124
127
  if (choice === 'request changes') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.6",
3
+ "version": "3.49.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": {
@@ -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 test/subprocess-env.local.mjs test/withdraw.local.mjs test/orders.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 test/payment-hold.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",