@blockrun/franklin 3.49.7 → 3.49.9

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.
@@ -42,6 +42,10 @@ interface SimpleCommand {
42
42
  writesFile: boolean;
43
43
  /** The files those output redirects write. */
44
44
  outFiles: string[];
45
+ /** Command substitutions inside double quotes (`"$(node pay.mjs)"`): they run. */
46
+ substitutions: string[];
47
+ /** A quote opened or closed in the middle of one of its words. */
48
+ collided: boolean;
45
49
  }
46
50
  /**
47
51
  * Split shell text into simple commands, honoring single/double quotes and
@@ -54,6 +58,14 @@ export declare function splitShellCommands(text: string): SimpleCommand[];
54
58
  export interface BashExecution {
55
59
  /** Only code that executes. Payment-send and reconciliation detection. */
56
60
  code: string;
61
+ /**
62
+ * Shell text whose quoting or structure did not resolve cleanly (see
63
+ * scanShell). It may run, so it counts toward a send and toward a
64
+ * persisted unpaid record, failing closed as an attempt with no
65
+ * identifiable recipient matches any send. When it is non-empty the parse
66
+ * is unreliable, so the run never counts as a lookup: that would fail open.
67
+ */
68
+ opaque: string;
57
69
  /** What it writes or prints rather than runs. Outcome-record detection. */
58
70
  data: string;
59
71
  /** Part of it keeps running after the Bash call returns. */
