@blockrun/franklin 3.49.5 → 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.
Files changed (39) hide show
  1. package/README.md +8 -8
  2. package/dist/agent/approvals.d.ts +1 -1
  3. package/dist/agent/commands.js +2 -0
  4. package/dist/agent/context.js +15 -2
  5. package/dist/agent/payment-hold.d.ts +116 -0
  6. package/dist/agent/payment-hold.js +821 -0
  7. package/dist/agent/streaming-executor.js +10 -3
  8. package/dist/agent/tool-guard.d.ts +25 -1
  9. package/dist/agent/tool-guard.js +305 -1
  10. package/dist/agent/types.d.ts +7 -0
  11. package/dist/audit/approvals.d.ts +2 -2
  12. package/dist/audit/approvals.js +1 -1
  13. package/dist/hooks/runner.js +8 -2
  14. package/dist/mcp/client.js +4 -1
  15. package/dist/mcp/codegraph.js +2 -0
  16. package/dist/memory/store.js +2 -0
  17. package/dist/tasks/runner.js +2 -1
  18. package/dist/tasks/spawn.js +2 -1
  19. package/dist/tools/bash.js +11 -10
  20. package/dist/tools/grep.js +3 -0
  21. package/dist/tools/jupiter.d.ts +1 -0
  22. package/dist/tools/jupiter.js +1 -1
  23. package/dist/tools/polymarket/creds.d.ts +8 -2
  24. package/dist/tools/polymarket/creds.js +1 -0
  25. package/dist/tools/polymarket/orders.d.ts +7 -0
  26. package/dist/tools/polymarket/orders.js +36 -0
  27. package/dist/tools/polymarket/relayer.js +38 -4
  28. package/dist/tools/polymarket/withdraw.js +122 -10
  29. package/dist/tools/polymarket-bet.js +6 -6
  30. package/dist/tools/subprocess-env.d.ts +2 -0
  31. package/dist/tools/subprocess-env.js +15 -0
  32. package/dist/tools/trade-plan.js +6 -3
  33. package/dist/tools/zerox-base.d.ts +2 -0
  34. package/dist/tools/zerox-base.js +1 -1
  35. package/dist/tools/zerox-gasless.d.ts +2 -0
  36. package/dist/tools/zerox-gasless.js +1 -1
  37. package/dist/trading/trade-plan.d.ts +9 -1
  38. package/dist/trading/trade-plan.js +153 -36
  39. package/package.json +2 -2
@@ -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
- import { checkTradePlanGate, recordTradeExecution } from '../trading/trade-plan.js';
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,10 +704,32 @@ 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) {
721
+ // Denied before execution (permission refused, PreSpend veto): nothing
722
+ // was submitted, so a trade-plan reservation made by the gate goes back.
723
+ try {
724
+ releaseTradeReservation(invocationId);
725
+ }
726
+ catch { /* budget accounting must never break tool flow */ }
426
727
  this.pendingSearches.delete(invocationId);
427
728
  this.pendingReads.delete(invocationId);
428
729
  this.pendingFetches.delete(invocationId);
730
+ this.pendingPaymentSends.delete(invocationId);
731
+ this.pendingReconciles.delete(invocationId);
732
+ this.userAllowedPaymentSends.delete(invocationId);
429
733
  }
430
734
  beforeWebSearch(invocation) {
431
735
  const query = String(invocation.input.query ?? '').trim();
@@ -82,6 +82,13 @@ export interface CapabilityResult {
82
82
  mediaType: string;
83
83
  base64: string;
84
84
  }>;
85
+ /**
86
+ * Set by a money-moving tool only when the call provably never submitted
87
+ * anything (validation failure, user cancel, definite venue rejection). The
88
+ * trade-plan gate reserves budget before execution and releases it only on
89
+ * this signal — an error alone may hide an accepted, unacknowledged order.
90
+ */
91
+ notSubmitted?: boolean;
85
92
  }
