@alexwkleung/reika 0.7.0 → 0.9.0

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 (43) hide show
  1. package/README.md +15 -0
  2. package/README.zh-CN.md +15 -0
  3. package/dist/agent/compaction.js +82 -27
  4. package/dist/agent/loop.js +84 -20
  5. package/dist/agent/prefillcost.js +16 -0
  6. package/dist/agent/prompt.js +5 -2
  7. package/dist/cli.js +5 -11
  8. package/dist/context/bootstrap.js +1 -1
  9. package/dist/debug.js +15 -0
  10. package/dist/{headless.js → headless/headless.js} +185 -48
  11. package/dist/{headlessargs.js → headless/headlessargs.js} +12 -2
  12. package/dist/headless/headlessprompt.js +132 -0
  13. package/dist/mcp/client.js +97 -5
  14. package/dist/mcp/manager.js +15 -2
  15. package/dist/provider/client.js +13 -0
  16. package/dist/session.js +12 -1
  17. package/dist/{skills.js → skills/skills.js} +93 -13
  18. package/dist/store/sessions.js +40 -3
  19. package/dist/store/transcript.js +38 -1
  20. package/dist/tools/_carriers.js +119 -0
  21. package/dist/tools/_danger.js +305 -82
  22. package/dist/tools/_readonly.js +13 -12
  23. package/dist/tools/_sandbox.js +13 -5
  24. package/dist/ui/App.js +288 -83
  25. package/dist/ui/Approval.js +80 -33
  26. package/dist/ui/Confirm.js +1 -27
  27. package/dist/ui/DiffView.js +24 -14
  28. package/dist/ui/Question.js +152 -19
  29. package/dist/ui/ResumeSelect.js +13 -6
  30. package/dist/ui/Scrollback.js +44 -8
  31. package/dist/ui/Status.js +35 -10
  32. package/dist/ui/commands.js +1 -1
  33. package/dist/ui/dialogspecs.js +38 -0
  34. package/dist/ui/layout.js +149 -6
  35. package/dist/ui/markdown.js +6 -5
  36. package/dist/ui/pr.js +15 -9
  37. package/dist/ui/reactbuild.js +15 -0
  38. package/dist/ui/summary.js +3 -2
  39. package/dist/ui/termtext.js +5 -1
  40. package/dist/ui/theme.js +5 -0
  41. package/dist/ui/tui.js +9 -0
  42. package/package.json +1 -1
  43. /package/dist/{skillmatch.js → skills/skillmatch.js} +0 -0