@@ -70,6 +82,7 @@ export interface BashExecution {
70
82
  * must not count as running it.
71
83
  */
72
84
  export declare function analyzeBash(command: string, workingDir: string): BashExecution;
85
+ /** Everything a Bash run may execute: its code, plus text whose quoting did not resolve. */
73
86
  export declare function bashExecutedText(command: string, workingDir: string): string;
74
87
  export declare function isPaymentSend(text: string): boolean;
75
88
  export declare function isReconciliation(text: string): boolean;
@@ -103,7 +116,11 @@ export interface PaymentAttempt {
103
116
  txHashes: string[];
104
117
  /** Set once a read-only receipt/nonce/balance lookup ran after it. */
105
118
  reconciled: boolean;
106
- /** Set when the user explicitly allowed a new payment despite it. */
119
+ /**
120
+ * Set once a send the user explicitly approved past this attempt has run.
121
+ * It lifts the hold only: the outcome is still unknown, so recording it as
122
+ * failed/unpaid still needs a lookup, and a lookup can still check it.
123
+ */
107
124
  overriddenByUser: boolean;
108
125
  }
109
126
  export declare function attemptsOverlap(a: string[], b: string[]): boolean;
@@ -183,6 +183,45 @@ function isInterpreter(word) {
183
183
  function expandHome(p) {
184
184
  return p.replace(/^~(?=\/|$)/, process.env.HOME ?? '~');
185
185
  }
186
+ /**
187
+ * Index of the `)` closing a `$(` whose body starts at `start`, honoring
188
+ * quotes, escapes and nesting; -1 when it never closes.
189
+ */
190
+ function substitutionEnd(text, start) {
191
+ let depth = 1;
192
+ for (let i = start; i < text.length; i++) {
193
+ const c = text[i];
194
+ if (c === '\\')
195
+ i++;
196
+ else if (c === "'") {
197
+ const close = text.indexOf("'", i + 1);
198
+ if (close === -1)
199
+ return -1;
200
+ i = close;
201
+ }
202
+ else if (c === '"') {
203
+ i++;
204
+ while (i < text.length && text[i] !== '"') {
205
+ if (text[i] === '\\')
206
+ i++;
207
+ else if (text[i] === '$' && text[i + 1] === '(') {
208
+ const end = substitutionEnd(text, i + 2);
209
+ if (end === -1)
210
+ return -1;
211
+ i = end;
212
+ }
213
+ i++;
214
+ }
215
+ if (i >= text.length)
216
+ return -1;
217
+ }
218
+ else if (c === '(')
219
+ depth++;
220
+ else if (c === ')' && --depth === 0)
221
+ return i;
222
+ }
223
+ return -1;
224
+ }
186
225
  /**
187
226
  * Split shell text into simple commands, honoring single/double quotes and
188
227
  * backslash escapes. Separators: newline ; & && | || ( ) $( ` . Output
@@ -191,8 +230,62 @@ function expandHome(p) {
191
230
  * stdin runs whatever arrives there.
192
231
  */
193
232
  export function splitShellCommands(text) {
233
+ return scanShell(text).commands;
234
+ }
235
+ /** `$'…'` escapes that stand for one character. */
236
+ const ANSI_C_ESCAPES = {
237
+ n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v',
238
+ '\\': '\\', "'": "'", '"': '"', '?': '?',
239
+ };
240
+ /**
241
+ * Decode the `$'…'` escape whose letter is at `at`: the character(s) it
242
+ * stands for and how many characters after the backslash it used. Hex,
243
+ * octal and Unicode escapes are decoded too, so `$'write\x43ontract'` reads
244
+ * as the `writeContract` bash hands the program.
245
+ */
246
+ function ansiCEscape(text, at) {
247
+ const esc = text[at];
248
+ const fromCode = (digits, radix) => {
249
+ const code = parseInt(digits, radix);
250
+ return Number.isFinite(code) && code <= 0x10ffff ? String.fromCodePoint(code) : '';
251
+ };
252
+ const run = (re) => re.exec(text.slice(at + 1))?.[0] ?? '';
253
+ if (esc === 'x') {
254
+ const hex = run(/^[0-9A-Fa-f]{1,2}/);
255
+ return hex ? [fromCode(hex, 16), 1 + hex.length] : ['\\x', 1];
256
+ }
257
+ if (esc === 'u' || esc === 'U') {
258
+ const hex = run(esc === 'u' ? /^[0-9A-Fa-f]{1,4}/ : /^[0-9A-Fa-f]{1,8}/);
259
+ return hex ? [fromCode(hex, 16), 1 + hex.length] : [`\\${esc}`, 1];
260
+ }
261
+ if (/[0-7]/.test(esc)) {
262
+ const oct = /^[0-7]{1,3}/.exec(text.slice(at))[0];
263
+ return [fromCode(oct, 8), oct.length];
264
+ }
265
+ if (esc === 'c' && at + 1 < text.length) {
266
+ return [String.fromCharCode(text.charCodeAt(at + 1) & 0x1f), 2];
267
+ }
268
+ return [ANSI_C_ESCAPES[esc] ?? `\\${esc}`, 1];
269
+ }
270
+ /**
271
+ * Split shell text, and say whether a quote never closed. Each command also
272
+ * records whether a quote opened or closed in the middle of one of its words
273
+ * (`wallet's`, `console.log("hi")` inside `node -e "…"`): legal shell, but in
274
+ * a program's inline code it almost always means an apostrophe or quote
275
+ * collided with the quotes around it, and the split is no longer a reliable
276
+ * account of what runs. (EmberTail, 3.49.7 live-3/S40: `// Get the wallet's
277
+ * USDC balance` inside `node -e '…'` hid the writeContract that followed.)
278
+ */
279
+ function scanShell(text) {
194
280
  const commands = [];
195
- const fresh = (pipedFrom = null) => ({ words: [], stdinFiles: [], hereStrings: [], pipedFrom, background: false, writesFile: false, outFiles: [] });
281
+ // A quote never closed, or a construct this splitter cannot place.
282
+ let unreliable = false;
283
+ const isWordChar = (ch) => ch !== undefined && /[A-Za-z0-9_]/.test(ch);
284
+ // A quote opening right after a letter or digit of the same word.
285
+ const opensMidWord = (i) => isWordChar(text[i - 1]);
286
+ // A quote closing right before a letter or digit of the same word.
287
+ const closesMidWord = (close) => isWordChar(text[close + 1]);
288
+ const fresh = (pipedFrom = null) => ({ words: [], stdinFiles: [], hereStrings: [], pipedFrom, background: false, writesFile: false, outFiles: [], substitutions: [], collided: false });
196
289
  let current = fresh();
197
290
  let word = '';
198
291
  let inWord = false;
@@ -216,7 +309,7 @@ export function splitShellCommands(text) {
216
309
  endWord();
217
310
  target = 'word';
218
311
  current.background = Boolean(opts.background);
219
- const done = current.words.length || current.stdinFiles.length || current.hereStrings.length ? current : null;
312
+ const done = current.words.length || current.stdinFiles.length || current.hereStrings.length || current.substitutions.length ? current : null;
220
313
  if (done)
221
314
  commands.push(done);
222
315
  current = fresh(opts.pipe ? done : null);
@@ -224,26 +317,102 @@ export function splitShellCommands(text) {
224
317
  for (let i = 0; i < text.length; i++) {
225
318
  const c = text[i];
226
319
  if (c === '\\' && i + 1 < text.length) {
227
- if (text[i + 1] !== '\n')
320
+ // A line continuation is removed, not part of a word: a `#` after it
321
+ // still starts a comment.
322
+ if (text[i + 1] !== '\n') {
228
323
  word += text[i + 1];
229
- inWord = true;
324
+ inWord = true;
325
+ }
230
326
  i++;
231
327
  }
328
+ else if (c === '#' && !inWord && (text[i - 1] === ')' || text[i - 1] === '`')) {
329
+ // `$(x)#…` is one word in bash, `(x)#…` a comment. Telling them apart
330
+ // needs the nesting this splitter does not keep, so the run is opaque.
331
+ unreliable = true;
332
+ word += c;
333
+ inWord = true;
334
+ }
335
+ else if (c === '#' && !inWord) {
336
+ // A comment runs to the end of the line. Its text never executes, and
337
+ // an apostrophe in it (`# check the wallet's balance`) must not open a
338
+ // quote that swallows the commands below.
339
+ while (i + 1 < text.length && text[i + 1] !== '\n')
340
+ i++;
341
+ }
342
+ else if (c === '$' && text[i + 1] === "'") {
343
+ // ANSI-C quoting: `$'…'`, where `\'` is a literal apostrophe.
344
+ if (opensMidWord(i))
345
+ current.collided = true;
346
+ // Bash finds the closing quote first (a backslash escapes one
347
+ // character), then decodes the body: `$'\c'` is closed.
348
+ let close = i + 2;
349
+ while (close < text.length && text[close] !== "'")
350
+ close += text[close] === '\\' ? 2 : 1;
351
+ const body = text.slice(i + 2, Math.min(close, text.length));
352
+ for (let k = 0; k < body.length; k++) {
353
+ if (body[k] === '\\' && k + 1 < body.length) {
354
+ const [decoded, used] = ansiCEscape(body, k + 1);
355
+ word += decoded;
356
+ k += used;
357
+ }
358
+ else {
359
+ word += body[k];
360
+ }
361
+ }
362
+ i = close;
363
+ if (i >= text.length)
364
+ unreliable = true;
365
+ else if (closesMidWord(i))
366
+ current.collided = true;
367
+ inWord = true;
368
+ }
232
369
  else if (c === "'") {
370
+ if (opensMidWord(i))
371
+ current.collided = true;
233
372
  const close = text.indexOf("'", i + 1);
373
+ if (close === -1)
374
+ unreliable = true;
375
+ else if (closesMidWord(close))
376
+ current.collided = true;
234
377
  const end = close === -1 ? text.length : close;
235
378
  word += text.slice(i + 1, end);
236
379
  inWord = true;
237
380
  i = end;
238
381
  }
239
- else if (c === '"') {
382
+ else if (c === '"' || (c === '$' && text[i + 1] === '"')) {
383
+ // `$"…"` (locale translation) quotes like `"…"`.
384
+ if (c === '$')
385
+ i++;
386
+ if (opensMidWord(i))
387
+ current.collided = true;
240
388
  i++;
241
389
  while (i < text.length && text[i] !== '"') {
242
390
  if (text[i] === '\\' && i + 1 < text.length && '"\\$`'.includes(text[i + 1]))
243
391
  i++;
392
+ else if ((text[i] === '$' && text[i + 1] === '(') || text[i] === '`') {
393
+ // `"$(node pay.mjs)"`, `"`node pay.mjs`"`: still runs inside quotes.
394
+ const tick = text[i] === '`';
395
+ const bodyStart = i + (tick ? 1 : 2);
396
+ let end = tick ? bodyStart : substitutionEnd(text, bodyStart);
397
+ if (tick)
398
+ while (end < text.length && text[end] !== '`')
399
+ end += text[end] === '\\' ? 2 : 1;
400
+ if (end === -1 || end >= text.length) {
401
+ unreliable = true;
402
+ end = text.length;
403
+ }
404
+ current.substitutions.push(text.slice(bodyStart, end));
405
+ word += text.slice(i, end + 1);
406
+ i = end + 1;
407
+ continue;
408
+ }
244
409
  word += text[i];
245
410
  i++;
246
411
  }
412
+ if (i >= text.length)
413
+ unreliable = true;
414
+ else if (closesMidWord(i))
415
+ current.collided = true;
247
416
  inWord = true;
248
417
  }
249
418
  else if (c === ' ' || c === '\t') {
@@ -317,7 +486,7 @@ export function splitShellCommands(text) {
317
486
  }
318
487
  }
319
488
  endCommand();
320
- return commands;
489
+ return { commands, unreliable };
321
490
  }
322
491
  /** Files a command writes or replaces through its own arguments. */
323
492
  function filesWrittenBy(words) {
@@ -501,33 +670,98 @@ function analyzeCommand(words) {
501
670
  }
502
671
  return run;
503
672
  }
673
+ function runsSomething(run) {
674
+ return Boolean(run.interpreter || run.cli || run.scripts.length || run.inlineCode.length || run.inlineShell.length);
675
+ }
676
+ /**
677
+ * Heredoc markers on one physical line that the shell would act on: not in
678
+ * quotes and not in a comment. `quote` is the state carried in from the line
679
+ * before, so a `<<` inside a multi-line `node -e '…'` program (`1n << 8n`)
680
+ * is code, not a heredoc. Also returns where an unquoted comment starts
681
+ * (`cat <<EOF # notes | node` pipes nothing) and the state carried out.
682
+ */
683
+ function scanLineForHeredocs(line, quote) {
684
+ const markers = [];
685
+ let uncertain = false;
686
+ for (let i = 0; i < line.length; i++) {
687
+ const c = line[i];
688
+ if (quote === "'") {
689
+ if (c === "'")
690
+ quote = '';
691
+ }
692
+ else if (quote === '"' || quote === "$'") {
693
+ // Quotes nest inside `"$(…)"` and `"`…`"`; a line scan cannot follow that.
694
+ if (quote === '"' && ((c === '$' && line[i + 1] === '(') || c === '`'))
695
+ uncertain = true;
696
+ if (c === '\\')
697
+ i++;
698
+ else if ((quote === '"' && c === '"') || (quote === "$'" && c === "'"))
699
+ quote = '';
700
+ }
701
+ else if (c === '\\') {
702
+ i++;
703
+ }
704
+ else if (c === '$' && line[i + 1] === "'") {
705
+ quote = "$'";
706
+ i++;
707
+ }
708
+ else if (c === "'" || c === '"') {
709
+ quote = c;
710
+ }
711
+ else if (c === '#' && (line[i - 1] === ')' || line[i - 1] === '`')) {
712
+ uncertain = true;
713
+ }
714
+ else if (c === '#' && (i === 0 || /[\s;&|(<>]/.test(line[i - 1]))) {
715
+ return { markers, commentAt: i, quote, uncertain };
716
+ }
717
+ else if (c === '(' && line[i + 1] === '(') {
718
+ // `$((1 << n))`, `((x <<= 1))`: a shift, not a heredoc.
719
+ uncertain = true;
720
+ }
721
+ else if (c === '<' && line[i + 1] === '<' && line[i + 2] !== '<' && line[i - 1] !== '<') {
722
+ const m = /^<<(-?)\s*(['"]?)([A-Za-z_][\w.-]*)\2/.exec(line.slice(i));
723
+ if (m) {
724
+ markers.push({ index: i, length: m[0].length, stripTabs: m[1] === '-', delim: m[3] });
725
+ i += m[0].length - 1;
726
+ }
727
+ else {
728
+ i++;
729
+ }
730
+ }
731
+ }
732
+ return { markers, commentAt: -1, quote, uncertain };
733
+ }
504
734
  /** Pull heredoc bodies out so their contents are not mistaken for shell. */
505
735
  function extractHeredocs(text) {
506
736
  const lines = text.split('\n');
507
737
  const out = [];
508
738
  const heredocs = [];
739
+ let quote = '';
740
+ let uncertain = false;
509
741
  for (let i = 0; i < lines.length; i++) {
510
742
  const line = lines[i];
511
743
  out.push(line);
512
- const markers = [...line.matchAll(/<<(-?)\s*(['"]?)([A-Za-z_][\w.-]*)\2/g)];
513
- for (const m of markers) {
514
- const stripTabs = m[1] === '-';
515
- const delim = m[3];
744
+ const scan = scanLineForHeredocs(line, quote);
745
+ quote = scan.quote;
746
+ if (scan.uncertain)
747
+ uncertain = true;
748
+ const codeEnd = scan.commentAt === -1 ? line.length : scan.commentAt;
749
+ for (const m of scan.markers) {
516
750
  const body = [];
517
751
  i++;
518
752
  while (i < lines.length) {
519
- const candidate = stripTabs ? lines[i].replace(/^\t+/, '') : lines[i];
520
- if (candidate === delim)
753
+ const candidate = m.stripTabs ? lines[i].replace(/^\t+/, '') : lines[i];
754
+ if (candidate === m.delim)
521
755
  break;
522
756
  body.push(lines[i]);
523
757
  i++;
524
758
  }
525
759
  const before = line.slice(0, m.index);
526
760
  const head = before.split(/;|&&|\|\||\||\(|\$\(/).pop() ?? '';
527
- heredocs.push({ head, tail: line.slice((m.index ?? 0) + m[0].length), body: body.join('\n') });
761
+ heredocs.push({ head, tail: line.slice(m.index + m.length, codeEnd), body: body.join('\n') });
528
762
  }
529
763
  }
530
- return { shell: out.join('\n'), heredocs };
764
+ return { shell: out.join('\n'), heredocs, uncertain };
531
765
  }
532
766
  function readScript(resolved) {
533
767
  try {
@@ -541,7 +775,7 @@ function readScript(resolved) {
541
775
  }
542
776
  }
543
777
  function collect(command, cwd, depth, out, seen) {
544
- const { shell, heredocs } = extractHeredocs(command);
778
+ const { shell, heredocs, uncertain } = extractHeredocs(command);
545
779
  // A heredoc is code when an interpreter reads it (`node <<EOF`, `cat <<EOF | python3`).
546
780
  // Otherwise it is data — usually a file being written (`cat > pay.mjs <<EOF`),
547
781
  // which counts as code if this same command then runs that file.
@@ -569,7 +803,13 @@ function collect(command, cwd, depth, out, seen) {
569
803
  if (target)
570
804
  writtenFiles.set(path.basename(expandHome(target[2])), doc.body);
571
805
  }
572
- const commands = splitShellCommands(shell);
806
+ const { commands, unreliable } = scanShell(shell);
807
+ // Quoting that did not resolve cleanly: the split below may have cut a
808
+ // program short and left the rest as shell words (a send among them). A
809
+ // collision in a command that runs nothing (`grep 'a' b' c'`) is only data.
810
+ if (uncertain || unreliable || commands.some(c => c.collided && runsSomething(analyzeCommand(c.words)))) {
811
+ out.opaque.push(command);
812
+ }
573
813
  // Files this same command writes or replaces before (or while) running
574
814
  // things: their on-disk contents are stale, so the command text that writes
575
815
  // them is evidence too.
@@ -588,10 +828,10 @@ function collect(command, cwd, depth, out, seen) {
588
828
  continue;
589
829
  }
590
830
  const run = analyzeCommand(words);
591
- const runsSomething = Boolean(run.interpreter || run.cli || run.scripts.length || run.inlineCode.length || run.inlineShell.length);
831
+ const runs = runsSomething(run);
592
832
  if (simple.background || words.some(w => DETACHERS.has(path.basename(w))))
593
833
  out.detached = true;
594
- if (!runsSomething && (simple.writesFile || !NON_RECORDING.has(path.basename(words[0] ?? '')))) {
834
+ if (!runs && (simple.writesFile || !NON_RECORDING.has(path.basename(words[0] ?? '')))) {
595
835
  out.data.push(words.join(' '));
596
836
  }
597
837
  // A program whose output goes into a file writes what it prints
@@ -599,7 +839,7 @@ function collect(command, cwd, depth, out, seen) {
599
839
  // with a body or a write method sends what it carries. A send's own
600
840
  // text is left out: its error messages are not outcome records.
601
841
  const httpWrite = Boolean(run.cli && isHttpWrite(words));
602
- if (runsSomething && (simple.writesFile || httpWrite)) {
842
+ if (runs && (simple.writesFile || httpWrite)) {
603
843
  const own = [words.join(' '), ...run.inlineCode];
604
844
  for (const t of own)
605
845
  if (!isPaymentSend(t))
@@ -621,6 +861,12 @@ function collect(command, cwd, depth, out, seen) {
621
861
  }
622
862
  }
623
863
  const runDir = run.chdir ? path.resolve(cwd, expandHome(run.chdir)) : cwd;
864
+ for (const sub of simple.substitutions) {
865
+ if (depth < MAX_SHELL_DEPTH)
866
+ collect(sub, cwd, depth + 1, out, seen);
867
+ else
868
+ out.code.push(sub);
869
+ }
624
870
  for (const code of run.inlineCode)
625
871
  out.code.push(code);
626
872
  if (run.cli)
@@ -678,12 +924,14 @@ function collect(command, cwd, depth, out, seen) {
678
924
  * must not count as running it.
679
925
  */
680
926
  export function analyzeBash(command, workingDir) {
681
- const out = { code: [], data: [], detached: false };
927
+ const out = { code: [], opaque: [], data: [], detached: false };
682
928
  collect(command, workingDir, 0, out, new Set());
683
- return { code: out.code.join('\n'), data: out.data.join('\n'), detached: out.detached };
929
+ return { code: out.code.join('\n'), opaque: out.opaque.join('\n'), data: out.data.join('\n'), detached: out.detached };
684
930
  }
931
+ /** Everything a Bash run may execute: its code, plus text whose quoting did not resolve. */
685
932
  export function bashExecutedText(command, workingDir) {
686
- return analyzeBash(command, workingDir).code;
933
+ const { code, opaque } = analyzeBash(command, workingDir);
934
+ return opaque ? `${code}\n${opaque}` : code;
687
935
  }
688
936
  export function isPaymentSend(text) {
689
937
  return SEND_PATTERNS.some(re => re.test(text));
@@ -793,6 +1041,12 @@ export function unknownOutcomeNotice(a) {
793
1041
  export function paymentHoldsDir() {
794
1042
  return path.join(BLOCKRUN_DIR, 'payment-holds');
795
1043
  }
1044
+ /**
1045
+ * Bumped when the saved meaning of a field changes. Version 1 (3.49.7) set
1046
+ * `overriddenByUser` when the user approved, before the send ran, so a send
1047
+ * that was then denied left it set; those flags are not trusted on load.
1048
+ */
1049
+ const HOLDS_FORMAT = 2;
796
1050
  function holdsPath(sessionId) {
797
1051
  return path.join(paymentHoldsDir(), `${sessionId.replace(/[^\w.-]/g, '_')}.json`);
798
1052
  }
@@ -801,7 +1055,13 @@ export function loadPaymentAttempts(sessionId) {
801
1055
  const raw = JSON.parse(fs.readFileSync(holdsPath(sessionId), 'utf-8'));
802
1056
  if (!Array.isArray(raw.attempts))
803
1057
  return [];
804
- return raw.attempts.filter((a) => !!a && typeof a === 'object' && typeof a.id === 'number' && Array.isArray(a.recipients)).map(a => ({ ...a, senders: Array.isArray(a.senders) ? a.senders : [], txHashes: Array.isArray(a.txHashes) ? a.txHashes : [] }));
1058
+ const trustOverrides = raw.format === HOLDS_FORMAT;
1059
+ return raw.attempts.filter((a) => !!a && typeof a === 'object' && typeof a.id === 'number' && Array.isArray(a.recipients)).map(a => ({
1060
+ ...a,
1061
+ senders: Array.isArray(a.senders) ? a.senders : [],
1062
+ txHashes: Array.isArray(a.txHashes) ? a.txHashes : [],
1063
+ overriddenByUser: trustOverrides && a.overriddenByUser === true,
1064
+ }));
805
1065
  }
806
1066
  catch {
807
1067
  return [];
@@ -812,7 +1072,7 @@ export function savePaymentAttempts(sessionId, attempts) {
812
1072
  fs.mkdirSync(paymentHoldsDir(), { recursive: true });
813
1073
  const file = holdsPath(sessionId);
814
1074
  const tmp = `${file}.${process.pid}.tmp`;
815
- fs.writeFileSync(tmp, JSON.stringify({ sessionId, attempts }, null, 2));
1075
+ fs.writeFileSync(tmp, JSON.stringify({ format: HOLDS_FORMAT, sessionId, attempts }, null, 2));
816
1076
  fs.renameSync(tmp, file);
817
1077
  }
818
1078
  catch {
@@ -208,6 +208,10 @@ export class StreamingExecutor {
208
208
  ? await this.guard.beforeExecute(invocation, this.scope)
209
209
  : null;
210
210
  if (guardResult) {
211
+ // Answered by the guard instead of running: a later check can block
212
+ // after an earlier one registered state (a payment-hold approval, a
213
+ // trade reservation) for this invocation, so release it.
214
+ this.guard?.cancelInvocation(invocation.id);
211
215
  return guardResult;
212
216
  }
213
217
  // Permission check
@@ -44,8 +44,18 @@ export declare class SessionToolGuard {
44
44
  * an OUTCOME UNKNOWN notice is appended before the model decides anything.
45
45
  */
46
46
  afterExecute(invocation: CapabilityInvocation, result: CapabilityResult): CapabilityResult;
47
- /** Payment attempts this session whose outcome is still unknown. */
47
+ /**
48
+ * Payment attempts this session whose outcome is still unknown: no lookup
49
+ * has checked them. A user override does not resolve an attempt — it
50
+ * answers "may I send again", not "did the first one settle".
51
+ */
48
52
  unresolvedPaymentAttempts(): PaymentAttempt[];
53
+ /**
54
+ * Attempts that hold a new send to the same recipient. A lookup does not
55
+ * lift a hold (a pending receipt is not a failure); only a send the user
56
+ * approved past it, once that send has actually run.
57
+ */
58
+ private holdingPaymentAttempts;
49
59
  private checkPaymentHold;
50
60
  private askToOverrideHold;
51
61
  private afterPayment;
@@ -213,8 +213,7 @@ function lookupAddressesAttempt(lookup, attempt) {
213
213
  const text = lookup.toLowerCase();
214
214
  return keys.some(k => text.includes(k));
215
215
  }
216
- function negativeOutcomeBlock(unresolved) {
217
- const pending = unresolved.filter(a => !a.reconciled);
216
+ function negativeOutcomeBlock(pending) {
218
217
  return {
219
218
  output: 'Blocked by Franklin\'s payment guard: this call records a payment as failed/unpaid, but the outcome of ' +
220
219
  `${pending.length === 1 ? 'this attempt is' : 'these attempts are'} UNKNOWN and nothing has been checked yet:\n` +
@@ -510,8 +509,20 @@ export class SessionToolGuard {
510
509
  }
511
510
  return result;
512
511
  }
513
- /** Payment attempts this session whose outcome is still unknown. */
512
+ /**
513
+ * Payment attempts this session whose outcome is still unknown: no lookup
514
+ * has checked them. A user override does not resolve an attempt — it
515
+ * answers "may I send again", not "did the first one settle".
516
+ */
514
517
  unresolvedPaymentAttempts() {
518
+ return this.paymentAttempts.filter(a => !a.reconciled);
519
+ }
520
+ /**
521
+ * Attempts that hold a new send to the same recipient. A lookup does not
522
+ * lift a hold (a pending receipt is not a failure); only a send the user
523
+ * approved past it, once that send has actually run.
524
+ */
525
+ holdingPaymentAttempts() {
515
526
  return this.paymentAttempts.filter(a => !a.overriddenByUser);
516
527
  }
517
528
  async checkPaymentHold(invocation, scope) {
@@ -520,8 +531,12 @@ export class SessionToolGuard {
520
531
  const cmd = String(invocation.input.command ?? '').trim();
521
532
  if (!cmd)
522
533
  return null;
523
- const { code, data, detached } = analyzeBash(cmd, scope.workingDir);
524
- const hasUncheckedAttempt = unresolved.some(a => !a.reconciled);
534
+ const { code: executed, opaque, data, detached } = analyzeBash(cmd, scope.workingDir);
535
+ // What may run: sends and persisted records are judged on this, so
536
+ // unresolved quoting fails closed. A run whose parse is unreliable
537
+ // (opaque) never counts as a check, whatever `executed` holds.
538
+ const code = opaque ? `${executed}\n${opaque}` : executed;
539
+ const hasUncheckedAttempt = unresolved.length > 0;
525
540
  // Recording failed/unpaid from the shell — checked before anything
526
541
  // else, so batching it with a send or a lookup changes nothing: text it
527
542
  // writes to a file or passes to a CLI (`echo '{"status":"unpaid"}' >
@@ -540,20 +555,21 @@ export class SessionToolGuard {
540
555
  // other way — every wallet Franklin holds.
541
556
  const named = own.filter(a => code.toLowerCase().includes(a.toLowerCase()));
542
557
  const senders = (named.length ? named : own).map(a => a.toLowerCase());
543
- const blocking = unresolved.filter(a => attemptsOverlap(a.recipients, recipients));
558
+ const blocking = this.holdingPaymentAttempts().filter(a => attemptsOverlap(a.recipients, recipients));
544
559
  if (blocking.length > 0) {
545
560
  const allowed = await this.askToOverrideHold(blocking, cmd, scope);
546
561
  if (!allowed)
547
562
  return paymentHoldResult(blocking);
548
- for (const a of blocking)
549
- a.overriddenByUser = true;
550
- this.persistPaymentAttempts();
563
+ // The hold is lifted in afterPayment, once this send has run. A
564
+ // permission prompt or PreSpend hook can still stop it, and then
565
+ // nothing was sent and the hold must stay.
551
566
  this.userAllowedPaymentSends.add(invocation.id);
552
567
  }
553
568
  this.pendingPaymentSends.set(invocation.id, {
554
569
  command: commandPreview(cmd),
555
570
  recipients,
556
571
  senders,
572
+ overrides: blocking.map(a => a.id),
557
573
  // `node pay.mjs &` or `nohup …` returns before the payment does,
558
574
  // exactly like the tool's own run_in_background.
559
575
  background: Boolean(invocation.input.run_in_background) || detached,
@@ -562,11 +578,11 @@ export class SessionToolGuard {
562
578
  }
563
579
  // Classified on executed code only: printing a lookup into a file is
564
580
  // not a lookup.
565
- if (isReconciliation(code)) {
581
+ if (!opaque && isReconciliation(executed)) {
566
582
  // A background lookup returns before it has looked anything up, so
567
583
  // it can never count as a check.
568
584
  if (unresolved.length > 0 && !invocation.input.run_in_background && !detached) {
569
- this.pendingReconciles.set(invocation.id, code);
585
+ this.pendingReconciles.set(invocation.id, executed);
570
586
  }
571
587
  }
572
588
  // Bash was judged above on what it writes and runs, not on its raw text.
@@ -575,7 +591,7 @@ export class SessionToolGuard {
575
591
  // Recording an unknown outcome as failed/unpaid before anything was
576
592
  // checked. Read-only tools and questions to the user are never outcome
577
593
  // records, so they pass.
578
- if (unresolved.some(a => !a.reconciled) &&
594
+ if (unresolved.length > 0 &&
579
595
  !OUTCOME_NEUTRAL_TOOLS.has(invocation.name) &&
580
596
  inputRecordsNegativeOutcome(invocation.name, invocation.input)) {
581
597
  return negativeOutcomeBlock(unresolved);
@@ -601,7 +617,9 @@ export class SessionToolGuard {
601
617
  blocking.map(a => `Earlier: ${describeAttempt(a)}`).join('\n') +
602
618
  `\n\nNew send: ${commandPreview(command)}\n\n` +
603
619
  '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.',
620
+ 'the recipient balance and sender nonce are unchanged). Deny keeps the hold.\n\n' +
621
+ 'Approving allows this one send. It does not mark the earlier attempt as failed: it stays UNKNOWN, ' +
622
+ 'and recording it as failed or unpaid still needs a read-only lookup.',
605
623
  options: ['approve', 'deny'],
606
624
  payload: { attempts: blocking, command },
607
625
  });
@@ -642,7 +660,19 @@ export class SessionToolGuard {
642
660
  if (!pending)
643
661
  return result;
644
662
  this.pendingPaymentSends.delete(invocation.id);
663
+ this.userAllowedPaymentSends.delete(invocation.id);
645
664
  const reason = forcedReason ?? ambiguousOutcomeReason(output, result.isError, pending.background);
665
+ // The send the user approved went out, or may have: the attempts it was
666
+ // approved past no longer hold sends. They are still unknown until a
667
+ // lookup checks them. A definitive failure before sending (a syntax
668
+ // error, a missing script) sent nothing, so the hold stays.
669
+ if (pending.overrides.length > 0 && (!result.isError || reason)) {
670
+ for (const a of this.paymentAttempts) {
671
+ if (pending.overrides.includes(a.id))
672
+ a.overriddenByUser = true;
673
+ }
674
+ this.persistPaymentAttempts();
675
+ }
646
676
  if (!reason)
647
677
  return result;
648
678
  const attempt = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.7",
3
+ "version": "3.49.9",
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": {
@@ -77,7 +77,7 @@
77
77
  "dependencies": {
78
78
  "@blockrun/llm": "^3.19.1",
79
79
  "@blockrun/model-catalog": "https://codeload.github.com/BlockRunAI/model-catalog/tar.gz/465c45941fb8ea9d6858fe8402abc8ba8934be90",
80
- "@blockrun/router-core": "https://codeload.github.com/BlockRunAI/router-core/tar.gz/d7bc10ce184b3daa40bcc115b523fd629d847a52",
80
+ "@blockrun/router-core": "https://codeload.github.com/BlockRunAI/router-core/tar.gz/27125a3dfe319a6f422a0c0f41bf1666b0dc61a9",
81
81
  "@colbymchenry/codegraph": "^1.5.0",
82
82
  "@modelcontextprotocol/sdk": "^1.29.0",
83
83
  "@polymarket/builder-relayer-client": "^0.0.10",