@draht/coding-agent 2026.10.16 → 2026.10.19-1

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 (173) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
  6. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  7. package/dist/bundle/chunks/{chunk-OWGSPJPZ.js → chunk-3DQNSI5W.js} +5 -5
  8. package/dist/bundle/chunks/{chunk-JFDPOIUH.js → chunk-4COXSQRQ.js} +1 -1
  9. package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
  10. package/dist/bundle/chunks/{chunk-TJ3AW62W.js → chunk-CQF6U56X.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
  12. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
  13. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  14. package/dist/bundle/chunks/{chunk-6APPDDHH.js → chunk-I2SOJ4JN.js} +3 -3
  15. package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
  16. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  17. package/dist/bundle/chunks/{chunk-MIUVNYYW.js → chunk-QPCP4VHF.js} +123 -111
  18. package/dist/bundle/chunks/{chunk-KU5HAKZL.js → chunk-QVTLBSTH.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-2VAF4XJI.js → chunk-U6LDZZGM.js} +10 -10
  20. package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
  21. package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
  22. package/dist/bundle/chunks/{chunk-NHTOADU6.js → chunk-X3YFUSCK.js} +1 -1
  23. package/dist/bundle/chunks/{cli-U7Y4VNNI.js → cli-VCHSHNKT.js} +1 -1
  24. package/dist/bundle/chunks/{execute-ZWB4PIQQ.js → execute-AGEWJLIO.js} +1 -1
  25. package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
  26. package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
  27. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  28. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  29. package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
  30. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  31. package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
  32. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
  33. package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
  34. package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
  35. package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
  36. package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
  37. package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
  38. package/dist/bundle/chunks/{runtime-PXJK4L7Y.js → runtime-2B56SZM6.js} +1 -1
  39. package/dist/bundle/chunks/{runtime-363BOYEO.js → runtime-TJ3EAMJK.js} +1 -1
  40. package/dist/bundle/chunks/{settings-manager-GEOZJXFQ.js → settings-manager-HC5RR36T.js} +1 -1
  41. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  42. package/dist/bundle/chunks/{virtual-modules-BEJ4ZJ3D.js → virtual-modules-XT4MP2GI.js} +1 -1
  43. package/dist/bundle/cli-runtime.js +1 -1
  44. package/dist/bundle/index.js +1 -1
  45. package/dist/bundle/rpc-entry.js +1 -1
  46. package/dist/core/agent-session.d.ts.map +1 -1
  47. package/dist/core/agent-session.js +4 -0
  48. package/dist/core/agent-session.js.map +1 -1
  49. package/dist/core/builtins/duet.d.ts +7 -1
  50. package/dist/core/builtins/duet.d.ts.map +1 -1
  51. package/dist/core/builtins/duet.js +83 -14
  52. package/dist/core/builtins/duet.js.map +1 -1
  53. package/dist/core/builtins/polyphase.d.ts.map +1 -1
  54. package/dist/core/builtins/polyphase.js +21 -2
  55. package/dist/core/builtins/polyphase.js.map +1 -1
  56. package/dist/core/builtins/subagent.d.ts +59 -2
  57. package/dist/core/builtins/subagent.d.ts.map +1 -1
  58. package/dist/core/builtins/subagent.js +258 -62
  59. package/dist/core/builtins/subagent.js.map +1 -1
  60. package/dist/core/extensions/loader.d.ts.map +1 -1
  61. package/dist/core/extensions/loader.js +23 -0
  62. package/dist/core/extensions/loader.js.map +1 -1
  63. package/dist/core/extensions/runner.d.ts.map +1 -1
  64. package/dist/core/extensions/runner.js +2 -0
  65. package/dist/core/extensions/runner.js.map +1 -1
  66. package/dist/core/extensions/types.d.ts +12 -0
  67. package/dist/core/extensions/types.d.ts.map +1 -1
  68. package/dist/core/extensions/types.js.map +1 -1
  69. package/dist/core/keybindings.d.ts +5 -0
  70. package/dist/core/keybindings.d.ts.map +1 -1
  71. package/dist/core/keybindings.js +4 -0
  72. package/dist/core/keybindings.js.map +1 -1
  73. package/dist/core/multi-agent/permission-gate.d.ts +18 -6
  74. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  75. package/dist/core/multi-agent/permission-gate.js +867 -59
  76. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  77. package/dist/core/polyphase/approval.d.ts +6 -2
  78. package/dist/core/polyphase/approval.d.ts.map +1 -1
  79. package/dist/core/polyphase/approval.js +23 -35
  80. package/dist/core/polyphase/approval.js.map +1 -1
  81. package/dist/core/polyphase/child-events.js +1 -1
  82. package/dist/core/polyphase/child-events.js.map +1 -1
  83. package/dist/core/polyphase/child-process.d.ts.map +1 -1
  84. package/dist/core/polyphase/child-process.js +65 -7
  85. package/dist/core/polyphase/child-process.js.map +1 -1
  86. package/dist/core/polyphase/commands.d.ts.map +1 -1
  87. package/dist/core/polyphase/commands.js +46 -5
  88. package/dist/core/polyphase/commands.js.map +1 -1
  89. package/dist/core/polyphase/details.d.ts.map +1 -1
  90. package/dist/core/polyphase/details.js +5 -0
  91. package/dist/core/polyphase/details.js.map +1 -1
  92. package/dist/core/polyphase/permission-bridge.d.ts +128 -0
  93. package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
  94. package/dist/core/polyphase/permission-bridge.js +357 -0
  95. package/dist/core/polyphase/permission-bridge.js.map +1 -0
  96. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  97. package/dist/core/polyphase/render/run-block.js +13 -4
  98. package/dist/core/polyphase/render/run-block.js.map +1 -1
  99. package/dist/core/polyphase/render/snapshot.d.ts +4 -0
  100. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  101. package/dist/core/polyphase/render/snapshot.js +4 -0
  102. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  103. package/dist/core/polyphase/result-text.d.ts.map +1 -1
  104. package/dist/core/polyphase/result-text.js +23 -3
  105. package/dist/core/polyphase/result-text.js.map +1 -1
  106. package/dist/core/polyphase/session.d.ts +15 -1
  107. package/dist/core/polyphase/session.d.ts.map +1 -1
  108. package/dist/core/polyphase/session.js +36 -1
  109. package/dist/core/polyphase/session.js.map +1 -1
  110. package/dist/core/polyphase/settings.d.ts +1 -0
  111. package/dist/core/polyphase/settings.d.ts.map +1 -1
  112. package/dist/core/polyphase/settings.js +1 -1
  113. package/dist/core/polyphase/settings.js.map +1 -1
  114. package/dist/core/polyphase/store.d.ts +18 -0
  115. package/dist/core/polyphase/store.d.ts.map +1 -1
  116. package/dist/core/polyphase/store.js +38 -0
  117. package/dist/core/polyphase/store.js.map +1 -1
  118. package/dist/core/polyphase/types.d.ts +60 -3
  119. package/dist/core/polyphase/types.d.ts.map +1 -1
  120. package/dist/core/polyphase/types.js.map +1 -1
  121. package/dist/core/polyphase/ui/inspector.js +1 -1
  122. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  123. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
  124. package/dist/core/polyphase/workflow/agent-host.js +17 -3
  125. package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
  126. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
  127. package/dist/core/polyphase/workflow/guidance.js +16 -5
  128. package/dist/core/polyphase/workflow/guidance.js.map +1 -1
  129. package/dist/core/polyphase/workflow/launch.d.ts +2 -1
  130. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
  131. package/dist/core/polyphase/workflow/launch.js +22 -3
  132. package/dist/core/polyphase/workflow/launch.js.map +1 -1
  133. package/dist/core/polyphase/workflow/limits.d.ts +80 -0
  134. package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
  135. package/dist/core/polyphase/workflow/limits.js +234 -0
  136. package/dist/core/polyphase/workflow/limits.js.map +1 -0
  137. package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
  138. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
  139. package/dist/core/polyphase/workflow/runtime.js.map +1 -1
  140. package/dist/core/polyphase/workflow/tool.d.ts +1 -0
  141. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
  142. package/dist/core/polyphase/workflow/tool.js +23 -2
  143. package/dist/core/polyphase/workflow/tool.js.map +1 -1
  144. package/dist/core/usage-totals.d.ts +5 -0
  145. package/dist/core/usage-totals.d.ts.map +1 -1
  146. package/dist/core/usage-totals.js +16 -0
  147. package/dist/core/usage-totals.js.map +1 -1
  148. package/dist/main.d.ts.map +1 -1
  149. package/dist/main.js +4 -0
  150. package/dist/main.js.map +1 -1
  151. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  152. package/dist/modes/interactive/interactive-mode.js +2 -0
  153. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  154. package/dist/utils/shell.d.ts.map +1 -1
  155. package/dist/utils/shell.js +3 -0
  156. package/dist/utils/shell.js.map +1 -1
  157. package/docs/duet.md +1 -1
  158. package/docs/environment-variables.md +3 -1
  159. package/docs/extensions.md +2 -1
  160. package/docs/keybindings.md +1 -0
  161. package/docs/polyphase.md +97 -33
  162. package/docs/settings.md +2 -2
  163. package/package.json +10 -10
  164. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  165. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
  166. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  167. package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
  168. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  169. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  170. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  171. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  172. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
  173. /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
@@ -29,15 +29,16 @@
29
29
  *
30
30
  * Rules are evaluated top-to-bottom; the first matching rule wins.
31
31
  *
32
- * On top of the rules sits a session-level `PermissionMode` (`default` /
32
+ * On top of the rules sits a session-level `PermissionMode` (`ask` /
33
33
  * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and
34
34
  * `approve` outcomes are handled — `deny` rules are never relaxed.
35
35
  *
36
36
  * `pattern` matching against bash commands is textual (no real shell
37
37
  * parser), so `deny` and `allow`/`approve` patterns are matched with
38
38
  * deliberately asymmetric strategies to stay fail-safe: `deny` scans every
39
- * chained/wrapped/unwrapped piece of the command it can find (paranoid,
40
- * over-matching is safe), while `allow`/`approve` require an exact
39
+ * chained/wrapped/unwrapped piece of the command it can find, plus every
40
+ * command a shell-aware read finds the shell runs (`collectDenyCandidates`;
41
+ * paranoid, over-matching is safe), while `allow`/`approve` require an exact
41
42
  * chain-shape match and reject anything containing `$(...)`, backticks, or
42
43
  * redirection (strict, under-matching just falls through to the default
43
44
  * decision instead of silently authorizing more than intended). See the
@@ -50,10 +51,23 @@ import { isAbsolute, join, relative, resolve, sep } from "node:path";
50
51
  import { minimatch } from "minimatch";
51
52
  import { parse } from "yaml";
52
53
  import { CONFIG_DIR_NAME, getAgentDir } from "../../config.js";
53
- export const PERMISSION_MODES = ["default", "auto", "yolo"];
54
+ import { resolveToCwd } from "../tools/path-utils.js";
55
+ /** Strictest first: `stricterPermissionMode` relies on this order. */
56
+ export const PERMISSION_MODES = ["ask", "auto", "yolo"];
57
+ /**
58
+ * The mode a session starts in when `DRAHT_PERMISSION_MODE` names none. A `PermissionGate`
59
+ * constructed without a mode still uses `ask`, the strictest, so a caller that forgets to
60
+ * pass the session's mode never gets a laxer gate than the session has. Never `yolo`: `/yolo`
61
+ * switches back to this mode when nothing else was chosen.
62
+ */
63
+ export const DEFAULT_SESSION_PERMISSION_MODE = "auto";
54
64
  export function isPermissionMode(value) {
55
65
  return typeof value === "string" && PERMISSION_MODES.includes(value);
56
66
  }
67
+ /** Whichever of the two modes asks more. */
68
+ export function stricterPermissionMode(a, b) {
69
+ return PERMISSION_MODES.indexOf(a) <= PERMISSION_MODES.indexOf(b) ? a : b;
70
+ }
57
71
  const VALID_ACTIONS = ["deny", "allow", "approve"];
58
72
  const RULES_FILE_NAME = "permissions.yml";
59
73
  const PATH_SCOPED_TOOLS = new Set(["read", "write", "edit"]);
@@ -63,13 +77,20 @@ const READ_ONLY_PATH_TOOLS = new Set(["grep", "find", "ls"]);
63
77
  * Tools that are safe to run without confirmation because the call itself
64
78
  * only delegates: spawned child processes run this same gate over every tool
65
79
  * call they actually make. Explicit rules can still `deny`/`approve` these.
66
- * Duet delegation is deliberately not included because it fans out paid model
67
- * requests; unmatched duet batches require explicit approval.
80
+ * Workflows and duet batches are deliberately not included because they fan
81
+ * out paid model requests; see `AUTO_ALLOWED_DELEGATION_TOOLS`.
68
82
  *
69
83
  * `polyphase_result` is also allowed by default: it returns a value to the parent workflow; no
70
84
  * side effects; children have no UI to approve it.
71
85
  */
72
86
  const DEFAULT_ALLOWED_TOOLS = new Set(["subagent", "polyphase_result"]);
87
+ /**
88
+ * Delegating tools that fan out paid model requests: a workflow run and a duet batch. Like
89
+ * `DEFAULT_ALLOWED_TOOLS`, they only start child processes that run this same gate over every
90
+ * tool call they make, so `auto` mode starts them without asking; `ask` mode asks first,
91
+ * for the spend. Explicit rules can still `deny`/`approve` these.
92
+ */
93
+ const AUTO_ALLOWED_DELEGATION_TOOLS = new Set(["workflow", "duet_delegate"]);
73
94
  function isPermissionAction(value) {
74
95
  return typeof value === "string" && VALID_ACTIONS.includes(value);
75
96
  }
@@ -226,6 +247,24 @@ const PASSTHROUGH_PREFIXES = new Set([
226
247
  ]);
227
248
  /** Shells whose `-c <command>` argument is itself a full command line to unwrap and re-check. */
228
249
  const SHELL_C_WRAPPERS = new Set(["bash", "sh", "zsh", "ksh", "dash", "fish"]);
250
+ /**
251
+ * Every shell the run checks know: the `-c` wrappers and other shells that equally run a script,
252
+ * stdin, or `-c`. The deny scan keeps to `SHELL_C_WRAPPERS`.
253
+ */
254
+ const SCRIPT_SHELLS = new Set([
255
+ ...SHELL_C_WRAPPERS,
256
+ "ash",
257
+ "mksh",
258
+ "pdksh",
259
+ "oksh",
260
+ "yash",
261
+ "posh",
262
+ "csh",
263
+ "tcsh",
264
+ "elvish",
265
+ "nu",
266
+ "xonsh",
267
+ ]);
229
268
  /**
230
269
  * Non-POSIX shells whose command-line argument is itself a full command line
231
270
  * to unwrap and re-check. Catches bash wrapping another shell, e.g.
@@ -239,6 +278,10 @@ function isOtherShellWrapperName(basename) {
239
278
  }
240
279
  /** Constructs that make a command dynamic/opaque enough that allow/approve patterns must never match it. */
241
280
  const DANGEROUS_CONSTRUCT_RE = /\$\(|`|<|>/;
281
+ /** `true` for the operators that feed one command's output into the next: `|` and `|&`. */
282
+ function isPipeOperator(operator) {
283
+ return operator === "|" || operator === "|&";
284
+ }
242
285
  /** Quote-aware split of a command string on top-level chain operators (`;`, `&&`, `||`, `|`, `&`, newlines). */
243
286
  function splitChain(command) {
244
287
  const segments = [];
@@ -616,7 +659,7 @@ function feedsBareShellViaHereDocOrString(text) {
616
659
  /** `true` when any `|`-joined segment pipes into a known shell with no `-c` (`echo ... | bash`). */
617
660
  function pipedIntoBareShell(segments) {
618
661
  return segments.some((seg) => {
619
- if (seg.operator !== "|")
662
+ if (!isPipeOperator(seg.operator))
620
663
  return false;
621
664
  const trimmed = seg.text.trim();
622
665
  const tokens = tokenizeShellWords(trimmed);
@@ -629,15 +672,291 @@ function pipedIntoBareShell(segments) {
629
672
  /**
630
673
  * `true` when `command` feeds a bare shell interpreter (`bash`, `sh`, `zsh`,
631
674
  * `dash`, `ksh`, `fish`) via a pipe, here-string, or heredoc, with no `-c`
632
- * flag. The deny scan can extract and check the piped/here-doc text (see
633
- * `scanDenyCandidates`), but can't prove the absence of danger the way a
634
- * plain unwrapped command can — so auto mode must never silently allow it.
675
+ * flag — in the command itself or in any command line it runs (see
676
+ * `scanExecutedCode`). The deny scan can extract and check the piped/here-doc
677
+ * text (see `scanDenyCandidates`), but can't prove the absence of danger the
678
+ * way a plain unwrapped command can — so auto mode must never silently allow it.
635
679
  */
636
680
  function commandFeedsBareShellWithoutDashC(command) {
637
- const segments = splitChain(command);
638
- if (pipedIntoBareShell(segments))
681
+ const feedsShell = (text) => {
682
+ const segments = splitChain(text);
683
+ return pipedIntoBareShell(segments) || segments.some((seg) => feedsBareShellViaHereDocOrString(seg.text));
684
+ };
685
+ if (feedsShell(command))
639
686
  return true;
640
- return segments.some((seg) => feedsBareShellViaHereDocOrString(seg.text));
687
+ const executed = scanExecutedCode(command);
688
+ return (executed.truncated ||
689
+ pipedIntoBareShell(executed.segments) ||
690
+ executed.segments.some((seg) => feedsBareShellViaHereDocOrString(seg.text)));
691
+ }
692
+ /** Interpreters: each runs a script operand, inline code (`-c`, `-e`), or the program on stdin. */
693
+ const INTERPRETER_RE = /^(python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|ruby|perl|php)$/;
694
+ /** The interpreter family `name` belongs to, the key of `INTERPRETER_ARG_FLAGS` and `INTERPRETER_INLINE_FLAGS`. */
695
+ function interpreterFamily(name) {
696
+ if (name.startsWith("python") || name.startsWith("pypy"))
697
+ return "python";
698
+ return name === "nodejs" ? "node" : name;
699
+ }
700
+ /** Interpreter flags that take the next word as their own argument (`python3 -W ignore`, `node -r ./x`). */
701
+ const INTERPRETER_ARG_FLAGS = new Map([
702
+ ["python", new Set(["-W", "-X", "--check-hash-based-pycs"])],
703
+ [
704
+ "node",
705
+ new Set([
706
+ "-r",
707
+ "--require",
708
+ "--import",
709
+ "--loader",
710
+ "--experimental-loader",
711
+ "-C",
712
+ "--conditions",
713
+ "--input-type",
714
+ "--env-file",
715
+ "--title",
716
+ ]),
717
+ ],
718
+ ["bun", new Set(["-r", "--require", "--preload", "--cwd", "--env-file", "--tsconfig-override"])],
719
+ ["deno", new Set(["--config", "--import-map", "--location", "--seed", "--v8-flags", "--env-file", "--cert"])],
720
+ ["ruby", new Set(["-I", "-r", "-C", "-E", "-F", "--encoding"])],
721
+ ["perl", new Set(["-I"])],
722
+ ["php", new Set(["-d", "-c", "-z"])],
723
+ ]);
724
+ /** Interpreter flags that give the program inline or as a module, so it is no script operand and not stdin. */
725
+ const INTERPRETER_INLINE_FLAGS = new Map([
726
+ ["python", new Set(["-c", "-m"])],
727
+ ["node", new Set(["-e", "--eval", "-p", "--print"])],
728
+ ["bun", new Set(["-e", "--eval", "-p", "--print"])],
729
+ ["ruby", new Set(["-e"])],
730
+ ["perl", new Set(["-e", "-E"])],
731
+ ["php", new Set(["-r"])],
732
+ ]);
733
+ /** Operands that name stdin itself. */
734
+ const STDIN_OPERANDS = new Set(["-", "/dev/stdin", "/dev/fd/0", "/proc/self/fd/0"]);
735
+ /** A descriptor other than stdin by path (`/dev/fd/3`): what a process substitution expands to. */
736
+ const DESCRIPTOR_PATH_RE = /^\/(?:dev\/fd|proc\/(?:self|\d+)\/fd)\/[1-9]\d*$/;
737
+ /** A redirection word (`<<EOF`, `<<<`, `>`, `2>&1`, `&>>log`), never a process substitution. */
738
+ const REDIRECTION_RE = /^\d*(?:<<<|<<-?|<>|<|&>>?|>>?|>&)(?!\()/;
739
+ /**
740
+ * `true` when `words` redirect stdin from a process substitution or another descriptor
741
+ * (`< <(...)`, `0</dev/fd/3`, `<&3`), or from a connection bash opens itself
742
+ * (`< /dev/tcp/host/port`), never from a file or stdin itself.
743
+ */
744
+ function stdinFromDescriptor(words) {
745
+ return words.some((word, i) => {
746
+ const redirection = word.match(/^0?<(?![<>(])(&?)(.*)$/);
747
+ if (!redirection)
748
+ return false;
749
+ const target = redirection[2] === "" ? (words[i + 1] ?? "") : redirection[2];
750
+ if (redirection[1] === "&")
751
+ return /^[1-9]\d*$/.test(target);
752
+ return target.startsWith("<(") || DESCRIPTOR_PATH_RE.test(target) || /^\/dev\/(?:tcp|udp)\//.test(target);
753
+ });
754
+ }
755
+ /**
756
+ * What can open a command without being its name: `{` and `!`, a subshell's `(`, `coproc`, the
757
+ * head of a loop that runs its body on the same line (`for x do`, `for ((...)) do`), the reserved
758
+ * words before a command (`if`, `then`, `do`, ...) and `builtin`, a function header (`f() {`,
759
+ * `function f {`), a case statement's head (`case $x in`), and a case pattern followed by its
760
+ * command (`start|stop) ...`, `"a b") ...`). A word and `)` followed by a redirection or nothing
761
+ * is the end of a subshell, not a case pattern: `(cd x && make) > log`.
762
+ */
763
+ const COMPOUND_OPENERS = [
764
+ /^\s*[{!](?=\s)/,
765
+ /^\s*\(+/,
766
+ /^\s*coproc\s+[A-Za-z_]\w*\s+\{(?=\s)/,
767
+ /^\s*(?:for|select)\s+[A-Za-z_]\w*\s+do(?=\s)/,
768
+ /^\s*for\s*\(\([\s\S]*?\)\)\s*do(?=\s)/,
769
+ /^\s*(?:if|then|else|elif|while|until|do|coproc|builtin)(?=\s)/,
770
+ /^\s*function\s+[^\s(){}]+(?:\s*\(\s*\))?(?:\s*\{(?=\s))?/,
771
+ /^\s*[A-Za-z_][\w.:-]*\s*\(\s*\)(?:\s*\{(?=\s))?/,
772
+ /^\s*case\s+\S+\s+in(?=\s|$)/,
773
+ /^\s*\(?(?:"[^"]*"|'[^']*'|\\.|[^\s()|;&<>"'\\])+(?:\s*\|\s*(?:"[^"]*"|'[^']*'|\\.|[^\s()|;&<>"'\\])+)*\)(?=\s+[^\s<>|&;)])/,
774
+ ];
775
+ /**
776
+ * `text` without the `)` that close a subshell around its command (`rm -rf ~)`,
777
+ * `bash) < <(...)`): every `)` outside quotes with no `(` of its own before it.
778
+ */
779
+ function stripUnbalancedClosers(text) {
780
+ let out = "";
781
+ let depth = 0;
782
+ let quote;
783
+ for (let i = 0; i < text.length; i++) {
784
+ const ch = text[i];
785
+ if (ch === "\\" && quote !== "'" && i + 1 < text.length) {
786
+ out += ch + text[i + 1];
787
+ i++;
788
+ continue;
789
+ }
790
+ if (quote !== undefined) {
791
+ if (ch === quote)
792
+ quote = undefined;
793
+ }
794
+ else if (ch === "'" || ch === '"') {
795
+ quote = ch;
796
+ }
797
+ else if (ch === "(") {
798
+ depth++;
799
+ }
800
+ else if (ch === ")") {
801
+ if (depth === 0)
802
+ continue;
803
+ depth--;
804
+ }
805
+ out += ch;
806
+ }
807
+ return out;
808
+ }
809
+ /**
810
+ * `text` without the compound-command syntax in front of its command (`COMPOUND_OPENERS`), and
811
+ * without the `)` that closes a subshell after it: `if x; then rm -rf ~; fi` runs `rm -rf ~`,
812
+ * `(rm -rf ~)` too.
813
+ */
814
+ function stripCompoundOpeners(text) {
815
+ let stripped = text;
816
+ for (let guard = 0; guard < 16; guard++) {
817
+ const opener = COMPOUND_OPENERS.find((re) => re.test(stripped));
818
+ if (opener === undefined)
819
+ break;
820
+ stripped = stripped.replace(opener, "");
821
+ }
822
+ return stripUnbalancedClosers(stripped);
823
+ }
824
+ /**
825
+ * `text` as the command it runs: compound-command syntax, leading assignments and passthrough
826
+ * wrappers (`env`, `nice`, `time`, ...) stripped in whatever order they come. `beforeWrappers`
827
+ * keeps the first wrapper, for `env -S`.
828
+ */
829
+ function unwrapCommand(text) {
830
+ let working = text;
831
+ let beforeWrappers;
832
+ for (let guard = 0; guard < 8; guard++) {
833
+ const opened = stripEnvAssignments(stripLeadingBackslashEscape(stripCompoundOpeners(working)));
834
+ beforeWrappers ??= opened;
835
+ const { stripped, changed } = stripPassthroughPrefix(opened);
836
+ const next = changed ? stripped : opened;
837
+ if (next === working)
838
+ break;
839
+ working = next;
840
+ }
841
+ return { working, beforeWrappers: beforeWrappers ?? working };
842
+ }
843
+ /** `text`'s words once `unwrapCommand` has stripped what runs it without being it. */
844
+ function unwrappedWords(text) {
845
+ return tokenizeShellWords(unwrapCommand(text).working.trim());
846
+ }
847
+ /**
848
+ * Where the shell, interpreter, `source` or `.` that `words` start with takes its program
849
+ * from: a script operand, inline code (`-c`, `-e`, `-m`; for a shell, with the command line its
850
+ * `-c` runs), or stdin (no operand, `-` and its spellings, or a shell given `-s`), noting whether
851
+ * stdin is redirected from a `<(...)` or another descriptor anywhere among the words. `undefined`
852
+ * when `words` start with anything else. Option arguments (`bash -euo pipefail`,
853
+ * `python3 -W ignore`) and redirections (`> out.txt`) are skipped, so neither passes for the script.
854
+ */
855
+ function programSource(words) {
856
+ const head = words[0];
857
+ if (head === undefined)
858
+ return undefined;
859
+ const name = basenameOfHeadToken(head);
860
+ const isShell = SCRIPT_SHELLS.has(name);
861
+ if (!isShell && !INTERPRETER_RE.test(name) && name !== "source" && name !== ".")
862
+ return undefined;
863
+ const family = interpreterFamily(name);
864
+ const argFlags = INTERPRETER_ARG_FLAGS.get(family);
865
+ const inlineFlags = INTERPRETER_INLINE_FLAGS.get(family);
866
+ const fromDescriptor = stdinFromDescriptor(words);
867
+ let readsStdin = false;
868
+ let inlineShell = false;
869
+ let optionsDone = false;
870
+ let subcommandSkipped = false;
871
+ for (let i = 1; i < words.length; i++) {
872
+ const word = words[i];
873
+ const redirection = word.match(REDIRECTION_RE);
874
+ if (redirection) {
875
+ if (redirection[0] === word)
876
+ i++;
877
+ continue;
878
+ }
879
+ if (!optionsDone) {
880
+ if (word === "--") {
881
+ optionsDone = true;
882
+ continue;
883
+ }
884
+ if (isShell && SHELL_DASH_O_FLAGS.has(word) && !/^[-+][oO]$/.test(word)) {
885
+ i++;
886
+ continue;
887
+ }
888
+ if (isShell && /^[-+][A-Za-z]+$/.test(word)) {
889
+ // A cluster: `c` runs the first operand as a command line, `s` the program on stdin,
890
+ // and each `o` takes the next word as an option name (`-euo pipefail`).
891
+ if (word.startsWith("-") && word.includes("c"))
892
+ inlineShell = true;
893
+ else if (word.startsWith("-") && word.includes("s"))
894
+ readsStdin = true;
895
+ i += (word.match(/[oO]/g) ?? []).length;
896
+ continue;
897
+ }
898
+ if (inlineFlags?.has(word))
899
+ return { kind: "inline" };
900
+ if ((family === "perl" || family === "ruby") && /^-[A-Za-z]*[eE][A-Za-z]*$/.test(word))
901
+ return { kind: "inline" };
902
+ if (argFlags?.has(word)) {
903
+ i++;
904
+ continue;
905
+ }
906
+ if (/^-./.test(word) || (isShell && /^\+./.test(word)))
907
+ continue;
908
+ }
909
+ if ((family === "deno" || family === "bun") && !subcommandSkipped && word === "run") {
910
+ subcommandSkipped = true;
911
+ continue;
912
+ }
913
+ if (inlineShell)
914
+ return { kind: "inline", code: word };
915
+ if (readsStdin || STDIN_OPERANDS.has(word))
916
+ return { kind: "stdin", fromDescriptor };
917
+ return { kind: "operand", operand: word };
918
+ }
919
+ return inlineShell ? { kind: "inline" } : { kind: "stdin", fromDescriptor };
920
+ }
921
+ /**
922
+ * `true` when a pipe, heredoc or here-string feeds a shell, interpreter or `source` the program
923
+ * it runs from stdin (`curl ... | python3`, `python3 - <<'EOF'`, `source /dev/stdin <<<...`), in
924
+ * the command or any command line it runs. The rule `commandFeedsBareShellWithoutDashC` applies
925
+ * to the shells, and the reason `python* -c*` is a danger pattern: the deny scan can't vet a
926
+ * program in another language. A runner given a script (`... | python3 -m json.tool`,
927
+ * `python3 tool.py <<EOF`) reads data, not code.
928
+ */
929
+ function commandFeedsCodeFromStdin(command) {
930
+ const executed = scanExecutedCode(command);
931
+ return (executed.truncated ||
932
+ executed.segments.some((seg) => {
933
+ if (programSource(unwrappedWords(seg.text))?.kind !== "stdin")
934
+ return false;
935
+ return isPipeOperator(seg.operator) || /<<<|<</.test(seg.text);
936
+ }));
937
+ }
938
+ /**
939
+ * `true` when code runs straight out of a process substitution, in the command or any command
940
+ * line it runs: a shell, interpreter, `source` or `.` whose script is `<(...)` (`bash <(curl ...)`,
941
+ * `source <(...)`) or whose stdin is one (`bash < <(...)`), or a `>(...)` that runs what is written
942
+ * into it (`tee >(sh)`). A descriptor path counts as one, being what `<(...)` expands to
943
+ * (`bash /dev/fd/3 3< <(curl ...)`, `bash <&3`). The deny scan sees the substitution's command,
944
+ * never the program it produces. A process substitution that only carries data
945
+ * (`diff <(ls a) <(ls b)`, `python3 tool.py < <(git log)`) runs nothing.
946
+ */
947
+ function commandRunsProcessSubstitution(command) {
948
+ const executed = scanExecutedCode(command);
949
+ if (executed.truncated)
950
+ return true;
951
+ const runsOne = executed.segments.some((seg) => {
952
+ const source = programSource(unwrappedWords(seg.text));
953
+ if (source?.kind === "operand") {
954
+ return source.operand.startsWith("<(") || DESCRIPTOR_PATH_RE.test(source.operand);
955
+ }
956
+ return source?.kind === "stdin" && source.fromDescriptor;
957
+ });
958
+ return (runsOne ||
959
+ executed.processSubstitutions.some(({ direction, body }) => direction === ">" && programSource(unwrappedWords(body))?.kind === "stdin"));
641
960
  }
642
961
  /**
643
962
  * Extracts the inner command line from a `pwsh -c "..."` / `powershell
@@ -715,6 +1034,24 @@ function extractSimpleEchoOutput(text) {
715
1034
  }
716
1035
  const MAX_DENY_CANDIDATES = 50;
717
1036
  const MAX_DENY_DEPTH = 4;
1037
+ /**
1038
+ * `splitChain`'s segments joined back with one space around every operator, so a pattern written
1039
+ * `curl * | *` also matches `curl x|sh`. `splitChain` reads `|&` as a pipe into an empty piece
1040
+ * sent to the background; here it is spelled `|`, so the pattern matches `curl x |& sh` too.
1041
+ */
1042
+ function spaceChainOperators(segments) {
1043
+ const parts = [];
1044
+ for (let i = 0; i < segments.length; i++) {
1045
+ const seg = segments[i];
1046
+ if (seg.operator === "|" && seg.text === "" && segments[i + 1]?.operator === "&") {
1047
+ parts.push(`| ${segments[i + 1].text.trim()}`);
1048
+ i++;
1049
+ continue;
1050
+ }
1051
+ parts.push(seg.operator === undefined ? seg.text.trim() : `${seg.operator} ${seg.text.trim()}`);
1052
+ }
1053
+ return parts.join(" ");
1054
+ }
718
1055
  /**
719
1056
  * Paranoidly enumerates every independently-executed "piece" of `command` a
720
1057
  * `deny` rule should be checked against: the raw command, each chained
@@ -812,9 +1149,418 @@ function scanDenyCandidates(command) {
812
1149
  }
813
1150
  return { candidates: [...seen], truncated };
814
1151
  }
815
- /** Candidate list only, for callers that don't need the truncation flag. */
1152
+ /**
1153
+ * The heredoc operator at `text[i]` (`<<EOF`, `<<-'EOF'`, `<< "E O F"`, `<<\\EOF`, `<<END-OF-DATA`):
1154
+ * the delimiter is the whole shell word after `<<`, quotes and backslashes removed.
1155
+ */
1156
+ function heredocAt(text, i) {
1157
+ const operator = text.slice(i).match(/^<<(-?)[ \t]*/);
1158
+ if (!operator)
1159
+ return undefined;
1160
+ let j = i + operator[0].length;
1161
+ let delimiter = "";
1162
+ let quoted = false;
1163
+ while (j < text.length && !/[\s;&|<>()]/.test(text[j])) {
1164
+ const ch = text[j];
1165
+ if (ch === "'" || ch === '"') {
1166
+ quoted = true;
1167
+ const close = text.indexOf(ch, j + 1);
1168
+ const end = close === -1 ? text.length : close;
1169
+ delimiter += text.slice(j + 1, end);
1170
+ j = end + 1;
1171
+ }
1172
+ else if (ch === "\\") {
1173
+ quoted = true;
1174
+ delimiter += text[j + 1] ?? "";
1175
+ j += 2;
1176
+ }
1177
+ else {
1178
+ delimiter += ch;
1179
+ j++;
1180
+ }
1181
+ }
1182
+ if (delimiter === "")
1183
+ return undefined;
1184
+ return { length: j - i, delimiter, quoted, stripTabs: operator[1] === "-", unreadable: text[j] === "(" };
1185
+ }
1186
+ /** The index just past the `)` that closes the arithmetic opened by the `(` at `text[open]`. */
1187
+ function arithmeticEnd(text, open) {
1188
+ let depth = 0;
1189
+ for (let j = open; j < text.length; j++) {
1190
+ if (text[j] === "(")
1191
+ depth++;
1192
+ else if (text[j] === ")" && --depth === 0)
1193
+ return j + 1;
1194
+ }
1195
+ return text.length;
1196
+ }
1197
+ /**
1198
+ * How deep `lexShellText` follows `$(`, `<(` and `>(` inside one another. Deeper text is reported
1199
+ * unreadable, so the checks ask instead of recursing until the stack overflows.
1200
+ */
1201
+ const MAX_LEX_NESTING = 32;
1202
+ /** The `$(...)` and backtick substitutions in arithmetic or an unquoted heredoc body, which runs them all. */
1203
+ function substitutionsIn(text, nesting) {
1204
+ const bodies = [];
1205
+ let unreadable = false;
1206
+ let i = 0;
1207
+ while (i < text.length) {
1208
+ if (text[i] === "$" && text[i + 1] === "(" && text[i + 2] !== "(") {
1209
+ const inner = lexShellText(text, i + 2, true, nesting + 1);
1210
+ if (inner.unreadable)
1211
+ unreadable = true;
1212
+ bodies.push(text.slice(i + 2, Math.max(i + 2, inner.end - 1)));
1213
+ i = inner.end;
1214
+ }
1215
+ else if (text[i] === "`") {
1216
+ let j = i + 1;
1217
+ while (j < text.length && text[j] !== "`")
1218
+ j += text[j] === "\\" ? 2 : 1;
1219
+ bodies.push(text.slice(i + 1, j));
1220
+ i = j + 1;
1221
+ }
1222
+ else {
1223
+ i += text[i] === "\\" ? 2 : 1;
1224
+ }
1225
+ }
1226
+ return { bodies, unreadable };
1227
+ }
1228
+ /**
1229
+ * Reads one layer of shell text as the shell would, for the checks that ask whether something is
1230
+ * RUN, and splits it at its unquoted chain operators. Single-quoted text runs nothing; in double
1231
+ * quotes only `$(...)` and backticks run; a quoted heredoc's body is data and an unquoted one runs
1232
+ * only its substitutions; `$((...))` and `((...))` are arithmetic. A `$(`, `<(` or `>(` is read to
1233
+ * the `)` that really closes it, past quotes and heredocs (`untilCloseParen`). Unlike the deny scan,
1234
+ * which over-matches on purpose, a commit message or a file written through a heredoc must not
1235
+ * read as code here. A heredoc that never ends, a delimiter this reader cannot follow, or nesting
1236
+ * past `MAX_LEX_NESTING` is reported, and the checks then ask rather than trust a misread.
1237
+ */
1238
+ function lexShellText(text, start = 0, untilCloseParen = false, nesting = 0) {
1239
+ if (nesting > MAX_LEX_NESTING) {
1240
+ return { segments: [], substitutions: [], processSubstitutions: [], unreadable: true, end: text.length };
1241
+ }
1242
+ const segments = [];
1243
+ const substitutions = [];
1244
+ const processSubstitutions = [];
1245
+ const pendingHeredocs = [];
1246
+ let unreadable = false;
1247
+ let current = "";
1248
+ let operator;
1249
+ let quote;
1250
+ let depth = 0;
1251
+ // Where an escape or a substitution just ended: a `#` there still belongs to that word.
1252
+ let glued = -1;
1253
+ // Open `${` expansions: a `#` inside one (`${x#prefix}`, `${x:- #}`) is never a comment.
1254
+ let braces = 0;
1255
+ const endSegment = (next) => {
1256
+ segments.push({ text: current, operator });
1257
+ current = "";
1258
+ operator = next;
1259
+ };
1260
+ /** Reads the `$(`, `<(` or `>(` body that starts at `open` to its closing `)`; returns the index after it. */
1261
+ const readNested = (open) => {
1262
+ const inner = lexShellText(text, open, true, nesting + 1);
1263
+ if (inner.unreadable)
1264
+ unreadable = true;
1265
+ return inner.end;
1266
+ };
1267
+ // Element by element: spreading 100k substitutions into `push` overflows the stack.
1268
+ const collectSubstitutionsIn = (body) => {
1269
+ const found = substitutionsIn(body, nesting);
1270
+ for (const substitution of found.bodies)
1271
+ substitutions.push(substitution);
1272
+ if (found.unreadable)
1273
+ unreadable = true;
1274
+ };
1275
+ let i = start;
1276
+ while (i < text.length) {
1277
+ const ch = text[i];
1278
+ if (quote === "'") {
1279
+ current += ch;
1280
+ if (ch === "'")
1281
+ quote = undefined;
1282
+ i++;
1283
+ continue;
1284
+ }
1285
+ if (ch === "\\" && i + 1 < text.length) {
1286
+ current += ch + text[i + 1];
1287
+ i += 2;
1288
+ glued = i;
1289
+ continue;
1290
+ }
1291
+ if (ch === "$" && text[i + 1] === "(") {
1292
+ if (text[i + 2] === "(") {
1293
+ const end = arithmeticEnd(text, i + 1);
1294
+ collectSubstitutionsIn(text.slice(i + 3, end));
1295
+ current += text.slice(i, end);
1296
+ i = end;
1297
+ glued = i;
1298
+ continue;
1299
+ }
1300
+ const end = readNested(i + 2);
1301
+ substitutions.push(text.slice(i + 2, Math.max(i + 2, end - 1)));
1302
+ current += text.slice(i, end);
1303
+ i = end;
1304
+ glued = i;
1305
+ continue;
1306
+ }
1307
+ if (ch === "`") {
1308
+ let j = i + 1;
1309
+ while (j < text.length && text[j] !== "`")
1310
+ j += text[j] === "\\" ? 2 : 1;
1311
+ substitutions.push(text.slice(i + 1, j));
1312
+ current += text.slice(i, j + 1);
1313
+ i = j + 1;
1314
+ continue;
1315
+ }
1316
+ if (quote === '"') {
1317
+ if (ch === '"')
1318
+ quote = undefined;
1319
+ current += ch;
1320
+ i++;
1321
+ continue;
1322
+ }
1323
+ if (ch === "$" && text[i + 1] === "{") {
1324
+ braces++;
1325
+ current += "${";
1326
+ i += 2;
1327
+ continue;
1328
+ }
1329
+ if (ch === "}" && braces > 0) {
1330
+ braces--;
1331
+ current += ch;
1332
+ i++;
1333
+ continue;
1334
+ }
1335
+ if (ch === "#" && braces === 0 && i !== glued && (i === start || /[\s;&|()<>]/.test(text[i - 1]))) {
1336
+ // A comment runs to the end of its line, and an apostrophe in it opens no quote.
1337
+ const newline = text.indexOf("\n", i);
1338
+ i = newline === -1 ? text.length : newline;
1339
+ continue;
1340
+ }
1341
+ if (ch === "$" && text[i + 1] === "$") {
1342
+ // `$$` is the shell's pid: a quote right after it is a plain one, not `$'...'`.
1343
+ current += "$$";
1344
+ i += 2;
1345
+ continue;
1346
+ }
1347
+ if (ch === "$" && text[i + 1] === "'") {
1348
+ // ANSI-C quoting: like single quotes, but a backslash escapes the next character, `\'` too.
1349
+ let j = i + 2;
1350
+ while (j < text.length && text[j] !== "'")
1351
+ j += text[j] === "\\" ? 2 : 1;
1352
+ current += text.slice(i, j + 1);
1353
+ i = j + 1;
1354
+ continue;
1355
+ }
1356
+ if (ch === "'" || ch === '"') {
1357
+ quote = ch;
1358
+ current += ch;
1359
+ i++;
1360
+ continue;
1361
+ }
1362
+ if ((ch === "<" || ch === ">") && text[i + 1] === "(") {
1363
+ const end = readNested(i + 2);
1364
+ processSubstitutions.push({ direction: ch, body: text.slice(i + 2, Math.max(i + 2, end - 1)) });
1365
+ current += `${ch}(_)`;
1366
+ i = end;
1367
+ glued = i;
1368
+ continue;
1369
+ }
1370
+ if (ch === "(" && text[i + 1] === "(") {
1371
+ const end = arithmeticEnd(text, i);
1372
+ collectSubstitutionsIn(text.slice(i + 2, end));
1373
+ current += text.slice(i, end);
1374
+ i = end;
1375
+ continue;
1376
+ }
1377
+ if (ch === "(") {
1378
+ depth++;
1379
+ current += ch;
1380
+ i++;
1381
+ continue;
1382
+ }
1383
+ if (ch === ")") {
1384
+ i++;
1385
+ if (depth > 0) {
1386
+ depth--;
1387
+ current += ch;
1388
+ continue;
1389
+ }
1390
+ if (untilCloseParen)
1391
+ break;
1392
+ current += ch;
1393
+ continue;
1394
+ }
1395
+ if (text.startsWith("<<<", i)) {
1396
+ current += "<<<";
1397
+ i += 3;
1398
+ continue;
1399
+ }
1400
+ const heredoc = ch === "<" && text[i + 1] === "<" ? heredocAt(text, i) : undefined;
1401
+ if (heredoc) {
1402
+ if (heredoc.unreadable)
1403
+ unreadable = true;
1404
+ pendingHeredocs.push(heredoc);
1405
+ current += text.slice(i, i + heredoc.length);
1406
+ i += heredoc.length;
1407
+ continue;
1408
+ }
1409
+ const two = text.slice(i, i + 2);
1410
+ if (two === "&&" || two === "||" || two === "|&") {
1411
+ endSegment(two);
1412
+ i += 2;
1413
+ continue;
1414
+ }
1415
+ // `&>file`, `2>&1` and `<&3` are redirections, not a background `&`. The character before
1416
+ // is the one `current` ends with (testing `current` itself would copy it on every `&`).
1417
+ if (ch === "&" && (text[i + 1] === ">" || text[i - 1] === "<" || text[i - 1] === ">")) {
1418
+ current += ch;
1419
+ i++;
1420
+ continue;
1421
+ }
1422
+ if (ch === ";" || ch === "|" || ch === "&") {
1423
+ endSegment(ch);
1424
+ i++;
1425
+ continue;
1426
+ }
1427
+ if (ch !== "\n") {
1428
+ current += ch;
1429
+ i++;
1430
+ continue;
1431
+ }
1432
+ endSegment(";");
1433
+ i++;
1434
+ // The bodies follow this line, one per heredoc it opened, each up to its delimiter line. An
1435
+ // unquoted body is expanded as a whole once it ends, so a substitution may span its lines.
1436
+ for (const pending of pendingHeredocs.splice(0)) {
1437
+ const bodyStart = i;
1438
+ let bodyEnd = text.length;
1439
+ let terminated = false;
1440
+ while (i < text.length) {
1441
+ const newline = text.indexOf("\n", i);
1442
+ const lineStart = i;
1443
+ const line = text.slice(i, newline === -1 ? text.length : newline).replace(/\r$/, "");
1444
+ i = newline === -1 ? text.length : newline + 1;
1445
+ if ((pending.stripTabs ? line.replace(/^\t+/, "") : line) === pending.delimiter) {
1446
+ bodyEnd = lineStart;
1447
+ terminated = true;
1448
+ break;
1449
+ }
1450
+ }
1451
+ if (!terminated)
1452
+ unreadable = true;
1453
+ if (!pending.quoted)
1454
+ collectSubstitutionsIn(text.slice(bodyStart, bodyEnd));
1455
+ }
1456
+ }
1457
+ segments.push({ text: current, operator });
1458
+ return { segments, substitutions, processSubstitutions, unreadable, end: i };
1459
+ }
1460
+ /** How many segments the executed scan reads before it stops and reports itself truncated. */
1461
+ const MAX_EXECUTED_SEGMENTS = 1000;
1462
+ /** The last command's executed scan: one evaluation asks several checks about the same command. */
1463
+ let lastExecutedScan;
1464
+ /**
1465
+ * Finds every command line the shell RUNS for `command`: the command itself and, recursively,
1466
+ * `bash -c` bodies, `eval` arguments, `pwsh -c`/`env -S`/`find -exec` commands and
1467
+ * substitution bodies, each read by `lexShellText`, so neither a heredoc body nor quoted text is
1468
+ * mistaken for one.
1469
+ */
1470
+ function scanExecutedCode(command) {
1471
+ if (lastExecutedScan?.command !== command)
1472
+ lastExecutedScan = { command, result: computeExecutedScan(command) };
1473
+ return lastExecutedScan.result;
1474
+ }
1475
+ function computeExecutedScan(command) {
1476
+ const segments = [];
1477
+ const processSubstitutions = [];
1478
+ const commands = new Set();
1479
+ const seen = new Set();
1480
+ const queue = [{ text: command, depth: 0 }];
1481
+ let truncated = false;
1482
+ // Read by index, not `shift()`: a command with 100k identical substitutions queues every one.
1483
+ for (let head = 0; head < queue.length; head++) {
1484
+ const next = queue[head];
1485
+ if (seen.has(next.text))
1486
+ continue;
1487
+ if (seen.size >= MAX_DENY_CANDIDATES || next.depth >= MAX_DENY_DEPTH) {
1488
+ truncated = true;
1489
+ break;
1490
+ }
1491
+ seen.add(next.text);
1492
+ const lexed = lexShellText(next.text);
1493
+ if (lexed.unreadable)
1494
+ truncated = true;
1495
+ if (segments.length + lexed.segments.length > MAX_EXECUTED_SEGMENTS) {
1496
+ truncated = true;
1497
+ break;
1498
+ }
1499
+ // Element by element: a long script spread into `push` overflows the stack.
1500
+ for (const seg of lexed.segments)
1501
+ segments.push(seg);
1502
+ for (const substitution of lexed.processSubstitutions)
1503
+ processSubstitutions.push(substitution);
1504
+ const runs = (body) => {
1505
+ if (body !== undefined && !seen.has(body))
1506
+ queue.push({ text: body, depth: next.depth + 1 });
1507
+ };
1508
+ for (const body of lexed.substitutions)
1509
+ runs(body);
1510
+ for (const { body } of lexed.processSubstitutions)
1511
+ runs(body);
1512
+ for (const seg of lexed.segments) {
1513
+ const { working, beforeWrappers } = unwrapCommand(seg.text);
1514
+ const basenameResolved = resolveBasenameOfFirstToken(working);
1515
+ for (const text of [seg.text, working, basenameResolved])
1516
+ if (text.trim() !== "")
1517
+ commands.add(text.trim());
1518
+ runs(extractShellBodyAfterDashC(working, SCRIPT_SHELLS) ??
1519
+ extractShellBodyAfterDashC(basenameResolved, SCRIPT_SHELLS));
1520
+ runs(extractOtherShellWrapperArg(working) ?? extractOtherShellWrapperArg(basenameResolved));
1521
+ runs(extractEvalArg(working) ?? extractEvalArg(basenameResolved));
1522
+ runs(extractFindExecArg(working) ?? extractFindExecArg(basenameResolved));
1523
+ runs(extractEnvSplitStringArg(beforeWrappers));
1524
+ // Past clustered options `extractShellBodyAfterDashC` stops at: `bash -euo pipefail -c '...'`.
1525
+ const source = programSource(tokenizeShellWords(working.trim()));
1526
+ if (source?.kind === "inline")
1527
+ runs(source.code);
1528
+ }
1529
+ }
1530
+ return { segments, processSubstitutions, commands: [...commands], truncated };
1531
+ }
1532
+ /** The last command's deny scan: one evaluation matches the same command against every pattern. */
1533
+ let lastDenyScan;
1534
+ function cachedDenyScan(command) {
1535
+ if (lastDenyScan?.command !== command)
1536
+ lastDenyScan = { command, result: scanDenyCandidates(command) };
1537
+ return lastDenyScan;
1538
+ }
1539
+ /**
1540
+ * What deny rules and the danger filter match: the deny scan's candidates, and the command each
1541
+ * segment the executed scan finds the shell runs. The deny scan over-reads on purpose, but it
1542
+ * loses its place at an apostrophe in a heredoc or a comment, at `\"` or `$'...'`, never looks
1543
+ * inside `<(...)`, and keeps `if ...; then`, `{ ...; }` or `( ... )` in front of a command; the
1544
+ * executed scan reads all of those as the shell does. Only the deny scan's own bounds make a
1545
+ * command truncated.
1546
+ */
816
1547
  function collectDenyCandidates(command) {
817
- return scanDenyCandidates(command).candidates;
1548
+ const scan = cachedDenyScan(command);
1549
+ scan.candidates ??= [...new Set([...scan.result.candidates, ...scanExecutedCode(command).commands])];
1550
+ return scan.candidates;
1551
+ }
1552
+ /**
1553
+ * Every candidate normalized for glob matching, and its chain again with spaced operators, so a
1554
+ * pattern written `curl * | *` also matches `curl x|sh` and `curl x |& sh`.
1555
+ */
1556
+ function matchableDenyForms(command) {
1557
+ const scan = cachedDenyScan(command);
1558
+ scan.forms ??= collectDenyCandidates(command).flatMap((candidate) => {
1559
+ const plain = normalizeForMatch(candidate);
1560
+ const spaced = normalizeForMatch(spaceChainOperators(splitChain(candidate)));
1561
+ return spaced === plain ? [plain] : [plain, spaced];
1562
+ });
1563
+ return scan.forms;
818
1564
  }
819
1565
  /**
820
1566
  * `true` when `command` has more chained pieces or wrapper layers than
@@ -824,7 +1570,7 @@ function collectDenyCandidates(command) {
824
1570
  * fall through to an auto-allow default.
825
1571
  */
826
1572
  function commandDenyScanTruncated(command) {
827
- return scanDenyCandidates(command).truncated;
1573
+ return cachedDenyScan(command).result.truncated;
828
1574
  }
829
1575
  /**
830
1576
  * Raw first whitespace-delimited token of `text`, with at most one matching
@@ -866,25 +1612,42 @@ function headIsOtherShellWrapper(text) {
866
1612
  function commandInvokesOtherShell(command) {
867
1613
  return collectDenyCandidates(command).some((candidate) => headIsOtherShellWrapper(candidate));
868
1614
  }
869
- /** A shell variable/parameter expansion, command substitution, or backtick substitution in command position. */
870
- function isDynamicCommandHead(token) {
871
- return /^(\$\(|\$\{|\$[A-Za-z_]|`)/.test(token);
1615
+ /**
1616
+ * A shell variable/parameter expansion, command substitution, or backtick substitution in command
1617
+ * position; with `specialParameters`, positional and special parameters (`$1`, `$@`) too.
1618
+ */
1619
+ function isDynamicCommandHead(token, options) {
1620
+ const pattern = options.specialParameters ? /^(\$\(|\$\{|\$[A-Za-z_0-9@*#?$!-]|`)/ : /^(\$\(|\$\{|\$[A-Za-z_]|`)/;
1621
+ return pattern.test(token);
872
1622
  }
873
1623
  /**
874
1624
  * `true` when any chain segment's command position (after stripping leading
875
1625
  * `VAR=val` assignments) is a variable/expansion rather than a literal
876
- * command name (`$p`, `${HOME:+pwsh}`, `$(...)`, a backtick substitution).
877
- * What actually runs then depends on the environment, so no pattern — deny,
878
- * danger filter, or interpreter check — can reason about it; auto mode must
879
- * require approval instead of silently resolving to whatever the variable
880
- * happens to hold.
1626
+ * command name (`$p`, `${HOME:+pwsh}`, `$(...)`, a backtick substitution), at
1627
+ * any layer the shell runs (`scanExecutedCode`): `bash -c "$(curl ...)"` and `eval "$(curl ...)"`
1628
+ * run another command's output. What actually runs then depends on the
1629
+ * environment or on that output, so no pattern — deny, danger filter, or
1630
+ * interpreter check — can reason about it; auto mode must require approval
1631
+ * instead of silently resolving to whatever the variable happens to hold.
881
1632
  */
882
1633
  function commandHeadIsDynamic(command) {
883
- return splitChain(command).some((seg) => {
884
- const working = stripEnvAssignments(stripLeadingBackslashEscape(seg.text));
885
- const head = tokenizeShellWords(working.trim())[0];
886
- return head !== undefined && isDynamicCommandHead(head);
1634
+ // The raw command's segments include heredoc lines, where `$5` or `"$@"` is text: special
1635
+ // parameters count only in what the lexed scan finds the shell runs, past `then`, `{` or `nohup`.
1636
+ const rawHeadIsDynamic = splitChain(command).some((seg) => {
1637
+ const head = tokenizeShellWords(stripEnvAssignments(stripLeadingBackslashEscape(seg.text)).trim())[0];
1638
+ return head !== undefined && isDynamicCommandHead(head, { specialParameters: false });
887
1639
  });
1640
+ if (rawHeadIsDynamic)
1641
+ return true;
1642
+ const executed = scanExecutedCode(command);
1643
+ return (executed.truncated ||
1644
+ executed.segments.some((seg) => {
1645
+ const heads = [
1646
+ tokenizeShellWords(stripEnvAssignments(stripLeadingBackslashEscape(seg.text)).trim())[0],
1647
+ unwrappedWords(seg.text)[0],
1648
+ ];
1649
+ return heads.some((head) => head !== undefined && isDynamicCommandHead(head, { specialParameters: true }));
1650
+ }));
888
1651
  }
889
1652
  /** Extracts the `<cmd>` from `find ... -exec <cmd> ... ;`/`+`/`-execdir <cmd> ... ;`, if present. */
890
1653
  function extractFindExecArg(text) {
@@ -936,7 +1699,7 @@ function matchDenyPattern(command, pattern) {
936
1699
  return true;
937
1700
  }
938
1701
  const regex = globToRegExp(normalizeForMatch(pattern));
939
- return candidates.some((candidate) => regex.test(normalizeForMatch(candidate)));
1702
+ return matchableDenyForms(command).some((form) => regex.test(form));
940
1703
  }
941
1704
  /**
942
1705
  * Strictly matches `command` against an `allow`/`approve` `pattern`: any
@@ -1017,9 +1780,13 @@ export const DANGEROUS_COMMAND_PATTERNS = [
1017
1780
  // work, and the gate cannot see file contents anyway (see the module doc
1018
1781
  // on interpreter escape hatches).
1019
1782
  "python* -c*",
1783
+ "pypy* -c*",
1020
1784
  "node -e*",
1021
1785
  "node --eval*",
1022
1786
  "node -p*",
1787
+ "nodejs -e*",
1788
+ "nodejs --eval*",
1789
+ "nodejs -p*",
1023
1790
  "bun -e*",
1024
1791
  "bun --eval*",
1025
1792
  "deno eval*",
@@ -1034,37 +1801,47 @@ export const DANGEROUS_COMMAND_PATTERNS = [
1034
1801
  export function findDangerousPattern(command) {
1035
1802
  return DANGEROUS_COMMAND_PATTERNS.find((pattern) => matchDenyPattern(command, pattern));
1036
1803
  }
1037
- /** Normalize a (possibly relative or absolute) path into a forward-slash path relative to `cwd`, for glob matching. */
1804
+ /**
1805
+ * `filePath` relative to `cwd`, resolved EXACTLY as the built-in tools resolve it (`resolveToCwd`:
1806
+ * `~` expansion, a leading `@`, `file://` URLs). The gate must judge the file the tool will open:
1807
+ * resolved naively, `~/.ssh/id_rsa` read as `<cwd>/~/.ssh/id_rsa`, inside the project, while the
1808
+ * read tool opened the real key.
1809
+ */
1810
+ function relativeToProject(filePath, cwd) {
1811
+ return relative(resolve(cwd), resolveToCwd(filePath, cwd));
1812
+ }
1813
+ /** A path argument as a forward-slash path relative to `cwd`, for glob matching. */
1038
1814
  function toMatchablePath(filePath, cwd) {
1039
- const resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);
1040
- const rel = relative(cwd, resolved);
1041
- return rel.split(sep).join("/");
1815
+ return relativeToProject(filePath, cwd).split(sep).join("/");
1042
1816
  }
1043
- /** Whether `filePath` (relative or absolute) resolves to a location inside `cwd`. */
1817
+ /** Whether `filePath` names a location inside `cwd`, as the tool will resolve it. */
1044
1818
  function isWithinProject(filePath, cwd) {
1045
- const resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);
1046
- const rel = relative(cwd, resolved);
1819
+ const rel = relativeToProject(filePath, cwd);
1047
1820
  return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
1048
1821
  }
1049
1822
  /**
1050
1823
  * NOTE: this assumes the tool-call args carry a `command` string under the
1051
- * exact key `command`. If/when this gate is wired into actual tool
1052
- * dispatch, verify every gated tool's argument shape matches these
1053
- * hardcoded key names — a mismatch doesn't error, it just silently fails to
1054
- * match any `pattern`/`paths` rule and falls through to the (fail-safe)
1055
- * default decision. Not currently exploitable: nothing outside this module
1056
- * and its test calls `PermissionGate`/`loadRules` yet.
1824
+ * exact key `command`. Verify every gated tool's argument shape matches
1825
+ * these hardcoded key names — a mismatch doesn't error, it just silently
1826
+ * fails to match any `pattern`/`paths` rule and falls through to the
1827
+ * (fail-safe) default decision.
1057
1828
  */
1058
1829
  function getCommandArg(args) {
1059
1830
  return typeof args.command === "string" ? args.command : undefined;
1060
1831
  }
1061
- /** Prefers `file_path` over `path` when both are present; see the note on `getCommandArg` above. */
1062
- function getPathArg(args) {
1063
- if (typeof args.file_path === "string")
1064
- return args.file_path;
1065
- if (typeof args.path === "string")
1066
- return args.path;
1067
- return undefined;
1832
+ /**
1833
+ * Every path argument the call carries. Both keys count, whichever the tool reads: the built-in
1834
+ * tools read `path`, others `file_path`. Judging only one of them (`file_path` used to win) let a
1835
+ * call name an outside path in the key its tool reads and an inside one in the key the gate read.
1836
+ */
1837
+ function getPathArgs(args) {
1838
+ const paths = [];
1839
+ for (const key of ["file_path", "path"]) {
1840
+ const value = args[key];
1841
+ if (typeof value === "string" && !paths.includes(value))
1842
+ paths.push(value);
1843
+ }
1844
+ return paths;
1068
1845
  }
1069
1846
  function describeMatch(rule) {
1070
1847
  const parts = [`tool=${rule.tool}`];
@@ -1098,11 +1875,17 @@ function ruleMatches(rule, toolName, args, cwd) {
1098
1875
  return false;
1099
1876
  }
1100
1877
  if (rule.paths !== undefined) {
1101
- const filePath = getPathArg(args);
1102
- if (filePath === undefined)
1878
+ const filePaths = getPathArgs(args);
1879
+ if (filePaths.length === 0)
1103
1880
  return false;
1104
- const matchable = toMatchablePath(filePath, cwd);
1105
- if (!rule.paths.some((pattern) => minimatch(matchable, pattern, { dot: true })))
1881
+ const globs = rule.paths;
1882
+ const covered = (filePath) => {
1883
+ const matchable = toMatchablePath(filePath, cwd);
1884
+ return globs.some((pattern) => minimatch(matchable, pattern, { dot: true }));
1885
+ };
1886
+ // The same asymmetry as `pattern`: a deny rule fires on ANY path it names; an allow/approve
1887
+ // rule only when it covers EVERY path the call names, so it never authorizes one it does not.
1888
+ if (rule.action === "deny" ? !filePaths.some(covered) : !filePaths.every(covered))
1106
1889
  return false;
1107
1890
  }
1108
1891
  return true;
@@ -1118,7 +1901,7 @@ export class PermissionGate {
1118
1901
  constructor(rules = [], options = {}) {
1119
1902
  this.rules = rules;
1120
1903
  this.cwd = options.cwd ?? process.cwd();
1121
- this.mode = options.mode ?? "default";
1904
+ this.mode = options.mode ?? "ask";
1122
1905
  }
1123
1906
  /** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */
1124
1907
  evaluate(toolName, args = {}) {
@@ -1156,6 +1939,12 @@ export class PermissionGate {
1156
1939
  if (DEFAULT_ALLOWED_TOOLS.has(toolName)) {
1157
1940
  return { action: "allow", reason: `no rule matched; "${toolName}" is allowed by default` };
1158
1941
  }
1942
+ if (this.mode === "auto" && AUTO_ALLOWED_DELEGATION_TOOLS.has(toolName)) {
1943
+ return {
1944
+ action: "allow",
1945
+ reason: `auto mode: no rule matched; "${toolName}" only starts agents that run this gate themselves`,
1946
+ };
1947
+ }
1159
1948
  if (toolName === "bash") {
1160
1949
  if (this.mode === "auto") {
1161
1950
  const command = getCommandArg(args);
@@ -1172,6 +1961,12 @@ export class PermissionGate {
1172
1961
  reason: `auto mode: command matched dangerous pattern ${JSON.stringify(dangerous)}, requires approval`,
1173
1962
  };
1174
1963
  }
1964
+ if (scanExecutedCode(command).truncated) {
1965
+ return {
1966
+ action: "approve",
1967
+ reason: "auto mode: command nests deeper or runs more pieces than the scan covers, or opens a heredoc that never ends; requires approval",
1968
+ };
1969
+ }
1175
1970
  if (commandHeadIsDynamic(command)) {
1176
1971
  return {
1177
1972
  action: "approve",
@@ -1196,6 +1991,18 @@ export class PermissionGate {
1196
1991
  reason: "auto mode: command feeds a bare shell interpreter via pipe/here-string/heredoc with no -c, which the deny scan can't fully vet; requires approval",
1197
1992
  };
1198
1993
  }
1994
+ if (commandFeedsCodeFromStdin(command)) {
1995
+ return {
1996
+ action: "approve",
1997
+ reason: "auto mode: command feeds an interpreter its program through stdin (pipe, heredoc or here-string), which the deny scan can't vet; requires approval",
1998
+ };
1999
+ }
2000
+ if (commandRunsProcessSubstitution(command)) {
2001
+ return {
2002
+ action: "approve",
2003
+ reason: "auto mode: command runs code straight out of a process substitution, which the deny scan can't vet; requires approval",
2004
+ };
2005
+ }
1199
2006
  return { action: "allow", reason: "auto mode: no rule matched and command passed the danger filter" };
1200
2007
  }
1201
2008
  return { action: "approve", reason: "no rule matched; bash commands require approval by default" };
@@ -1204,13 +2011,13 @@ export class PermissionGate {
1204
2011
  // Unlike bash, powershell has no danger filter tuned for its own
1205
2012
  // syntax (DANGEROUS_COMMAND_PATTERNS is bash-shaped), so auto mode
1206
2013
  // cannot safely auto-allow it — every unmatched powershell call
1207
- // requires approval in default and auto mode (yolo's applyMode still
2014
+ // requires approval in ask and auto mode (yolo's applyMode still
1208
2015
  // turns this approve into allow, as for every tool).
1209
2016
  return { action: "approve", reason: "no rule matched; powershell commands always require approval" };
1210
2017
  }
1211
2018
  if (PATH_SCOPED_TOOLS.has(toolName)) {
1212
- const filePath = getPathArg(args);
1213
- if (filePath !== undefined && isWithinProject(filePath, this.cwd)) {
2019
+ const filePaths = getPathArgs(args);
2020
+ if (filePaths.length > 0 && filePaths.every((filePath) => isWithinProject(filePath, this.cwd))) {
1214
2021
  return { action: "allow", reason: "no rule matched; allowed by default within the project" };
1215
2022
  }
1216
2023
  return {
@@ -1221,8 +2028,9 @@ export class PermissionGate {
1221
2028
  if (READ_ONLY_PATH_TOOLS.has(toolName)) {
1222
2029
  // Unlike read/write/edit, these tools treat a missing `path` as the
1223
2030
  // cwd, so an absent path arg is within the project by definition.
1224
- const filePath = getPathArg(args) ?? ".";
1225
- if (isWithinProject(filePath, this.cwd)) {
2031
+ const filePaths = getPathArgs(args);
2032
+ const searched = filePaths.length > 0 ? filePaths : ["."];
2033
+ if (searched.every((filePath) => isWithinProject(filePath, this.cwd))) {
1226
2034
  return { action: "allow", reason: "no rule matched; read-only tool allowed by default within the project" };
1227
2035
  }
1228
2036
  return {