@@ -0,0 +1,119 @@
1
+ // The words that sit between a segment's start and the command it actually runs: privilege and
2
+ // environment wrappers (`sudo -u me`, `env -i`), the two carriers that only bound or reprioritize a
3
+ // command (`timeout 5`, `nice -n 10`), and `command`/`nohup`/`exec`/`time`.
4
+ //
5
+ // One table, because two readers ask the same question about it and answered differently (#756).
6
+ // `_danger.ts`'s `stripVerbPrefix` puts the verb in verb position for the `^`-anchored approval
7
+ // patterns, where missing one costs a fetch that runs unprompted under `safe`: `timeout 5 curl x`
8
+ // read as a `timeout` line and reported nothing. `_readonly.ts`'s `dropCarriers` skips the carrier
9
+ // for plan mode's read-only gate and the sandbox's network reader, where a carrier it does not know
10
+ // is a read it refuses. A spelling only one of them learns is a hole in whichever it is not
11
+ // (#749/#752 were that drift, one level down), so the table is the single place a carrier is
12
+ // described, and both walks below are its only readers.
13
+ //
14
+ // Nothing here is a shell lexer: the walkers take the words their caller already produced —
15
+ // `_danger.ts`'s quote-aware `SHELL_WORD_RE` walk, `_readonly.ts`'s `words()`.
16
+ export const CARRIERS = {
17
+ // `sudo -u me curl x` used to keep the option's VALUE as the lead, and `curl` read as an argument
18
+ // (#794). Both lists are closed on purpose: an option nobody enumerated costs a label, which is
19
+ // the direction `_danger.ts` errs in.
20
+ sudo: {
21
+ values: [
22
+ '-u',
23
+ '-g',
24
+ '-U',
25
+ '-C',
26
+ '-D',
27
+ '-h',
28
+ '-p',
29
+ '-r',
30
+ '-t',
31
+ '-T',
32
+ '-R',
33
+ '--user',
34
+ '--group',
35
+ '--other-user',
36
+ '--close-from',
37
+ '--chdir',
38
+ '--host',
39
+ '--prompt',
40
+ '--role',
41
+ '--type',
42
+ '--command-timeout',
43
+ ],
44
+ operands: 0,
45
+ transparent: false,
46
+ },
47
+ // `env` takes its options and its `VAR=value` operands in any order, so the walk keeps it in place
48
+ // across an assignment. `-S`/`--split-string` is here as well: its value is already read as a
49
+ // program of its own by `_danger.ts`'s `nestedBodies`, and skipping the value silently would be
50
+ // the one direction that file does not take.
51
+ env: {
52
+ values: ['-u', '-C', '-S', '-P', '--unset', '--chdir', '--split-string', '--path'],
53
+ operands: 0,
54
+ transparent: false,
55
+ },
56
+ exec: { values: ['-a', '--argv0'], operands: 0, transparent: false },
57
+ time: { values: ['-o', '-f', '--output', '--format'], operands: 0, transparent: false },
58
+ command: { values: [], operands: 0, transparent: false },
59
+ nohup: { values: [], operands: 0, transparent: false },
60
+ // `timeout [OPTION] DURATION COMMAND`: the DURATION is a positional operand, and `-s`/`-k` take
61
+ // values (`timeout -s KILL 5 curl`, `timeout -k 1s 5 curl`). GNU stops reading options at the
62
+ // first operand (`timeout 5 -k 1s curl` runs a command named `-k` — measured), so options are only
63
+ // read before it. `--signal=KILL` carries its value attached and eats no word.
64
+ timeout: { values: ['-s', '--signal', '-k', '--kill-after'], operands: 1, transparent: true },
65
+ // `nice [-n N | -N] COMMAND`, plus `--adjustment=N`. The legacy `nice -10 curl` is one word that
66
+ // starts with `-` and takes no value, which the option arm below already reads correctly.
67
+ nice: { values: ['-n', '--adjustment'], operands: 0, transparent: true },
68
+ };
69
+ const VALUE_SETS = new Map(Object.entries(CARRIERS).map(([name, carrier]) => [name, new Set(carrier.values)]));
70
+ /** Whether `word` (already read as an option) consumes the next word as its value. */
71
+ export function carrierOptionValue(carrier, word) {
72
+ if (VALUE_SETS.get(carrier)?.has(word))
73
+ return true;
74
+ // A BUNDLED short spelling (`sudo -iu me`, `env -iu PATH …`) follows getopt: the letters are read
75
+ // left to right, and the FIRST one that takes a value takes the rest of the bundle as that value
76
+ // (`-ume` is `-u me`, `-of x` is `-o f`) unless it is the bundle's LAST letter, in which case the
77
+ // value is the next word (`-iu me` is `-i -u me`). Anything else eats nothing. A long spelling
78
+ // carrying `=` (`--user=me`) keeps its value attached and never reaches here.
79
+ if (!/^-[a-zA-Z]+$/.test(word))
80
+ return false;
81
+ for (let i = 1; i < word.length; i++) {
82
+ if (VALUE_SETS.get(carrier)?.has(`-${word[i]}`))
83
+ return i === word.length - 1;
84
+ }
85
+ return false;
86
+ }
87
+ /**
88
+ * The index of the word the carrier at `start` hands to — past its own options and operands — or -1
89
+ * when `wordList[start]` is not a carrier (or, with `transparentOnly`, not one that leaves the
90
+ * command's effect alone). Callers loop, because carriers nest: `timeout 5 nice gh …` is two.
91
+ */
92
+ export function skipCarrier(wordList, start, transparentOnly = false) {
93
+ const carrier = CARRIERS[wordList[start] ?? ''];
94
+ if (!carrier || (transparentOnly && !carrier.transparent))
95
+ return -1;
96
+ let i = start + 1;
97
+ let operands = carrier.operands;
98
+ let optionsEnded = false;
99
+ while (i < wordList.length) {
100
+ const word = wordList[i];
101
+ // `--` ends the carrier's options, not its operands: `timeout -- 5 cat f` still has a DURATION.
102
+ if (!optionsEnded && word === '--') {
103
+ optionsEnded = true;
104
+ i++;
105
+ continue;
106
+ }
107
+ // A bare `-` is an operand, not an option, so it falls through to the operand count.
108
+ if (!optionsEnded && word.startsWith('-') && word !== '-') {
109
+ i += carrierOptionValue(wordList[start], word) ? 2 : 1;
110
+ continue;
111
+ }
112
+ if (operands <= 0)
113
+ break;
114
+ operands--;
115
+ optionsEnded = true;
116
+ i++;
117
+ }
118
+ return Math.min(i, wordList.length);
119
+ }
@@ -10,6 +10,7 @@ import { existsSync } from 'node:fs';
10
10
  import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