86
93
  export interface ExecutionScope {
87
94
  workingDir: string;
@@ -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
  */
@@ -17,6 +17,7 @@ import { logger } from '../logger.js';
17
17
  import { appendApprovalRecord } from '../audit/approvals.js';
18
18
  import { loadHooks } from './loader.js';
19
19
  import { BLOCKING_EVENTS, } from './types.js';
20
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
20
21
  const DEFAULT_TIMEOUT_SECS = 5;
21
22
  const MAX_STDOUT_BYTES = 64 * 1024;
22
23
  export class HookEngine {
@@ -78,13 +79,18 @@ export class HookEngine {
78
79
  if (fs.existsSync(resolved))
79
80
  command = resolved;
80
81
  }
82
+ // Lifecycle hooks are user-authored and keep the full env. Tool and spend
83
+ // hooks receive model-controlled input on stdin and may execute it, so the
84
+ // inherited env drops wallet/account keys; the hook's own configured `env`
85
+ // is an explicit user grant and still applies.
86
+ const inherited = input.toolInput || input.spend ? sanitizeSubprocessEnv() : process.env;
87
+ const env = { ...inherited, ...hook.handler.env };
81
88
  return new Promise(resolve => {
82
89
  const child = execFile('/bin/sh', ['-c', command], {
83
90
  timeout: timeoutMs,
84
91
  maxBuffer: MAX_STDOUT_BYTES,
85
92
  env: {
86
- ...process.env,
87
- ...hook.handler.env,
93
+ ...env,
88
94
  // Reserved vars always win over handler env.
89
95
  FRANKLIN_HOOK_EVENT: input.hookEventName,
90
96
  FRANKLIN_SESSION_ID: input.sessionId,
@@ -21,6 +21,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
21
21
  import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
22
22
  import { logger } from '../logger.js';
23
23
  import { createOAuthProvider } from './oauth.js';
24
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
24
25
  // ─── State ────────────────────────────────────────────────────────────────
25
26
  const connections = new Map();
26
27
  const lastFailures = new Map();
@@ -156,7 +157,9 @@ async function connectStdio(name, config) {
156
157
  const transport = new StdioClientTransport({
157
158
  command: config.command,
158
159
  args: config.args || [],
159
- env: { ...process.env, ...(config.env || {}) },
160
+ // Inherited env drops wallet/account keys; values the user wrote into this
161
+ // server's own `env` config are an explicit grant and pass through.
162
+ env: { ...sanitizeSubprocessEnv(), ...(config.env || {}) },
160
163
  // Capture stderr so we can show it in `/mcp` rather than dumping to the
161
164
  // user's terminal. The previous `'ignore'` mode meant a misconfigured
162
165
  // server (missing env, OAuth failure, missing binary) showed up as a
@@ -20,6 +20,7 @@ import { spawn } from 'node:child_process';
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import { logger } from '../logger.js';
23
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
23
24
  const require = createRequire(import.meta.url);
24
25
  /** True unless the user explicitly disabled CodeGraph via env. */
25
26
  function userEnabled() {
@@ -99,6 +100,7 @@ export function ensureCodegraphIndex(workDir) {
99
100
  try {
100
101
  const child = spawn(process.execPath, [shim, 'init', workDir, '-i'], {
101
102
  cwd: workDir,
103
+ env: sanitizeSubprocessEnv(),
102
104
  // Discard output: this is best-effort background indexing. Failures are
103
105
  // non-fatal — the agent simply keeps using grep/read until (and if) the
104
106
  // index appears. Surfacing a stack trace here would just be noise.
@@ -23,6 +23,7 @@ import path from 'node:path';
23
23
  import crypto from 'node:crypto';
24
24
  import { execFileSync } from 'node:child_process';
25
25
  import { BLOCKRUN_DIR } from '../config.js';
26
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
26
27
  export function memoryEnabled() {
27
28
  return process.env.FRANKLIN_MEMORY !== '0';
28
29
  }
@@ -49,6 +50,7 @@ export function repoIdentity(workDir) {
49
50
  let identity = null;
50
51
  try {
51
52
  const url = execFileSync('git', ['-C', workDir, 'remote', 'get-url', 'origin'], {
53
+ env: sanitizeSubprocessEnv(),
52
54
  encoding: 'utf-8',
53
55
  timeout: 2000,
54
56
  stdio: ['ignore', 'pipe', 'ignore'],
@@ -22,6 +22,7 @@ import { spawn } from 'node:child_process';
22
22
  import fs from 'node:fs';
23
23
  import { readTaskMeta, applyEvent, writeTaskMeta } from './store.js';
24
24
  import { taskLogPath, ensureTaskDir } from './paths.js';
25
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
25
26
  const HEARTBEAT_MS = 5_000;
26
27
  const TAIL_BYTES = 500;
27
28
  function safeCloseFd(fd) {
@@ -129,7 +130,7 @@ export async function runDetachedTask(runId) {
129
130
  const child = spawn('bash', ['-lc', meta.command], {
130
131
  cwd: meta.workingDir,
131
132
  stdio: ['ignore', logFd, logFd],
132
- env: { ...process.env, FRANKLIN_TASK_RUN_ID: runId },
133
+ env: { ...sanitizeSubprocessEnv(), FRANKLIN_TASK_RUN_ID: runId },
133
134
  });
134
135
  // Cancel path: parent CLI sends SIGTERM (or user hits Ctrl-C). We must
135
136
  // (a) flip `finalized` BEFORE the soon-to-fire child.exit handler runs so
@@ -30,6 +30,7 @@ import path from 'node:path';
30
30
  import { randomUUID } from 'node:crypto';
31
31
  import { writeTaskMeta } from './store.js';
32
32
  import { taskLogPath, ensureTaskDir } from './paths.js';
33
+ import { sanitizeSubprocessEnv } from '../tools/subprocess-env.js';
33
34
  // Captured at module load so it survives later chdir / argv mutation.
34
35
  // `process.argv[1]` may be relative (`dist/index.js` in dev mode); we
35
36
  // resolve against process.cwd() at startup which is when the user's
@@ -83,7 +84,7 @@ export function startDetachedTask(input) {
83
84
  cwd: input.workingDir,
84
85
  detached: true,
85
86
  stdio: ['ignore', logFd, logFd],
86
- env: { ...process.env, FRANKLIN_TASK_RUN_ID: runId },
87
+ env: { ...sanitizeSubprocessEnv(), FRANKLIN_TASK_RUN_ID: runId },
87
88
  });
88
89
  child.unref();
89
90
  // The child has duped the fd; closing ours frees the parent's slot.
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { spawn } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
+ import { sanitizeSubprocessEnv } from './subprocess-env.js';
6
7
  // ─── Smart Output Compression ─────────────────────────────────────────────
7
8
  // Learned from RTK (Rust Token Killer): strip noise before sending to LLM.
8
9
  // Applied after capture, before the 32KB cap — reduces tokens on verbose commands.
@@ -289,22 +290,22 @@ function executeCommand(command, timeoutMs, ctx) {
289
290
  const shell = fs.existsSync('/bin/bash') ? '/bin/bash' : (process.env.SHELL || '/bin/sh');
290
291
  let child;
291
292
  try {
292
- // The account bearer key is deliberately withheld from the subprocess.
293
- // bash-guard auto-approves `printenv` and `echo` as safe, so
294
- // `printenv BLOCKRUN_API_KEY` ran with no confirmation and returned the
295
- // key as tool output — into the model prompt and the saved transcript.
296
- // Wallet private keys are never in the environment at all; this gives
297
- // the key the same treatment. Franklin's own gateway calls read
298
- // process.env in-process and are unaffected, and a user who genuinely
299
- // needs the key in a shell can export it there themselves.
293
+ // Credentials are withheld from the subprocess. bash-guard auto-approves
294
+ // `printenv` and `echo` as safe, so `printenv BLOCKRUN_API_KEY` once ran
295
+ // with no confirmation and returned the key as tool output. The same
296
+ // holds for the wallet keys the SDK reads from BLOCKRUN_WALLET_KEY /
297
+ // BASE_CHAIN_WALLET_KEY / SOLANA_WALLET_KEY: inherited, they let a
298
+ // model-written script sign transfers that no Franklin gate ever sees.
299
+ // Franklin's own gateway calls read process.env in-process and are
300
+ // unaffected, and a user who genuinely needs a key in a shell can
301
+ // export it there themselves.
300
302
  const childEnv = {
301
- ...process.env,
303
+ ...sanitizeSubprocessEnv(),
302
304
  FRANKLIN: '1', // Let scripts detect they're running inside Franklin
303
305
  FRANKLIN_WORKDIR: ctx.workingDir,
304
306
  RUNCODE: '1', // Backwards compat
305
307
  RUNCODE_WORKDIR: ctx.workingDir,
306
308
  };
307
- delete childEnv.BLOCKRUN_API_KEY;
308
309
  child = spawn(shell, ['-c', command], {
309
310
  cwd: ctx.workingDir,
310
311
  env: childEnv,