12
  import { WORD_RE, dequote, maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
13
+ import { CARRIERS, carrierOptionValue } from './_carriers.js';
13
14
  import { scanHeredocs, stripHeredocs } from './_heredoc.js';
14
15
  import { maskMarkdownData } from './_markdown.js';
15
16
  // Workflow-policy commands: not destructive (a commit is local and reversible, a push is
@@ -22,6 +23,7 @@ const POLICY_PATTERNS = [
22
23
  { re: /\bgit\s+commit\b/, label: 'Git commit (records to version history)' },
23
24
  // Bare push; force push is also flagged separately below as a destructive pattern.
24
25
  { re: /\bgit\s+push\b/, label: 'Git push (publishes commits to remote)' },
26
+ { re: /\bgit\s+send-email\b/, label: 'Git send-email (sends mail, outward-facing)' },
25
27
  // Outward-facing GitHub/HF actions. Scoped to the publishing subcommands here because they are
26
28
  // the ones whose label the user needs to see in these words — the rest of the coverage is the
27
29
  // read-verb allowlists (`GH_READ_VERBS`, `HF_READ_VERBS`), which flag every verb that is not a
@@ -730,22 +732,19 @@ const VERB_PATTERNS = [
730
732
  // reading, and the value is exactly what that `bash -c` runs. So `verbLabels` reads a segment both
731
733
  // ways and reports the union — quoting can add a label, and cannot cost one. Both readings strip the
732
734
  // same words, from one list, or the union would disagree about a wrapper only one of them knows.
733
- const VERB_PREFIX_WORDS = [
734
- 'sudo',
735
- 'command',
736
- 'nohup',
737
- 'exec',
738
- 'env',
739
- 'time',
740
- 'if',
741
- 'then',
742
- 'else',
743
- 'elif',
744
- 'do',
745
- 'while',
746
- 'until',
747
- '!',
748
- ];
735
+ //
736
+ // The words are `_carriers.ts`'s table plus the shell grammar a segment can open with (`if curl …
737
+ // ; then`). The table is shared with `_readonly.ts`'s `dropCarriers` (#756) because a carrier only
738
+ // one of the two knew is a fetch that runs unprompted on this side and a refused read on that one:
739
+ // `timeout 5 curl x` and `nice curl x` each reported NOTHING here, so under `safe` the fetch ran.
740
+ //
741
+ // The whitespace reading is the blind half of that pair, and it can only see bare words: it has no
742
+ // way to tell which of a carrier's tokens is an option's value, so it strips the carrier's NAME and
743
+ // leaves its operands standing (`timeout 5 curl` reads as `5 curl`). Nothing is lost by that — a
744
+ // leftover operand is a word no `^`-anchored pattern matches, and the union takes the label from
745
+ // the quoted reading, which is the one that reaches the verb.
746
+ const SHELL_PREFIX_KEYWORDS = ['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!'];
747
+ const VERB_PREFIX_WORDS = [...Object.keys(CARRIERS), ...SHELL_PREFIX_KEYWORDS];
749
748
  const VERB_PREFIX_WORD_SET = new Set(VERB_PREFIX_WORDS);
750
749
  const VERB_PREFIX_WS_RE = new RegExp(String.raw `^(?:(?:[A-Za-z_]\w*=\S*|${VERB_PREFIX_WORDS.join('|')})\s+)+`);
751
750
  const SHELL_WORD_RE = /(?:"(?:[^"\\]|\\[\s\S])*"|\$'(?:[^'\\]|\\[\s\S])*'|'[^']*'|\\[\s\S]|[^\s"'\\])+/y;
@@ -754,61 +753,20 @@ const WORD_GAP_RE = /\s+/y;
754
753
  const ENV_ASSIGN_WORD_RE = /^[A-Za-z_]\w*=/;
755
754
  // A wrapper's own options sit between it and the command it runs (`sudo -u me grep …`, `env -i …`,
756
755
  // `time -p …`); left in place, the option became the lead and the command behind it read as an
757
- // argument (#757 review). These are the options that consume the next word as their value, in their
758
- // SHORT spellings; the long ones are `WRAPPER_LONG_VALUE_OPTIONS` below and the bundled ones are
759
- // `wrapperOptionValue`'s last clause (#794). Both lists are closed on purpose: an option nobody
756
+ // argument (#757 review). Which options those are — and how many operands the carrier itself takes
757
+ // before the command (`timeout`'s DURATION) — is `_carriers.ts`'s table, read here and in
758
+ // `_readonly.ts`'s `dropCarriers` (#756). Its lists are closed on purpose: an option nobody
760
759
  // enumerated costs a label, which is the direction this file errs in.
761
- const WRAPPER_VALUE_OPTIONS = {
762
- sudo: new Set(['-u', '-g', '-U', '-C', '-D', '-h', '-p', '-r', '-t', '-T', '-R']),
763
- env: new Set(['-u', '-C', '-S', '-P']),
764
- exec: new Set(['-a']),
765
- time: new Set(['-o', '-f']),
766
- };
767
- // The same options spelled out: `sudo --user me curl …` and `env --chdir /x make install` hid the
768
- // command behind them exactly as the short spellings did (#794).
769
- const WRAPPER_LONG_VALUE_OPTIONS = {
770
- sudo: new Set([
771
- '--user',
772
- '--group',
773
- '--other-user',
774
- '--close-from',
775
- '--chdir',
776
- '--host',
777
- '--prompt',
778
- '--role',
779
- '--type',
780
- '--command-timeout',
781
- ]),
782
- env: new Set(['--unset', '--chdir', '--split-string', '--path']),
783
- exec: new Set(['--argv0']),
784
- time: new Set(['--output', '--format']),
785
- };
786
- const WRAPPER_WORDS = new Set(['sudo', 'command', 'nohup', 'exec', 'env', 'time']);
760
+ const CARRIER_WORDS = new Set(Object.keys(CARRIERS));
787
761
  // `command -v x` looks `x` up and runs nothing, so it has no verb at all.
788
762
  const COMMAND_LOOKUP_RE = /^-[a-zA-Z]*[vV]/;
789
- // Whether a wrapper option consumes the NEXT word as its value. `word` has already been read as an
790
- // option. A long spelling carrying `=` (`--user=me`) keeps its value attached and eats nothing.
791
- function wrapperOptionValue(wrapper, word) {
792
- if (WRAPPER_VALUE_OPTIONS[wrapper]?.has(word))
793
- return true;
794
- if (WRAPPER_LONG_VALUE_OPTIONS[wrapper]?.has(word))
795
- return true;
796
- // A BUNDLED short spelling (`sudo -iu me`, `env -iu PATH …`) follows getopt: the letters are read
797
- // left to right, and the FIRST one that takes a value takes the rest of the bundle as that value
798
- // (`-ume` is `-u me`, `-of x` is `-o f`) unless it is the bundle's LAST letter, in which case the
799
- // value is the next word (`-iu me` is `-i -u me`). Anything else is a flag that eats nothing.
800
- if (!/^-[a-zA-Z]+$/.test(word))
801
- return false;
802
- for (let i = 1; i < word.length; i++) {
803
- if (WRAPPER_VALUE_OPTIONS[wrapper]?.has(`-${word[i]}`))
804
- return i === word.length - 1;
805
- }
806
- return false;
807
- }
808
763
  function stripVerbPrefix(segment) {
809
764
  let at = 0;
810
- let wrapper;
765
+ let carrier;
811
766
  let takesValue = false;
767
+ // Operands the carrier still takes before the command it runs: one for `timeout`, whose DURATION
768
+ // is not an option and used to land in verb position (`timeout 5 curl x` read as a `5`).
769
+ let operands = 0;
812
770
  for (;;) {
813
771
  SHELL_WORD_RE.lastIndex = at;
814
772
  let end = SHELL_WORD_RE.exec(segment) ? SHELL_WORD_RE.lastIndex : at;
@@ -818,29 +776,38 @@ function stripVerbPrefix(segment) {
818
776
  end = NON_SPACE_RUN_RE.lastIndex;
819
777
  }
820
778
  const word = segment.slice(at, end);
821
- if (wrapper === 'command' && COMMAND_LOOKUP_RE.test(word))
779
+ if (carrier === 'command' && COMMAND_LOOKUP_RE.test(word))
822
780
  return '';
823
- const isOption = wrapper !== undefined && (takesValue || word.startsWith('-'));
781
+ const isOption = carrier !== undefined && (takesValue || word.startsWith('-'));
824
782
  WORD_GAP_RE.lastIndex = end;
825
783
  const gap = WORD_GAP_RE.exec(segment);
826
- if (!gap || !(isOption || VERB_PREFIX_WORD_SET.has(word) || ENV_ASSIGN_WORD_RE.test(word))) {
784
+ if (!gap ||
785
+ !(isOption || operands > 0 || VERB_PREFIX_WORD_SET.has(word) || ENV_ASSIGN_WORD_RE.test(word))) {
827
786
  return segment.slice(at);
828
787
  }
829
788
  if (takesValue) {
830
789
  takesValue = false;
831
790
  }
832
791
  else if (isOption) {
833
- // `--` ends the wrapper's options: the next word is the command, even one spelled `-x`.
792
+ // `--` ends the carrier's options: the next word is the command, even one spelled `-x`.
834
793
  if (word === '--')
835
- wrapper = undefined;
794
+ carrier = undefined;
836
795
  else
837
- takesValue = wrapperOptionValue(wrapper, word);
796
+ takesValue = carrierOptionValue(carrier, word);
797
+ }
798
+ else if (ENV_ASSIGN_WORD_RE.test(word)) {
799
+ // An assignment is `env`'s own operand (`env FOO=1 -S …`) and leaves the carrier in place.
800
+ }
801
+ else if (operands > 0) {
802
+ operands--;
838
803
  }
839
- else if (WRAPPER_WORDS.has(word)) {
840
- wrapper = word;
804
+ else if (CARRIER_WORDS.has(word)) {
805
+ carrier = word;
806
+ operands = CARRIERS[word].operands;
841
807
  }
842
- else if (!ENV_ASSIGN_WORD_RE.test(word)) {
843
- wrapper = undefined;
808
+ else {
809
+ // A shell keyword: it runs the word after it, and is no carrier itself.
810
+ carrier = undefined;
844
811
  }
845
812
  at = WORD_GAP_RE.lastIndex;
846
813
  }
@@ -1447,6 +1414,232 @@ function nestedBodies(command) {
1447
1414
  }
1448
1415
  return found;
1449
1416
  }
1417
+ // An interpreter reading its PROGRAM from stdin rather than from an argument: `python3 -`, `node -`,
1418
+ // `ruby -`, `perl -`. The body arrives by heredoc, so the shell pastes it — nothing quote-parses a
1419
+ // body and the verb readers are blind to it (#699) — but the pasted text is code, not data, and a
1420
+ // script that shells out runs those commands for real. The sandbox does not cover that: signals are
1421
+ // not confined (`pkill`, `killall`), docker's socket is allowed, and a loopback cluster (kind,
1422
+ // minikube) is reachable by `kubectl` (#750).
1423
+ //
1424
+ // It is deliberately NOT read as a nested body the way a `-c` argument is. Handing the whole body to
1425
+ // `detectAtDepth` would re-open #699: a `;` in a string literal in a pasted body splits a segment
1426
+ // there as soon as nothing marks the body, which is what `verbData` suppresses for the outer pass.
1427
+ // So what is read here is narrow, and only in the direction that cannot hide anything:
1428
+ //
1429
+ // - `INTERPRETER_BODY_PATTERNS` over the whole body (they are specific enough to run on text);
1430
+ // - the verb readers over the STRING ARGUMENTS of a shell-out call site, and nothing else.
1431
+ //
1432
+ // Call sites only, not every string literal — `print("x; pkill y")` is data, and reading it is
1433
+ // exactly #699's false positive. The cost of the narrow reading is the other direction: a command
1434
+ // assembled at runtime (`os.system("pk" + "ill node")`) is still not seen.
1435
+ // A flag arm may carry `=value` (`node --input-type=module -`), which is otherwise a word past it.
1436
+ // The `-` is optional: with no script operand at all each of the four reads its program from stdin
1437
+ // too, and `python3 <<'PY'` is the spelling models write most. Bare, the flags must run to the end of
1438
+ // the command (a redirect, a separator, the line's end), or the next word is the script.
1439
+ const INTERPRETER_STDIN_RE = /\b(python[\d.]*|ruby|perl|node)((?:\s+-[\w-]+(?:=[^\s]+)?)*)(?:\s+(-)(?![\w.=-])|(?=[ \t]*(?:[<>|;&)\n]|\d+>|$)))/g;
1440
+ // A last flag that takes the program (`-c`, `-e`) or a module (`-m`) as its value: the program is
1441
+ // not on stdin, and in the masked view the quoted value is blank, so it reads as a bare interpreter.
1442
+ const PROGRAM_FLAG_RE = /\s(?:-[cemEp]|--eval|--print)$/;
1443
+ // `stdinBodies`' pre-test: the two walks it needs (a quote mask, a heredoc scan) cost more than the
1444
+ // rest of the command's detection put together. A name alone is not rare enough — `node` is in every
1445
+ // `node_modules` path — but every body this reader finds is a heredoc, so a command with no `<<` has
1446
+ // none. Not the /g/ pattern above, whose `lastIndex` `matchAll` inherits.
1447
+ const INTERPRETER_NAME_RE = /\b(?:python|ruby|perl|node)/;
1448
+ // Where an interpreter hands a string to a shell. `os.popen` is `os.system` with a pipe, and
1449
+ // `system` alone is Ruby's and Perl's spelling of it; `subprocess.*` and `child_process.*` are the
1450
+ // whole module, since every entry point takes the same argv. A `node -` body usually reaches the
1451
+ // module through `require`, and a named import strips the qualifier entirely, so the spellings that
1452
+ // reach the same call are here too — the sync ones are Node's own names and appear nowhere else,
1453
+ // while bare `exec`/`spawn` also name a database client, and those keep their qualifier.
1454
+ const SHELL_OUT_CALL_RE = /\b(?:os\s*\.\s*(?:system|popen)|subprocess\s*\.\s*[A-Za-z_]\w*|child_process\s*\.\s*\w+|childProcess\s*\.\s*\w+|require\s*\(\s*['"]child_process['"]\s*\)\s*\.\s*\w+|execSync|execFileSync|spawnSync|system)\s*\(\s*/g;
1455
+ // The shell command a call hands over: a plain literal (`os.system("…")`), an `f`/`r`/`b`-prefixed
1456
+ // or triple-quoted one, or an argv — a list (`subprocess.run(["git", "push", "--force"])`), a
1457
+ // program followed by its list (`execFileSync("git", ["push"])`, `spawn`), or a program followed by
1458
+ // its words (Ruby's and Perl's `system("git", "push")`). An argv is joined back into the command it
1459
+ // spells, each element quoted, so `["sh", "-c", "pkill node"]` keeps its `-c` body one word. A
1460
+ // variable, a `.format` template or a concatenation is not text this file can read, and guessing at
1461
+ // one would put words in the command that the shell never sees; an argv stops at its first one.
1462
+ function callArgument(text, from) {
1463
+ let at = skipSpace(text, from);
1464
+ const parts = [];
1465
+ let argv = false;
1466
+ const readList = () => {
1467
+ argv = true;
1468
+ at++;
1469
+ for (;;) {
1470
+ const lit = readLiteral(text, skipSpace(text, at));
1471
+ if (!lit)
1472
+ return false;
1473
+ parts.push(lit.value);
1474
+ at = skipSpace(text, lit.end);
1475
+ if (text[at] !== ',')
1476
+ return text[at] === ']' || text[at] === ')';
1477
+ at++;
1478
+ }
1479
+ };
1480
+ if (text[at] === '[' || text[at] === '(') {
1481
+ readList();
1482
+ }
1483
+ else {
1484
+ const lit = readLiteral(text, at);
1485
+ if (!lit)
1486
+ return undefined;
1487
+ parts.push(lit.value);
1488
+ at = skipSpace(text, lit.end);
1489
+ // Further arguments are the program's words only while they are literals or a closed list.
1490
+ while (text[at] === ',') {
1491
+ at = skipSpace(text, at + 1);
1492
+ if (text[at] === '[') {
1493
+ readList();
1494
+ break;
1495
+ }
1496
+ const next = readLiteral(text, at);
1497
+ if (!next)
1498
+ break;
1499
+ argv = true;
1500
+ parts.push(next.value);
1501
+ at = skipSpace(text, next.end);
1502
+ }
1503
+ }
1504
+ if (!parts.length)
1505
+ return undefined;
1506
+ if (!argv)
1507
+ return parts[0] || undefined;
1508
+ // A shell's `-c` element IS the command, and a call argument is read one level deep, where the
1509
+ // `-c` reader does not run — so it is handed over unwrapped.
1510
+ if (parts.length >= 3 && SHELL_ARGV0_RE.test(parts[0]) && /^-\w*c$/.test(parts[1]))
1511
+ return parts[2];
1512
+ return parts.map(shellQuote).join(' ');
1513
+ }
1514
+ const SHELL_ARGV0_RE = /(?:^|\/)(?:ba|z|da|k)?sh$/;
1515
+ function skipSpace(text, at) {
1516
+ while (at < text.length && /\s/.test(text[at]))
1517
+ at++;
1518
+ return at;
1519
+ }
1520
+ // One string literal at `at`, with the index past its closing quote. A triple quote opens a
1521
+ // Python block string, which a single `"` would read as an empty literal followed by text.
1522
+ function readLiteral(text, at) {
1523
+ const m = /^[A-Za-z]{0,2}("""|'''|['"`])/.exec(text.slice(at));
1524
+ if (!m)
1525
+ return undefined;
1526
+ const quote = m[1];
1527
+ const start = at + m[0].length;
1528
+ let i = start;
1529
+ for (; i < text.length; i++) {
1530
+ if (text[i] === '\\')
1531
+ i++;
1532
+ else if (text.startsWith(quote, i))
1533
+ break;
1534
+ }
1535
+ if (i >= text.length)
1536
+ return undefined;
1537
+ // A raw literal (`r"…"`, `rb"…"`) keeps its backslashes: `\n` there is two characters, not a
1538
+ // line break, and reading it as one would label a second command the shell never runs.
1539
+ const raw = /r/i.test(m[0].slice(0, -quote.length));
1540
+ const body = text.slice(start, i);
1541
+ return { value: raw ? body : unescapeLiteral(body), end: i + quote.length };
1542
+ }
1543
+ // An argv element as the one shell word it was: a bare word stays bare, anything else is quoted.
1544
+ function shellQuote(word) {
1545
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
1546
+ }
1547
+ // The escapes that change the command's SHAPE, so an argument spelled on one source line reads as
1548
+ // the two commands the shell will run: `os.system("curl x\npkill y")` is a `pkill` line. Everything
1549
+ // else is left alone — `\d` in a regex in the same string is not this file's business.
1550
+ function unescapeLiteral(s) {
1551
+ return s.replace(/\\(?:([nrt])|(['"\\`]))/g, (_m, esc, ch) => esc === 'n' ? '\n' : esc === 'r' ? '\r' : esc === 't' ? '\t' : ch);
1552
+ }
1553
+ // The commands a body hands to a shell, capped like the nested bodies themselves: a body with more
1554
+ // call sites than that is a script, and past a handful the labels say the same thing.
1555
+ function shellOutStrings(body) {
1556
+ const out = [];
1557
+ for (const m of body.matchAll(SHELL_OUT_CALL_RE)) {
1558
+ if (out.length >= MAX_NESTED_BODIES)
1559
+ break;
1560
+ const arg = callArgument(body, m.index + m[0].length);
1561
+ if (arg)
1562
+ out.push(arg);
1563
+ }
1564
+ return out;
1565
+ }
1566
+ // Whether the newline at `nl` is escaped by an odd run of backslashes before it.
1567
+ function continues(command, nl) {
1568
+ if (nl <= 0 || command[nl] !== '\n')
1569
+ return false;
1570
+ let n = 0;
1571
+ while (nl - 1 - n >= 0 && command[nl - 1 - n] === '\\')
1572
+ n++;
1573
+ return n % 2 === 1;
1574
+ }
1575
+ // A `&` that ends a command, not one inside a redirect (`2>&1`, `&>f`, `<&3`).
1576
+ function isCommandAmpersand(view, i) {
1577
+ return view[i] === '&' && view[i - 1] !== '>' && view[i - 1] !== '<' && view[i + 1] !== '>';
1578
+ }
1579
+ // Where the pipeline holding `at` begins on its line: past the last `;`, `&`, `||` or `(` before it.
1580
+ function pipelineStart(view, lineStart, at) {
1581
+ for (let i = at - 1; i >= lineStart; i--) {
1582
+ const c = view[i];
1583
+ if (c === ';' || c === '(' || isCommandAmpersand(view, i))
1584
+ return i + 1;
1585
+ if (c === '|' && view[i - 1] === '|')
1586
+ return i + 1;
1587
+ }
1588
+ return lineStart;
1589
+ }
1590
+ // Where the command starting before `from` ends on its line: the first `;`, `&`, `|` or `)`.
1591
+ function commandEnd(view, from, lineEnd) {
1592
+ for (let i = from; i < lineEnd; i++) {
1593
+ const c = view[i];
1594
+ if (c === ';' || c === '|' || c === ')' || isCommandAmpersand(view, i))
1595
+ return i;
1596
+ }
1597
+ return lineEnd;
1598
+ }
1599
+ // The stdin bodies of the interpreters above. Failures here go the same way as everywhere else in the
1600
+ // nested-body readers: a body that cannot be found costs nothing extra, and one that cannot be
1601
+ // bounded (an unreadable lexer) over-reports.
1602
+ function stdinBodies(command) {
1603
+ if (!command.includes('<<') || !INTERPRETER_NAME_RE.test(command))
1604
+ return [];
1605
+ const found = [];
1606
+ // A `python3 -` inside a quoted argument runs no interpreter: it is another command's text.
1607
+ const view = maskQuoted(command);
1608
+ const scan = scanHeredocs(command);
1609
+ for (const m of view.matchAll(INTERPRETER_STDIN_RE)) {
1610
+ if (found.length >= MAX_NESTED_BODIES)
1611
+ break;
1612
+ if (!m[3] && PROGRAM_FLAG_RE.test(m[2]))
1613
+ continue;
1614
+ const at = m.index;
1615
+ const context = m[3] ? `${m[1]} -` : m[1];
1616
+ const lineStart = command.lastIndexOf('\n', at - 1) + 1;
1617
+ const nl = command.indexOf('\n', at);
1618
+ // A line continued by a backslash puts the body after the NEXT newline (or the pipeline before
1619
+ // the previous one), where the walk below cannot follow it. Like an unreadable lexer, that
1620
+ // reads the whole command as the body: it can only add labels.
1621
+ if (scan.uncertain || continues(command, nl) || continues(command, lineStart - 1)) {
1622
+ if (command.includes('<<'))
1623
+ found.push({ context, body: command });
1624
+ continue;
1625
+ }
1626
+ const lineEnd = nl === -1 ? command.length : nl;
1627
+ // The body lands on the stdin of the command its operator sits on, and the interpreter reads it
1628
+ // when that command is its own or one the pipe hands it on from (`cat <<'PY' | python3 -`). So
1629
+ // every heredoc from the start of the interpreter's pipeline to the end of its own command
1630
+ // counts, and none behind a `;` or `&&`, which is another command's input.
1631
+ const from = pipelineStart(view, lineStart, at);
1632
+ const to = commandEnd(view, at + m[0].length, lineEnd);
1633
+ for (const h of scan.heredocs) {
1634
+ if (h.opAt < from || h.opAt >= to)
1635
+ continue;
1636
+ if (found.length >= MAX_NESTED_BODIES)
1637
+ break;
1638
+ found.push({ context, body: command.slice(h.bodyStart, h.bodyEnd) });
1639
+ }
1640
+ }
1641
+ return found;
1642
+ }
1450
1643
  // Two checks read the working tree, because the command text alone cannot answer them: whether
1451
1644
  // `npx vitest` fetches anything, and whether `git checkout App.tsx` names a branch or a file.
1452
1645
  // Without a cwd both fall back to the text — npx flags, checkout stays with the regexes above.
@@ -1609,17 +1802,47 @@ function detectAtDepth(rawCommand, depth, cwd) {
1609
1802
  for (const { context, body, interp } of nestedBodies(command)) {
1610
1803
  const inner = detectAtDepth(body, 1, cwd);
1611
1804
  if (interp) {
1612
- for (const { re, label } of INTERPRETER_BODY_PATTERNS) {
1613
- if (re.test(body) && !inner.includes(label))
1805
+ for (const label of interpreterBodyLabels(body, cwd)) {
1806
+ if (!inner.includes(label))
1614
1807
  inner.push(label);
1615
1808
  }
1616
1809
  }
1617
- for (const label of inner) {
1618
- const prefixed = `via ${context}: ${label}`;
1619
- if (!hits.includes(label) && !hits.includes(prefixed))
1620
- hits.push(prefixed);
1621
- }
1810
+ addNested(hits, context, inner);
1811
+ }
1812
+ // A program pasted onto an interpreter's stdin is the one nested body the outer pass refuses to
1813
+ // read (#699), so it is read here instead — and ONLY through `interpreterBodyLabels`: the body
1814
+ // itself is never handed to `detectAtDepth`, which is what keeps a `;` in one of its string
1815
+ // literals from splitting a segment into a verb.
1816
+ for (const { context, body } of stdinBodies(command)) {
1817
+ addNested(hits, context, interpreterBodyLabels(body, cwd));
1622
1818
  }
1623
1819
  }
1624
1820
  return hits;
1625
1821
  }
1822
+ // What an interpreter's own body says on top of what its text says as a command: the stdlib patterns
1823
+ // above, and the commands the body actually hands to a shell. Both are read off the body text alone,
1824
+ // with no dependence on where its quote spans are — which is what makes this the one reading that is
1825
+ // safe on a PASTED body, where the shell has not quote-parsed anything and a `;` in a string literal
1826
+ // is not marked as data (#699).
1827
+ function interpreterBodyLabels(body, cwd) {
1828
+ const labels = [];
1829
+ for (const { re, label } of INTERPRETER_BODY_PATTERNS) {
1830
+ if (re.test(body))
1831
+ labels.push(label);
1832
+ }
1833
+ for (const call of shellOutStrings(body)) {
1834
+ for (const label of detectAtDepth(call, 1, cwd)) {
1835
+ if (!labels.includes(label))
1836
+ labels.push(label);
1837
+ }
1838
+ }
1839
+ return labels;
1840
+ }
1841
+ // The prefixed form of every label a nested body earned.
1842
+ function addNested(hits, context, inner) {
1843
+ for (const label of inner) {
1844
+ const prefixed = `via ${context}: ${label}`;
1845
+ if (!hits.includes(label) && !hits.includes(prefixed))
1846
+ hits.push(prefixed);
1847
+ }
1848
+ }
@@ -1,4 +1,5 @@
1
1
  import { scanQuotes } from './_heredoc.js';
2
+ import { skipCarrier } from './_carriers.js';
2
3
  // Shell commands that only READ — asked as TWO questions, because the two callers pull in opposite
3
4
  // directions and collapsing them costs whichever one is on the losing side.
4
5
  //
@@ -373,21 +374,21 @@ function readAnsiC(word, start, emit) {
373
374
  // (#621) — while `_danger.ts`, which matches a command's own patterns through an unlisted carrier
374
375
  // (`timeout 5 rm` still gates), saw the gh read and did not flag it. (`xargs` is the other carrier,
375
376
  // read in `_sandbox.ts`'s verb reader, where the command it runs is known to be the argument.)
376
- // Flags and the DURATION operand are skipped; `-s`/`-k` take the next word as their value,
377
- // `--signal=KILL` does not.
378
- const CARRIER_VALUE_FLAGS = new Set(['-s', '--signal', '-k', '--kill-after']);
377
+ //
378
+ // Which carriers are read through, and what their own options and operands are, is
379
+ // `_carriers.ts`'s table (#756): `_danger.ts`'s verb strip walks the same entries, and a carrier
380
+ // only one of the two knew was a fetch left ungated on one side and a refused read on the other.
381
+ // Only the TRANSPARENT entry of the table is skipped here — `nice` and `timeout` bound or
382
+ // deprioritize the command, while `sudo`/`env`/`nohup` change what running it means — and the walk
383
+ // loops, so `timeout 30 nice gh pr view 1` is still the `gh` read.
379
384
  export function dropCarriers(wordList) {
380
385
  let i = 0;
381
- while (wordList[i] === 'timeout') {
382
- i++;
383
- while (wordList[i]?.startsWith('-')) {
384
- if (CARRIER_VALUE_FLAGS.has(wordList[i]))
385
- i++;
386
- i++;
387
- }
388
- i++; // the DURATION operand
386
+ for (;;) {
387
+ const next = skipCarrier(wordList, i, true);
388
+ if (next < 0)
389
+ return wordList.slice(i);
390
+ i = next;
389
391
  }
390
- return wordList.slice(i);
391
392
  }
392
393
  // Plan mode's sed: a line-range or pattern-range print (`sed -n '120,180p' f`,
393
394
  // `sed -n '/## A/,/## B/p' f`) — the read models reach for most, refused before at a round's cost.
@@ -220,8 +220,9 @@ const GIT_GLOBAL_VALUE_FLAGS = new Set([
220
220
  ]);
221
221
  // Subcommand options that run a program the model wrote. `--template` plants hooks that run at
222
222
  // checkout and clone's `--config` is `-c` again, so both belong here although neither is spelled
223
- // as a command. Long names apply to every subcommand: none has a harmless option abbreviated by
224
- // these, and `push --exec`/`archive --exec` mean the same as `rebase --exec`.
223
+ // as a command. Long names apply to every subcommand: `push --exec`/`archive --exec` mean the same
224
+ // as `rebase --exec`, and an abbreviation of one of these is refused on any subcommand — a false
225
+ // deny where that subcommand's own `--e`/`--t`/`--u` means something else, never a hole.
225
226
  const GIT_PROGRAM_LONG_FLAGS = [
226
227
  'upload-pack',
227
228
  'receive-pack',
@@ -240,8 +241,14 @@ const GIT_PROGRAM_SHORT_FLAGS = {
240
241
  rebase: { run: 'x', value: 'sXxC' },
241
242
  difftool: { run: 'x', value: 'tx' },
242
243
  };
243
- // Whole subcommands (or a subcommand's first operand) whose job is running a command.
244
- const GIT_PROGRAM_SUBCOMMANDS = new Set(['filter-branch', 'submodule foreach', 'bisect run']);
244
+ // Whole subcommands (or a subcommand's first operand) that name a program to run: `send-email`
245
+ // does so five ways (four `--*-cmd` options, and `--smtp-server=/path`), so it goes by subcommand.
246
+ const GIT_PROGRAM_SUBCOMMANDS = new Set([
247
+ 'filter-branch',
248
+ 'submodule foreach',
249
+ 'bisect run',
250
+ 'send-email',
251
+ ]);
245
252
  function gitSubcommandRunsProgram(sub, args) {
246
253
  if (GIT_PROGRAM_SUBCOMMANDS.has(sub))
247
254
  return true;
@@ -254,7 +261,8 @@ function gitSubcommandRunsProgram(sub, args) {
254
261
  return false;
255
262
  if (a.startsWith('--')) {
256
263
  const name = a.slice(2).split('=')[0];
257
- if (name.length >= 2 && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
264
+ // Any prefix, down to one letter (`--u=cmd` ran); `--=x` has an empty name, which is none.
265
+ if (name && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
258
266
  return true;
259
267
  }
260
268
  else if (short && a.startsWith('-')) {