@draht/coding-agent 2026.10.16-1 → 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.
- package/CHANGELOG.md +39 -0
- package/README.md +1 -0
- package/dist/bundle/chunks/{chunk-BOGY4QVF.js → chunk-3DQNSI5W.js} +4 -4
- package/dist/bundle/chunks/{chunk-VQOV5VFH.js → chunk-4COXSQRQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-6QIFWMDF.js → chunk-CQF6U56X.js} +1 -1
- package/dist/bundle/chunks/{chunk-GD2WVXWT.js → chunk-I2SOJ4JN.js} +3 -3
- package/dist/bundle/chunks/{chunk-KJJJSTND.js → chunk-QPCP4VHF.js} +103 -91
- package/dist/bundle/chunks/{chunk-AHGUOQPH.js → chunk-X3YFUSCK.js} +1 -1
- package/dist/bundle/chunks/{cli-O6OWCY7N.js → cli-VCHSHNKT.js} +1 -1
- package/dist/bundle/chunks/{execute-4JU5WQXP.js → execute-AGEWJLIO.js} +1 -1
- package/dist/bundle/chunks/{runtime-FIGQHW75.js → runtime-2B56SZM6.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-UIGTRGHQ.js → virtual-modules-XT4MP2GI.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +7 -1
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +83 -14
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts.map +1 -1
- package/dist/core/builtins/polyphase.js +21 -2
- package/dist/core/builtins/polyphase.js.map +1 -1
- package/dist/core/builtins/subagent.d.ts +59 -2
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +258 -62
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +23 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +2 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +12 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +5 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +4 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts +18 -6
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +867 -59
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +6 -2
- package/dist/core/polyphase/approval.d.ts.map +1 -1
- package/dist/core/polyphase/approval.js +23 -35
- package/dist/core/polyphase/approval.js.map +1 -1
- package/dist/core/polyphase/child-events.js +1 -1
- package/dist/core/polyphase/child-events.js.map +1 -1
- package/dist/core/polyphase/child-process.d.ts.map +1 -1
- package/dist/core/polyphase/child-process.js +65 -7
- package/dist/core/polyphase/child-process.js.map +1 -1
- package/dist/core/polyphase/commands.d.ts.map +1 -1
- package/dist/core/polyphase/commands.js +46 -5
- package/dist/core/polyphase/commands.js.map +1 -1
- package/dist/core/polyphase/details.d.ts.map +1 -1
- package/dist/core/polyphase/details.js +5 -0
- package/dist/core/polyphase/details.js.map +1 -1
- package/dist/core/polyphase/permission-bridge.d.ts +128 -0
- package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
- package/dist/core/polyphase/permission-bridge.js +357 -0
- package/dist/core/polyphase/permission-bridge.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
- package/dist/core/polyphase/render/run-block.js +13 -4
- package/dist/core/polyphase/render/run-block.js.map +1 -1
- package/dist/core/polyphase/render/snapshot.d.ts +4 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
- package/dist/core/polyphase/render/snapshot.js +4 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -1
- package/dist/core/polyphase/result-text.d.ts.map +1 -1
- package/dist/core/polyphase/result-text.js +23 -3
- package/dist/core/polyphase/result-text.js.map +1 -1
- package/dist/core/polyphase/session.d.ts +15 -1
- package/dist/core/polyphase/session.d.ts.map +1 -1
- package/dist/core/polyphase/session.js +36 -1
- package/dist/core/polyphase/session.js.map +1 -1
- package/dist/core/polyphase/settings.d.ts +1 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -1
- package/dist/core/polyphase/settings.js +1 -1
- package/dist/core/polyphase/settings.js.map +1 -1
- package/dist/core/polyphase/store.d.ts +18 -0
- package/dist/core/polyphase/store.d.ts.map +1 -1
- package/dist/core/polyphase/store.js +38 -0
- package/dist/core/polyphase/store.js.map +1 -1
- package/dist/core/polyphase/types.d.ts +60 -3
- package/dist/core/polyphase/types.d.ts.map +1 -1
- package/dist/core/polyphase/types.js.map +1 -1
- package/dist/core/polyphase/ui/inspector.js +1 -1
- package/dist/core/polyphase/ui/inspector.js.map +1 -1
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/agent-host.js +17 -3
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/guidance.js +16 -5
- package/dist/core/polyphase/workflow/guidance.js.map +1 -1
- package/dist/core/polyphase/workflow/launch.d.ts +2 -1
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/launch.js +22 -3
- package/dist/core/polyphase/workflow/launch.js.map +1 -1
- package/dist/core/polyphase/workflow/limits.d.ts +80 -0
- package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/limits.js +234 -0
- package/dist/core/polyphase/workflow/limits.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/runtime.js.map +1 -1
- package/dist/core/polyphase/workflow/tool.d.ts +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/tool.js +23 -2
- package/dist/core/polyphase/workflow/tool.js.map +1 -1
- package/dist/core/usage-totals.d.ts +5 -0
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +16 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +4 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +2 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +3 -0
- package/dist/utils/shell.js.map +1 -1
- package/docs/duet.md +1 -1
- package/docs/environment-variables.md +3 -1
- package/docs/extensions.md +2 -1
- package/docs/keybindings.md +1 -0
- package/docs/polyphase.md +97 -33
- package/docs/settings.md +2 -2
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permission-gate.js","sourceRoot":"","sources":["../../../src/core/multi-agent/permission-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AA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,KAAK,SAAS,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACnE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,wDAAwD,EAAE,CAAC;YAC9F,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,SAAS;gBACjB,MAAM,EAAE,8EAA8E;aACtF,CAAC;QACH,CAAC;QAED,IAAI,oBAAoB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxC,oEAAoE;YACpE,kEAAkE;YAClE,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC;YACzC,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACzC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,uEAAuE,EAAE,CAAC;YAC7G,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,SAAS;gBACjB,MAAM,EAAE,iEAAiE;aACzE,CAAC;QACH,CAAC;QAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,6BAA6B,QAAQ,wBAAwB,EAAE,CAAC;IACrG,CAAC;CACD","sourcesContent":["/**\n * Permission gate: a three-tier permission system that decides whether a\n * tool call may proceed automatically, must be blocked, or must be confirmed\n * by the user before it runs.\n *\n * SECURITY-CRITICAL: this module gates real bash/write tool calls. Prefer\n * fail-safe (approve/deny) over fail-open (allow) whenever a decision is\n * ambiguous.\n *\n * Configuration is read from `.draht/permissions.yml` (project) and\n * `~/.draht/agent/permissions.yml` (global), e.g.:\n *\n * ```yaml\n * rules:\n * - tool: bash\n * pattern: \"rm -rf *\"\n * action: deny\n * - tool: bash\n * pattern: \"git push *\"\n * action: approve\n * - tool: read\n * action: allow\n * - tool: write\n * paths: [\"src/**\"]\n * action: allow\n * - tool: write\n * action: approve\n * ```\n *\n * Rules are evaluated top-to-bottom; the first matching rule wins.\n *\n * On top of the rules sits a session-level `PermissionMode` (`default` /\n * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and\n * `approve` outcomes are handled — `deny` rules are never relaxed.\n *\n * `pattern` matching against bash commands is textual (no real shell\n * parser), so `deny` and `allow`/`approve` patterns are matched with\n * deliberately asymmetric strategies to stay fail-safe: `deny` scans every\n * chained/wrapped/unwrapped piece of the command it can find (paranoid,\n * over-matching is safe), while `allow`/`approve` require an exact\n * chain-shape match and reject anything containing `$(...)`, backticks, or\n * redirection (strict, under-matching just falls through to the default\n * decision instead of silently authorizing more than intended). See the\n * doc comment on `matchCommandPattern` below for details and known limits —\n * in particular, `pattern` can never guarantee real path containment; use\n * `paths` for that.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { minimatch } from \"minimatch\";\nimport { parse } from \"yaml\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.ts\";\n\n/** The three permission tiers a rule (or default) can resolve to. */\nexport type PermissionAction = \"deny\" | \"allow\" | \"approve\";\n\n/**\n * Session-level permission mode. Modes only relax the gate's *default*\n * decisions — explicit rules from `permissions.yml` always win first:\n *\n * - `default`: rules as authored; unmatched bash/powershell requires approval.\n * - `auto`: unmatched bash is auto-allowed unless it trips the built-in\n * danger filter (`DANGEROUS_COMMAND_PATTERNS`), in which case it still\n * requires approval. `powershell` is excluded from this auto-allow — the\n * danger filter is bash-shaped and has no powershell-specific coverage, so\n * unmatched powershell calls always require approval, even in auto mode.\n * Explicit `deny`/`approve` rules behave as authored.\n * - `yolo`: every `approve` (rule-based or default) is downgraded to\n * `allow`. Explicit `deny` rules still block — yolo is \"stop asking\",\n * not \"disable the gate\".\n */\nexport type PermissionMode = \"default\" | \"auto\" | \"yolo\";\n\nexport const PERMISSION_MODES: readonly PermissionMode[] = [\"default\", \"auto\", \"yolo\"];\n\nexport function isPermissionMode(value: unknown): value is PermissionMode {\n\treturn typeof value === \"string\" && (PERMISSION_MODES as readonly string[]).includes(value);\n}\n\n/** A single permission rule as authored in `permissions.yml`. */\nexport interface PermissionRule {\n\t/** Tool identifier this rule applies to (e.g. \"bash\", \"read\", \"write\", \"edit\"), or \"*\" for any tool. */\n\ttool: string;\n\t/** Glob pattern matched against the bash command string (only meaningful for tools with a `command` arg). */\n\tpattern?: string;\n\t/** Glob patterns matched against the file path (only meaningful for tools with a `path`/`file_path` arg). */\n\tpaths?: string[];\n\t/** The action to take when this rule matches. */\n\taction: PermissionAction;\n}\n\n/** The result of evaluating a tool call against the permission rules. */\nexport interface PermissionDecision {\n\taction: PermissionAction;\n\treason: string;\n}\n\nconst VALID_ACTIONS: readonly PermissionAction[] = [\"deny\", \"allow\", \"approve\"];\nconst RULES_FILE_NAME = \"permissions.yml\";\nconst PATH_SCOPED_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n/** Read-only tools whose optional `path` arg defaults to the cwd when omitted. */\nconst READ_ONLY_PATH_TOOLS = new Set([\"grep\", \"find\", \"ls\"]);\n/**\n * Tools that are safe to run without confirmation because the call itself\n * only delegates: spawned child processes run this same gate over every tool\n * call they actually make. Explicit rules can still `deny`/`approve` these.\n * Duet delegation is deliberately not included because it fans out paid model\n * requests; unmatched duet batches require explicit approval.\n *\n * `polyphase_result` is also allowed by default: it returns a value to the parent workflow; no\n * side effects; children have no UI to approve it.\n */\nconst DEFAULT_ALLOWED_TOOLS = new Set([\"subagent\", \"polyphase_result\"]);\n\nfunction isPermissionAction(value: unknown): value is PermissionAction {\n\treturn typeof value === \"string\" && (VALID_ACTIONS as readonly string[]).includes(value);\n}\n\nfunction validateRule(raw: unknown, index: number): PermissionRule {\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} must be an object`);\n\t}\n\tconst record = raw as Record<string, unknown>;\n\n\tif (typeof record.tool !== \"string\" || record.tool.length === 0) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} is missing a valid \"tool\" field`);\n\t}\n\tif (!isPermissionAction(record.action)) {\n\t\tthrow new Error(\n\t\t\t`permissions.yml: rule at index ${index} has an invalid \"action\" (must be one of ${VALID_ACTIONS.join(\", \")})`,\n\t\t);\n\t}\n\n\tconst rule: PermissionRule = { tool: record.tool, action: record.action };\n\n\tif (record.pattern !== undefined) {\n\t\tif (typeof record.pattern !== \"string\") {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has a non-string \"pattern\"`);\n\t\t}\n\t\trule.pattern = record.pattern;\n\t}\n\n\tif (record.paths !== undefined) {\n\t\tif (!Array.isArray(record.paths) || !record.paths.every((entry) => typeof entry === \"string\")) {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has an invalid \"paths\" (must be a string array)`);\n\t\t}\n\t\trule.paths = record.paths as string[];\n\t}\n\n\treturn rule;\n}\n\n/**\n * Parse a `permissions.yml` document (as a string) into an ordered list of\n * rules. Returns an empty array for empty documents or documents without a\n * `rules` key. Throws on malformed rule entries so misconfiguration fails\n * loudly rather than silently degrading the gate.\n */\nexport function parseRules(yamlText: string): PermissionRule[] {\n\tconst parsed = parse(yamlText) as { rules?: unknown } | null | undefined;\n\tif (parsed === null || parsed === undefined) return [];\n\tif (parsed.rules === undefined) return [];\n\tif (!Array.isArray(parsed.rules)) {\n\t\tthrow new Error('permissions.yml: \"rules\" must be an array');\n\t}\n\treturn parsed.rules.map((raw, index) => validateRule(raw, index));\n}\n\nfunction readRulesFile(filePath: string): PermissionRule[] {\n\tif (!existsSync(filePath)) return [];\n\treturn parseRules(readFileSync(filePath, \"utf-8\"));\n}\n\n/**\n * Load and merge permission rules from the global (`~/.draht/agent/permissions.yml`)\n * and project (`<projectDir>/.draht/permissions.yml`) config files.\n *\n * Loading order: global is read first, project is read after (so a project\n * can be authored as a delta on top of the global defaults). Merge order is\n * reversed relative to load order: project rules are placed *before* global\n * rules in the returned array, so that under first-match-wins evaluation the\n * project's rules take precedence over — i.e. \"override\" — the global ones.\n */\nexport function loadRules(projectDir?: string, globalDir?: string): PermissionRule[] {\n\tconst globalRulesPath = join(globalDir ?? getAgentDir(), RULES_FILE_NAME);\n\tconst projectRulesPath = join(projectDir ?? process.cwd(), CONFIG_DIR_NAME, RULES_FILE_NAME);\n\n\tconst globalRules = readRulesFile(globalRulesPath);\n\tconst projectRules = readRulesFile(projectRulesPath);\n\n\treturn [...projectRules, ...globalRules];\n}\n\n/**\n * Bash `pattern` matching against the raw command string can never be more\n * than textual — it has no real shell parser behind it. A previous\n * implementation matched the whole command string against the pattern with\n * minimatch after stripping every \"/\" (to stop \"*\" from being blocked by\n * minimatch's path-segment semantics). That was trivially bypassed: any\n * prefix at all (a leading space, `sudo`, `/bin/`, `env`, chaining with `;`\n * or `&&`, wrapping in `bash -c \"...\"`, double spaces, reordered combined\n * flags like `-fr` vs `-rf`, or different case) defeated the anchored match,\n * and — separately — a trailing-wildcard *allow* rule like\n * `{ pattern: \"npm test*\", action: \"allow\" }` matched anything appended\n * after it via `;`, `&&`, `|`, backticks, or `$(...)`, silently\n * auto-approving injected commands.\n *\n * To stay fail-safe rather than fail-open, `deny` and `allow`/`approve` are\n * matched with deliberately different, asymmetric strategies:\n *\n * - `deny` is matched *paranoidly*. The command is decomposed into every\n * independently-executed piece we can find — split on chaining operators\n * (`;`, `&&`, `||`, `|`, `&`, newlines); unwrapped from passthrough\n * prefixes (`sudo`, `env`, `nice`, ...) and leading `VAR=val`\n * assignments; unwrapped from `bash -c \"...\"` / `sh -c '...'` / `eval\n * \"...\"`; unwrapped from `$(...)`/backtick substitutions; resolved from\n * an absolute/relative path to a bare command name — recursively, up to\n * a bounded depth/count. The pattern matches if *any* resulting\n * candidate matches, after collapsing whitespace and canonicalizing\n * combined short flags (so `-rf`/`-fr` compare equal), case-insensitively.\n * Over-matching here is the safe failure mode.\n * - `allow`/`approve` are matched *strictly*: the command is rejected\n * outright if it contains any dynamic/opaque construct (`$(...)`,\n * backticks, redirection `<`/`>`), and otherwise must have the exact same\n * chain shape (same number of segments joined by the same operators) as\n * the pattern, with each segment matched independently. A rule authored\n * for `npm test*` therefore can never also authorize\n * `npm test; rm -rf /` — the extra chained segment has no counterpart in\n * the pattern, so the rule simply doesn't match (falling through to the\n * default decision) instead of silently allowing it.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): interpreter\n * escape hatches. Once a command hands control to a language runtime, the\n * payload is no longer shell and no shell-shaped pattern — `deny` rules\n * included — can see into it: `python -c \"os.system('rm -rf /')\"` never\n * surfaces `rm -rf /` as a match candidate, `python script.py` hides the\n * danger in file contents the gate never reads, and\n * `python -c \"shutil.rmtree('/')\"` involves no shell command at all. The\n * built-in danger filter flags *inline eval* invocations (`python -c`,\n * `node -e`, ...) so auto mode prompts on them, but script files and\n * in-language equivalents are out of reach by construction. The gate is a\n * guard against a confused agent, not a confinement boundary for a\n * malicious one — a hard boundary needs OS-level sandboxing of the bash\n * tool itself (Seatbelt/Landlock-style), not better string matching.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): `pattern` cannot\n * enforce real directory containment. A rule like\n * `{ pattern: \"cat /safe/dir/*\", action: \"allow\" }` will still match\n * `cat /safe/dir/../../../etc/passwd`, because from a glob's point of view\n * `..` is just more characters absorbed by the trailing `*` — there is no\n * shell/path awareness in a plain string pattern. Use the `paths` mechanism\n * (which resolves real paths via `resolve`/`relative`, see `toMatchablePath`\n * below) instead of `pattern` whenever a rule needs to be scoped to a\n * directory; don't rely on `pattern` for path containment.\n */\n\n/** Command names that merely forward to another command without changing what ultimately runs. */\nconst PASSTHROUGH_PREFIXES = new Set([\n\t\"sudo\",\n\t\"doas\",\n\t\"command\",\n\t\"exec\",\n\t\"nice\",\n\t\"nohup\",\n\t\"env\",\n\t\"time\",\n\t\"stdbuf\",\n\t\"ionice\",\n\t\"chrt\",\n\t\"setsid\",\n\t\"xargs\",\n\t\"timeout\",\n\t// busybox dispatches to its builtin applet by the same name and arguments\n\t// it was given (`busybox rm -rf /` behaves exactly like `rm -rf /`), so it\n\t// is a pure passthrough for deny-scan purposes.\n\t\"busybox\",\n\t// wsl/wsl.exe runs its arguments as a command inside the Linux subsystem,\n\t// same shape as sudo/env.\n\t\"wsl\",\n]);\n\n/** Shells whose `-c <command>` argument is itself a full command line to unwrap and re-check. */\nconst SHELL_C_WRAPPERS = new Set([\"bash\", \"sh\", \"zsh\", \"ksh\", \"dash\", \"fish\"]);\n\n/**\n * Non-POSIX shells whose command-line argument is itself a full command line\n * to unwrap and re-check. Catches bash wrapping another shell, e.g.\n * `bash -c \"pwsh -c 'rm -rf ~'\"`. Matched by regex rather than a fixed Set so\n * variants like `pwsh-preview`, `powershell_ise`, and `.exe`/path-prefixed\n * spellings (normalized by `basenameOfHeadToken`) are all covered.\n */\nconst OTHER_SHELL_WRAPPER_RE = /^(pwsh|powershell|powershell_ise|cmd)([-_].*)?$/;\n\nfunction isOtherShellWrapperName(basename: string): boolean {\n\treturn OTHER_SHELL_WRAPPER_RE.test(basename);\n}\n\n/** Constructs that make a command dynamic/opaque enough that allow/approve patterns must never match it. */\nconst DANGEROUS_CONSTRUCT_RE = /\\$\\(|`|<|>/;\n\ninterface ChainSegment {\n\ttext: string;\n\t/** The operator immediately preceding this segment; `undefined` for the first segment. */\n\toperator?: string;\n}\n\n/** Quote-aware split of a command string on top-level chain operators (`;`, `&&`, `||`, `|`, `&`, newlines). */\nfunction splitChain(command: string): ChainSegment[] {\n\tconst segments: ChainSegment[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet operator: string | undefined;\n\tlet i = 0;\n\twhile (i < command.length) {\n\t\tconst ch = command[i];\n\t\tif (quote) {\n\t\t\tcurrent += ch;\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"' || ch === \"'\") {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < command.length) {\n\t\t\tcurrent += ch + command[i + 1];\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tconst two = command.slice(i, i + 2);\n\t\tif (two === \"&&\" || two === \"||\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = two;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = ch === \"\\n\" ? \";\" : ch;\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\tsegments.push({ text: current, operator });\n\treturn segments;\n}\n\nfunction collapseWhitespace(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * Canonicalizes combined single-dash short-flag clusters (`-rf` / `-fr`) by\n * sorting their letters. The sort is case-insensitive: matching elsewhere is\n * already case-insensitive (`globToRegExp`'s `i` flag), but a case-sensitive\n * sort would put uppercase letters before lowercase ones (ASCII order), so a\n * mixed-case cluster like `-Rf` would canonicalize to `-Rf` while `-rf`\n * canonicalizes to `-fr` — different letter *order*, which the `i` flag\n * can't paper over. Sorting case-insensitively (while keeping each letter's\n * original case) gives `-Rf` and `-rf` the same order (`-fR` / `-fr`), so\n * `-Rf`/`-fR`/`-RF`/... all canonicalize to match a plain `-rf` pattern.\n */\nfunction normalizeFlagClusters(text: string): string {\n\treturn text.replace(/(^|\\s)-([A-Za-z]{2,})(?=\\s|$)/g, (_match, pre: string, letters: string) => {\n\t\tconst sorted = [...letters].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n\t\treturn `${pre}-${sorted.join(\"\")}`;\n\t});\n}\n\nfunction normalizeForMatch(text: string): string {\n\treturn normalizeFlagClusters(collapseWhitespace(text));\n}\n\nfunction tokenize(text: string): string[] {\n\tconst trimmed = text.trim();\n\treturn trimmed.length === 0 ? [] : trimmed.split(/\\s+/);\n}\n\n/** A combined short-flag cluster token (`-rf`, `-R`), optionally glob-suffixed (`-r*`) by a danger-pattern author. */\nfunction parseShortFlagClusterToken(token: string): string | undefined {\n\treturn token.match(/^-([A-Za-z]+)\\*?$/)?.[1];\n}\n\nfunction parseLongFlagToken(token: string): string | undefined {\n\treturn token.match(/^--([A-Za-z][A-Za-z-]*)$/)?.[1]?.toLowerCase();\n}\n\ninterface FlagSet {\n\tshortFlags: Set<string>;\n\tlongFlags: Set<string>;\n}\n\n/** Collects every short/long flag found anywhere in `tokens`, regardless of order, clustering, or position. */\nfunction extractFlagSet(tokens: string[]): FlagSet {\n\tconst shortFlags = new Set<string>();\n\tconst longFlags = new Set<string>();\n\tfor (const token of tokens) {\n\t\tconst letters = parseShortFlagClusterToken(token);\n\t\tif (letters !== undefined) {\n\t\t\tfor (const ch of letters) shortFlags.add(ch.toLowerCase());\n\t\t\tcontinue;\n\t\t}\n\t\tconst long = parseLongFlagToken(token);\n\t\tif (long !== undefined) longFlags.add(long);\n\t}\n\treturn { shortFlags, longFlags };\n}\n\ninterface FlagClusterDenyPattern {\n\tcommand: string;\n\trequiredShortFlags: Set<string>;\n\trequiredLongFlags: Set<string>;\n}\n\n/**\n * Parses a deny `pattern` of the shape `<command> <flags...> [*]` (e.g.\n * `rm -rf *`, `rm -r*`, `chmod -R *`) into a required flag set, for matching\n * by `flagClusterPatternMatchesCandidate` below. Returns `undefined` for any\n * pattern that doesn't have this exact \"bare command name plus only\n * flags/wildcard\" shape, so those patterns keep using the generic glob\n * matcher unchanged.\n */\nfunction parseFlagClusterPattern(pattern: string): FlagClusterDenyPattern | undefined {\n\tconst [command, ...rest] = tokenize(pattern);\n\tif (command === undefined || /[*?]/.test(command)) return undefined;\n\n\tconst requiredShortFlags = new Set<string>();\n\tconst requiredLongFlags = new Set<string>();\n\tlet sawFlag = false;\n\tfor (const token of rest) {\n\t\tif (token === \"*\") continue;\n\t\tconst letters = parseShortFlagClusterToken(token);\n\t\tif (letters !== undefined) {\n\t\t\tsawFlag = true;\n\t\t\tfor (const ch of letters) requiredShortFlags.add(ch.toLowerCase());\n\t\t\tcontinue;\n\t\t}\n\t\tconst long = parseLongFlagToken(token);\n\t\tif (long !== undefined) {\n\t\t\tsawFlag = true;\n\t\t\trequiredLongFlags.add(long);\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (!sawFlag) return undefined;\n\treturn { command: command.toLowerCase(), requiredShortFlags, requiredLongFlags };\n}\n\n/** `rm`'s two spellings of \"recursive\"/\"force\" that are interchangeable for flag-set matching purposes. */\nconst SHORT_LONG_FLAG_EQUIVALENTS: ReadonlyMap<string, string> = new Map([\n\t[\"r\", \"recursive\"],\n\t[\"f\", \"force\"],\n]);\n\nfunction flagClusterPatternMatchesCandidate(flagPattern: FlagClusterDenyPattern, candidateText: string): boolean {\n\tconst tokens = tokenize(candidateText);\n\tconst commandToken = tokens[0];\n\tif (commandToken === undefined) return false;\n\tconst commandName = (\n\t\tcommandToken.includes(\"/\") ? commandToken.slice(commandToken.lastIndexOf(\"/\") + 1) : commandToken\n\t).toLowerCase();\n\tif (commandName !== flagPattern.command) return false;\n\n\tconst { shortFlags, longFlags } = extractFlagSet(tokens.slice(1));\n\tconst hasShort = (flag: string) =>\n\t\tshortFlags.has(flag) || longFlags.has(SHORT_LONG_FLAG_EQUIVALENTS.get(flag) ?? \"\");\n\tconst hasLong = (flag: string) => {\n\t\tif (longFlags.has(flag)) return true;\n\t\tfor (const [short, long] of SHORT_LONG_FLAG_EQUIVALENTS) {\n\t\t\tif (long === flag && shortFlags.has(short)) return true;\n\t\t}\n\t\treturn false;\n\t};\n\n\tfor (const flag of flagPattern.requiredShortFlags) if (!hasShort(flag)) return false;\n\tfor (const flag of flagPattern.requiredLongFlags) if (!hasLong(flag)) return false;\n\treturn true;\n}\n\n/** Resolves a leading `/some/path/cmd` (or `./cmd`, `../cmd`) first token down to its bare basename. */\nfunction resolveBasenameOfFirstToken(text: string): string {\n\tconst leadingWs = text.slice(0, text.length - text.trimStart().length);\n\tconst trimmed = text.trimStart();\n\tconst match = trimmed.match(/^(\\S+)([\\s\\S]*)$/);\n\tif (!match) return text;\n\tconst [, firstToken, rest] = match;\n\tif (!firstToken.includes(\"/\")) return text;\n\tconst basename = firstToken.slice(firstToken.lastIndexOf(\"/\") + 1);\n\treturn leadingWs + basename + rest;\n}\n\nfunction stripLeadingBackslashEscape(text: string): string {\n\treturn text.replace(/^(\\s*)\\\\(?=[A-Za-z])/, \"$1\");\n}\n\nfunction stripEnvAssignments(text: string): string {\n\treturn text.replace(/^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)+/, \"\");\n}\n\n/**\n * Flags that consume a separate following argument (rather than being a\n * standalone `-flag` token) for each passthrough wrapper, so\n * `stripPassthroughPrefix` doesn't mistake that argument for the start of\n * the wrapped command.\n */\nconst WRAPPER_FLAGS_WITH_ARG: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n\t[\"timeout\", new Set([\"-s\", \"-k\", \"--signal\", \"--kill-after\"])],\n\t[\"nice\", new Set([\"-n\"])],\n\t[\"ionice\", new Set([\"-c\", \"-n\", \"-p\"])],\n\t// policy flags (-b/-f/-i/-o/-r) take a priority; -p takes a target pid.\n\t[\"chrt\", new Set([\"-b\", \"-f\", \"-i\", \"-o\", \"-r\", \"-p\"])],\n\t[\"stdbuf\", new Set([\"-i\", \"-o\", \"-e\"])],\n\t[\"env\", new Set([\"-u\", \"-C\", \"-S\", \"--split-string\"])],\n\t[\"sudo\", new Set([\"-u\", \"-g\", \"-h\", \"-p\", \"-C\", \"-D\", \"-r\", \"-t\", \"-U\"])],\n]);\n\n/**\n * Strips one leading passthrough-wrapper command (e.g. `sudo`, `env FOO=1`)\n * and its own flags, if present, consuming each flag's own separate argument\n * (`WRAPPER_FLAGS_WITH_ARG`) rather than mistaking it for the wrapped\n * command. `timeout DURATION cmd...` additionally skips the required\n * duration positional, which isn't a `-flag` token, so `timeout 5 rm -rf /`\n * unwraps down to `rm -rf /` instead of leaving the bogus `5 rm -rf /`\n * behind.\n */\nfunction stripPassthroughPrefix(text: string): { stripped: string; changed: boolean } {\n\tconst trimmed = text.replace(/^\\s+/, \"\");\n\tconst tokens = tokenizeShellWords(trimmed);\n\tconst head = tokens[0];\n\tif (head === undefined) return { stripped: text, changed: false };\n\tconst basename = basenameOfHeadToken(head);\n\tif (!PASSTHROUGH_PREFIXES.has(basename)) return { stripped: text, changed: false };\n\n\tconst argFlags = WRAPPER_FLAGS_WITH_ARG.get(basename);\n\tlet i = 1;\n\twhile (i < tokens.length) {\n\t\tconst token = tokens[i];\n\t\tif (argFlags?.has(token)) {\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/^-/.test(token)) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\tif (basename === \"timeout\" && i < tokens.length) i++;\n\n\treturn { stripped: tokens.slice(i).map(requoteTokenIfNeeded).join(\" \"), changed: true };\n}\n\n/** Re-wraps a dequoted token in single quotes if it contains whitespace, so rejoining tokens with `\" \"` doesn't silently merge what was one quoted argument into several unquoted words. */\nfunction requoteTokenIfNeeded(token: string): string {\n\treturn /\\s/.test(token) ? `'${token.replace(/'/g, `'\\\\''`)}'` : token;\n}\n\n/**\n * Minimal POSIX-ish shell word tokenizer: splits `text` on unquoted\n * whitespace, honoring single quotes (fully literal, no escapes), double\n * quotes (backslash escapes the next character), and a bare backslash\n * outside quotes (escapes the next character). This is only used to locate\n * wrapper flags and the command-body token that follows them, not to\n * implement real shell grammar (no variable expansion, globbing, etc.).\n */\nfunction tokenizeShellWords(text: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet hasCurrent = false;\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst ch = text[i];\n\t\tif (/\\s/.test(ch)) {\n\t\t\tif (hasCurrent) {\n\t\t\t\ttokens.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t\thasCurrent = false;\n\t\t\t}\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\") {\n\t\t\thasCurrent = true;\n\t\t\ti++;\n\t\t\twhile (i < text.length && text[i] !== \"'\") {\n\t\t\t\tcurrent += text[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\thasCurrent = true;\n\t\t\ti++;\n\t\t\twhile (i < text.length && text[i] !== '\"') {\n\t\t\t\tif (text[i] === \"\\\\\" && i + 1 < text.length) {\n\t\t\t\t\tcurrent += text[i + 1];\n\t\t\t\t\ti += 2;\n\t\t\t\t} else {\n\t\t\t\t\tcurrent += text[i];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < text.length) {\n\t\t\thasCurrent = true;\n\t\t\tcurrent += text[i + 1];\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\thasCurrent = true;\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\tif (hasCurrent) tokens.push(current);\n\treturn tokens;\n}\n\n/**\n * Lowercased basename of a (possibly quoted/escaped, already-tokenized)\n * command-head token: split on both `/` and `\\` (Windows paths), lowercased,\n * with a trailing `.exe` stripped — so `C:\\Windows\\System32\\cmd.EXE`,\n * `./cmd`, and `cmd` all normalize to `cmd` for wrapper/interpreter lookup.\n */\nfunction basenameOfHeadToken(token: string): string {\n\tconst parts = token.split(/[/\\\\]/);\n\tconst base = (parts[parts.length - 1] ?? token).toLowerCase();\n\treturn base.endsWith(\".exe\") ? base.slice(0, -4) : base;\n}\n\n/** Shell options that consume the following token as their own argument, not as part of the command. */\nconst SHELL_DASH_O_FLAGS = new Set([\"-o\", \"-O\", \"+o\", \"+O\", \"--rcfile\", \"--init-file\"]);\n\n/**\n * Extracts the command-body token following a `-c` flag from an\n * already-tokenized shell invocation, if `text`'s head is in `wrapperSet` and\n * a `-c` flag (bare or clustered with other short flags, e.g. `-lc`, `-cx`,\n * `-ce`) appears anywhere before the first non-flag token — including after\n * `-o pipefail`, `-O extglob`, `--`, or `-l`. Trailing positional arguments\n * after the body (e.g. `$0` in `bash -c '...' x`) are ignored.\n */\nfunction extractShellBodyAfterDashC(text: string, wrapperSet: ReadonlySet<string>): string | undefined {\n\tconst tokens = tokenizeShellWords(text.trim());\n\tconst head = tokens[0];\n\tif (head === undefined || !wrapperSet.has(basenameOfHeadToken(head))) return undefined;\n\n\tlet sawDashC = false;\n\tfor (let i = 1; i < tokens.length; i++) {\n\t\tconst token = tokens[i];\n\t\tif (token === \"--\") continue;\n\t\tif (SHELL_DASH_O_FLAGS.has(token)) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/^-[A-Za-z]+$/.test(token)) {\n\t\t\tif (token.includes(\"c\")) sawDashC = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// Long (`--norc`, `--login`) and `+` options (`+x`) are flags too; skip them\n\t\t// so a later `-c` is still found.\n\t\tif (/^(?:--|\\+)[A-Za-z][\\w-]*$/.test(token)) continue;\n\t\treturn sawDashC ? token : undefined;\n\t}\n\treturn undefined;\n}\n\n/** Extracts the payload of a `<<< '...'` here-string or a `<<DELIM ... DELIM` heredoc, if present anywhere in `text`. */\nfunction extractHereStringOrHeredocPayload(text: string): string | undefined {\n\tconst hereString = text.match(/<<<\\s*(['\"]?)([\\s\\S]*?)\\1\\s*$/);\n\tif (hereString) return hereString[2];\n\tconst heredoc = text.match(/<<-?\\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\\1[^\\n]*\\n([\\s\\S]*?)\\n[ \\t]*\\2\\s*$/);\n\treturn heredoc ? heredoc[3] : undefined;\n}\n\n/** `true` when `text` invokes a known shell with no `-c`, but feeds it a here-string or heredoc body. */\nfunction feedsBareShellViaHereDocOrString(text: string): boolean {\n\tconst trimmed = text.trim();\n\tconst tokens = tokenizeShellWords(trimmed);\n\tconst head = tokens[0];\n\tif (head === undefined || !SHELL_C_WRAPPERS.has(basenameOfHeadToken(head))) return false;\n\tif (extractShellBodyAfterDashC(trimmed, SHELL_C_WRAPPERS) !== undefined) return false;\n\treturn /<<<|<</.test(trimmed);\n}\n\n/** `true` when any `|`-joined segment pipes into a known shell with no `-c` (`echo ... | bash`). */\nfunction pipedIntoBareShell(segments: ChainSegment[]): boolean {\n\treturn segments.some((seg) => {\n\t\tif (seg.operator !== \"|\") return false;\n\t\tconst trimmed = seg.text.trim();\n\t\tconst tokens = tokenizeShellWords(trimmed);\n\t\tconst head = tokens[0];\n\t\tif (head === undefined || !SHELL_C_WRAPPERS.has(basenameOfHeadToken(head))) return false;\n\t\treturn extractShellBodyAfterDashC(trimmed, SHELL_C_WRAPPERS) === undefined;\n\t});\n}\n\n/**\n * `true` when `command` feeds a bare shell interpreter (`bash`, `sh`, `zsh`,\n * `dash`, `ksh`, `fish`) via a pipe, here-string, or heredoc, with no `-c`\n * flag. The deny scan can extract and check the piped/here-doc text (see\n * `scanDenyCandidates`), but can't prove the absence of danger the way a\n * plain unwrapped command can — so auto mode must never silently allow it.\n */\nfunction commandFeedsBareShellWithoutDashC(command: string): boolean {\n\tconst segments = splitChain(command);\n\tif (pipedIntoBareShell(segments)) return true;\n\treturn segments.some((seg) => feedsBareShellViaHereDocOrString(seg.text));\n}\n\n/**\n * Extracts the inner command line from a `pwsh -c \"...\"` / `powershell\n * -Command \"...\"` / `cmd /c \"...\"` style wrapper, if present. Accepts `-c`,\n * `-Command`, and `/c` case-insensitively, anywhere among the wrapper's\n * tokens, rather than the exact flag each shell prefers — for danger\n * detection, over-matching is the safe direction.\n */\nfunction extractOtherShellWrapperArg(text: string): string | undefined {\n\tconst trimmed = text.trim();\n\tif (!headIsOtherShellWrapper(trimmed)) return undefined;\n\tconst tokens = tokenizeShellWords(trimmed);\n\tfor (let i = 1; i < tokens.length - 1; i++) {\n\t\tconst token = tokens[i].toLowerCase();\n\t\tif (token === \"-c\" || token === \"-command\" || token === \"/c\") return tokens[i + 1];\n\t}\n\treturn undefined;\n}\n\n/**\n * Extracts the inner command line from an `eval \"...\"` / `eval '...'` /\n * `eval <unquoted words...>` wrapper, if present — bash's `eval` joins all of\n * its arguments with spaces and evaluates the result as a command, whether or\n * not they were quoted.\n */\nfunction extractEvalArg(text: string): string | undefined {\n\tconst trimmed = text.trim();\n\tconst quoted = trimmed.match(/^eval\\s+(['\"])([\\s\\S]*)\\1\\s*$/i);\n\tif (quoted) return quoted[2];\n\tconst unquoted = trimmed.match(/^eval\\s+(\\S[\\s\\S]*)$/i);\n\treturn unquoted ? unquoted[1] : undefined;\n}\n\n/** Extracts the contents of every `$(...)` and `` `...` `` command substitution found anywhere in `text`. */\nfunction extractSubstitutions(text: string): string[] {\n\tconst results: string[] = [];\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tif (text[i] === \"$\" && text[i + 1] === \"(\") {\n\t\t\tlet depth = 1;\n\t\t\tlet j = i + 2;\n\t\t\twhile (j < text.length && depth > 0) {\n\t\t\t\tif (text[j] === \"(\") depth++;\n\t\t\t\telse if (text[j] === \")\") depth--;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tresults.push(text.slice(i + 2, depth === 0 ? j - 1 : j));\n\t\t\ti = j;\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t}\n\tconst backtickMatches = text.match(/`([^`]*)`/g);\n\tif (backtickMatches) {\n\t\tfor (const m of backtickMatches) results.push(m.slice(1, -1));\n\t}\n\treturn results;\n}\n\n/**\n * Returns the literal output of a simple `echo ...` command. This covers a\n * substitution used as a command position, such as `$(echo rm -rf /)`, where\n * the output is subsequently executed by the outer shell.\n */\nfunction extractSimpleEchoOutput(text: string): string | undefined {\n\tconst match = text.match(/^\\s*echo\\s+([^$`]+?)\\s*$/i);\n\tif (!match) return undefined;\n\tconst captured = match[1];\n\tconst quoted = captured.match(/^(['\"])([\\s\\S]*)\\1$/);\n\treturn quoted ? quoted[2] : captured;\n}\n\nconst MAX_DENY_CANDIDATES = 50;\nconst MAX_DENY_DEPTH = 4;\n\ninterface DenyScanResult {\n\tcandidates: string[];\n\t/**\n\t * `true` when the candidate/depth cap cut the scan short before every\n\t * piece of `command` could be enumerated. Callers MUST treat a truncated\n\t * scan as \"unknown, not denied\" rather than \"not denied\" — see\n\t * `commandDenyScanTruncated` below.\n\t */\n\ttruncated: boolean;\n}\n\n/**\n * Paranoidly enumerates every independently-executed \"piece\" of `command` a\n * `deny` rule should be checked against: the raw command, each chained\n * segment, prefix/wrapper-stripped variants of each segment, and the bodies\n * of any `bash -c` / `eval` / `$(...)` / backtick constructs — recursively,\n * bounded so adversarial input can't cause unbounded work.\n *\n * The bound is itself a fail-safe surface: a command with more pieces or\n * wrapper layers than the cap allows must not be treated as \"scanned clean\".\n * `truncated` on the result flags exactly that case.\n */\nfunction scanDenyCandidates(command: string): DenyScanResult {\n\tconst seen = new Set<string>();\n\tconst queue: Array<{ text: string; depth: number }> = [{ text: command, depth: 0 }];\n\tlet truncated = false;\n\n\twhile (queue.length > 0) {\n\t\tif (seen.size >= MAX_DENY_CANDIDATES) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst next = queue.shift();\n\t\tif (!next) break;\n\t\tconst { text, depth } = next;\n\t\tif (seen.has(text)) continue;\n\t\tseen.add(text);\n\t\tif (depth >= MAX_DENY_DEPTH) {\n\t\t\ttruncated = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst enqueue = (candidate: string) => {\n\t\t\tif (seen.has(candidate)) return;\n\t\t\tif (seen.size + queue.length >= MAX_DENY_CANDIDATES) {\n\t\t\t\ttruncated = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tqueue.push({ text: candidate, depth: depth + 1 });\n\t\t};\n\n\t\tconst segmentObjs = splitChain(text);\n\t\tconst segments = segmentObjs.map((s) => s.text);\n\t\tconst pieces = segments.length > 1 ? segments : [text];\n\t\tfor (const seg of segments) enqueue(seg);\n\n\t\tfor (let i = 0; i < segmentObjs.length; i++) {\n\t\t\tif (segmentObjs[i].operator !== \"|\") continue;\n\t\t\tconst prevText = segmentObjs[i - 1]?.text;\n\t\t\tif (prevText === undefined) continue;\n\t\t\tconst echoOutput = extractSimpleEchoOutput(prevText);\n\t\t\tif (echoOutput !== undefined) enqueue(echoOutput);\n\t\t}\n\n\t\tfor (const piece of pieces) {\n\t\t\tlet working = stripLeadingBackslashEscape(piece);\n\t\t\tworking = stripEnvAssignments(working);\n\t\t\tconst beforeWrapperStrip = working;\n\t\t\tfor (let guard = 0; guard < 5; guard++) {\n\t\t\t\tconst { stripped, changed } = stripPassthroughPrefix(working);\n\t\t\t\tif (!changed) break;\n\t\t\t\tworking = stripped;\n\t\t\t}\n\t\t\tenqueue(working);\n\n\t\t\tconst basenameResolved = resolveBasenameOfFirstToken(working);\n\t\t\tenqueue(basenameResolved);\n\n\t\t\tconst shellC =\n\t\t\t\textractShellBodyAfterDashC(working, SHELL_C_WRAPPERS) ??\n\t\t\t\textractShellBodyAfterDashC(basenameResolved, SHELL_C_WRAPPERS);\n\t\t\tif (shellC !== undefined) enqueue(shellC);\n\n\t\t\tconst hereRedirect = extractHereStringOrHeredocPayload(piece);\n\t\t\tif (hereRedirect !== undefined) enqueue(hereRedirect);\n\n\t\t\tconst otherShellArg = extractOtherShellWrapperArg(working) ?? extractOtherShellWrapperArg(basenameResolved);\n\t\t\tif (otherShellArg !== undefined) enqueue(otherShellArg);\n\n\t\t\tconst evalArg = extractEvalArg(working) ?? extractEvalArg(basenameResolved);\n\t\t\tif (evalArg !== undefined) enqueue(evalArg);\n\n\t\t\tconst findExecArg = extractFindExecArg(working) ?? extractFindExecArg(basenameResolved);\n\t\t\tif (findExecArg !== undefined) enqueue(findExecArg);\n\n\t\t\tconst envSplitStringArg = extractEnvSplitStringArg(beforeWrapperStrip);\n\t\t\tif (envSplitStringArg !== undefined) enqueue(envSplitStringArg);\n\n\t\t\tfor (const sub of extractSubstitutions(piece)) {\n\t\t\t\tenqueue(sub);\n\t\t\t\tconst echoOutput = extractSimpleEchoOutput(sub);\n\t\t\t\tif (echoOutput !== undefined) enqueue(echoOutput);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { candidates: [...seen], truncated };\n}\n\n/** Candidate list only, for callers that don't need the truncation flag. */\nfunction collectDenyCandidates(command: string): string[] {\n\treturn scanDenyCandidates(command).candidates;\n}\n\n/**\n * `true` when `command` has more chained pieces or wrapper layers than\n * `scanDenyCandidates` could fully enumerate. A truncated scan can never be\n * trusted to say \"no deny/danger match\" — the unscanned remainder might hide\n * one — so callers must fail closed (deny or require approval) rather than\n * fall through to an auto-allow default.\n */\nfunction commandDenyScanTruncated(command: string): boolean {\n\treturn scanDenyCandidates(command).truncated;\n}\n\n/**\n * Raw first whitespace-delimited token of `text`, with at most one matching\n * pair of surrounding quotes stripped — deliberately *not* run through\n * `tokenizeShellWords`'s backslash-escape collapsing, so a literal Windows\n * path separator (`C:\\Windows\\System32\\cmd.exe`) survives for\n * `basenameOfHeadToken` to split on, instead of being eaten as a POSIX\n * shell escape character.\n */\nfunction rawFirstToken(text: string): string | undefined {\n\tconst token = text.trimStart().match(/^\\S+/)?.[0];\n\tif (token === undefined) return undefined;\n\tconst quoted = token.match(/^(['\"])([\\s\\S]*)\\1$/);\n\treturn quoted ? quoted[2] : token;\n}\n\n/**\n * `true` when `basename(head(text))` is a recognized `pwsh`/`powershell`/\n * `cmd` spelling, checking both the POSIX-escape-aware token (`p\\wsh` ->\n * `pwsh`) and the raw token (`C:\\Windows\\...\\cmd.exe` -> `cmd`), since the\n * two normalizations disagree on what a bare `\\` means.\n */\nfunction headIsOtherShellWrapper(text: string): boolean {\n\tconst dequotedHead = tokenizeShellWords(text.trimStart())[0];\n\tif (dequotedHead !== undefined && isOtherShellWrapperName(basenameOfHeadToken(dequotedHead))) return true;\n\tconst raw = rawFirstToken(text);\n\treturn raw !== undefined && isOtherShellWrapperName(basenameOfHeadToken(raw));\n}\n\n/**\n * `true` when `command` (bash tool) invokes `pwsh`/`powershell`/`cmd` at any\n * unwrapped layer, e.g. `pwsh -c \"Remove-Item -Recurse ~\"` or\n * `bash -c \"cmd /c del ...\"`. Auto mode's danger filter\n * (`DANGEROUS_COMMAND_PATTERNS`) is bash-shaped and has no coverage for these\n * interpreters' own syntax, the same reason unmatched `powershell` tool calls\n * always require approval — so a bash-tool call that merely shells out to one\n * of them must not get a free pass auto mode never meant to give it.\n */\nfunction commandInvokesOtherShell(command: string): boolean {\n\treturn collectDenyCandidates(command).some((candidate) => headIsOtherShellWrapper(candidate));\n}\n\n/** A shell variable/parameter expansion, command substitution, or backtick substitution in command position. */\nfunction isDynamicCommandHead(token: string): boolean {\n\treturn /^(\\$\\(|\\$\\{|\\$[A-Za-z_]|`)/.test(token);\n}\n\n/**\n * `true` when any chain segment's command position (after stripping leading\n * `VAR=val` assignments) is a variable/expansion rather than a literal\n * command name (`$p`, `${HOME:+pwsh}`, `$(...)`, a backtick substitution).\n * What actually runs then depends on the environment, so no pattern — deny,\n * danger filter, or interpreter check — can reason about it; auto mode must\n * require approval instead of silently resolving to whatever the variable\n * happens to hold.\n */\nfunction commandHeadIsDynamic(command: string): boolean {\n\treturn splitChain(command).some((seg) => {\n\t\tconst working = stripEnvAssignments(stripLeadingBackslashEscape(seg.text));\n\t\tconst head = tokenizeShellWords(working.trim())[0];\n\t\treturn head !== undefined && isDynamicCommandHead(head);\n\t});\n}\n\n/** Extracts the `<cmd>` from `find ... -exec <cmd> ... ;`/`+`/`-execdir <cmd> ... ;`, if present. */\nfunction extractFindExecArg(text: string): string | undefined {\n\tconst tokens = tokenizeShellWords(text.trim());\n\tconst head = tokens[0];\n\tif (head === undefined || basenameOfHeadToken(head) !== \"find\") return undefined;\n\tconst execIndex = tokens.findIndex((token) => token === \"-exec\" || token === \"-execdir\");\n\tif (execIndex === -1) return undefined;\n\tconst cmdTokens: string[] = [];\n\tfor (let i = execIndex + 1; i < tokens.length; i++) {\n\t\tconst token = tokens[i];\n\t\tif (token === \";\" || token === \"+\") break;\n\t\tcmdTokens.push(token);\n\t}\n\treturn cmdTokens.length > 0 ? cmdTokens.join(\" \") : undefined;\n}\n\n/** Extracts `env -S '<cmd>'` / `env --split-string '<cmd>'`'s argument, which `env` itself parses as a command line. */\nfunction extractEnvSplitStringArg(text: string): string | undefined {\n\tconst tokens = tokenizeShellWords(text.trim());\n\tconst head = tokens[0];\n\tif (head === undefined || basenameOfHeadToken(head) !== \"env\") return undefined;\n\tfor (let i = 1; i < tokens.length; i++) {\n\t\tif (tokens[i] === \"-S\" || tokens[i] === \"--split-string\") return tokens[i + 1];\n\t}\n\treturn undefined;\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = \"\";\n\tfor (const ch of pattern) {\n\t\tif (ch === \"*\") source += \".*\";\n\t\telse if (ch === \"?\") source += \".\";\n\t\telse source += ch.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\t}\n\treturn new RegExp(`^${source}$`, \"is\");\n}\n\nfunction matchDenyPattern(command: string, pattern: string): boolean {\n\tconst candidates = collectDenyCandidates(command);\n\tconst flagPattern = parseFlagClusterPattern(pattern);\n\tif (\n\t\tflagPattern !== undefined &&\n\t\tcandidates.some((candidate) => flagClusterPatternMatchesCandidate(flagPattern, candidate))\n\t) {\n\t\treturn true;\n\t}\n\tconst regex = globToRegExp(normalizeForMatch(pattern));\n\treturn candidates.some((candidate) => regex.test(normalizeForMatch(candidate)));\n}\n\n/**\n * Strictly matches `command` against an `allow`/`approve` `pattern`: any\n * dynamic/opaque construct disqualifies the match outright, and the command\n * must have the same chain shape (segment count and operators) as the\n * pattern, with every segment matching independently. This is what stops a\n * rule like `{ pattern: \"npm test*\", action: \"allow\" }` from also\n * authorizing `npm test; rm -rf /` or `` npm test `rm -rf /` ``.\n */\nfunction matchAllowPattern(command: string, pattern: string): boolean {\n\tif (DANGEROUS_CONSTRUCT_RE.test(command)) return false;\n\n\tconst commandSegments = splitChain(command);\n\tconst patternSegments = splitChain(pattern);\n\tif (commandSegments.length !== patternSegments.length) return false;\n\n\tfor (let i = 0; i < commandSegments.length; i++) {\n\t\tif (commandSegments[i].operator !== patternSegments[i].operator) return false;\n\t\tconst cmdText = normalizeForMatch(commandSegments[i].text);\n\t\tconst cmdResolved = normalizeForMatch(resolveBasenameOfFirstToken(commandSegments[i].text));\n\t\tconst regex = globToRegExp(normalizeForMatch(patternSegments[i].text));\n\t\tif (!regex.test(cmdText) && !regex.test(cmdResolved)) return false;\n\t}\n\treturn true;\n}\n\nfunction matchCommandPattern(command: string, pattern: string, action: PermissionAction): boolean {\n\treturn action === \"deny\" ? matchDenyPattern(command, pattern) : matchAllowPattern(command, pattern);\n}\n\n/**\n * Built-in danger filter backing `auto` mode. These are matched with the\n * same paranoid strategy as `deny` rules (chain splitting, wrapper\n * unwrapping, substitution extraction), so `echo hi && rm -rf /` or\n * `bash -c \"sudo dd ...\"` still trip the filter.\n *\n * This is a *prompt* heuristic, not a security boundary: it decides which\n * unmatched commands fall back to approval instead of auto-allow. It can\n * never enumerate every destructive command — anything that must be hard\n * blocked belongs in a `deny` rule in `permissions.yml`.\n */\nexport const DANGEROUS_COMMAND_PATTERNS: readonly string[] = [\n\t// recursive/forced deletion (flag clusters normalize to sorted letters,\n\t// so `-rf`/`-fr` become `-fr` and are caught by the `-f*` prefix; bare\n\t// `-r`/`-R` by the `-r*` prefix via case-insensitive matching)\n\t\"rm -r*\",\n\t\"rm -f*\",\n\t// privilege escalation\n\t\"sudo *\",\n\t\"doas *\",\n\t\"su *\",\n\t// raw disk / filesystem surgery\n\t\"dd *\",\n\t\"mkfs*\",\n\t// system state\n\t\"shutdown*\",\n\t\"reboot*\",\n\t\"halt*\",\n\t\"poweroff*\",\n\t// blanket permission changes\n\t\"chmod 777 *\",\n\t\"chmod -R *\",\n\t\"chown -R *\",\n\t// outward-facing / history-rewriting git and publishing\n\t\"git push*\",\n\t\"git reset --hard*\",\n\t\"git clean*\",\n\t\"npm publish*\",\n\t\"yarn publish*\",\n\t\"pnpm publish*\",\n\t// pipe-to-shell installers\n\t\"curl * | *\",\n\t\"wget * | *\",\n\t// inline interpreter eval — the code payload is another language the gate\n\t// cannot parse, so `python -c \"os.system('rm -rf /')\"` would otherwise\n\t// sail through as \"not shell-dangerous\". Running a script *file*\n\t// (`python script.py`) is deliberately NOT flagged: it is everyday dev\n\t// work, and the gate cannot see file contents anyway (see the module doc\n\t// on interpreter escape hatches).\n\t\"python* -c*\",\n\t\"node -e*\",\n\t\"node --eval*\",\n\t\"node -p*\",\n\t\"bun -e*\",\n\t\"bun --eval*\",\n\t\"deno eval*\",\n\t\"ruby -e*\",\n\t\"perl -e*\",\n\t\"php -r*\",\n];\n\n/**\n * Returns the first built-in dangerous pattern the command matches, or\n * `undefined` if the command passes the filter.\n */\nexport function findDangerousPattern(command: string): string | undefined {\n\treturn DANGEROUS_COMMAND_PATTERNS.find((pattern) => matchDenyPattern(command, pattern));\n}\n\n/** Normalize a (possibly relative or absolute) path into a forward-slash path relative to `cwd`, for glob matching. */\nfunction toMatchablePath(filePath: string, cwd: string): string {\n\tconst resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\tconst rel = relative(cwd, resolved);\n\treturn rel.split(sep).join(\"/\");\n}\n\n/** Whether `filePath` (relative or absolute) resolves to a location inside `cwd`. */\nfunction isWithinProject(filePath: string, cwd: string): boolean {\n\tconst resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\tconst rel = relative(cwd, resolved);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\n/**\n * NOTE: this assumes the tool-call args carry a `command` string under the\n * exact key `command`. If/when this gate is wired into actual tool\n * dispatch, verify every gated tool's argument shape matches these\n * hardcoded key names — a mismatch doesn't error, it just silently fails to\n * match any `pattern`/`paths` rule and falls through to the (fail-safe)\n * default decision. Not currently exploitable: nothing outside this module\n * and its test calls `PermissionGate`/`loadRules` yet.\n */\nfunction getCommandArg(args: Record<string, unknown>): string | undefined {\n\treturn typeof args.command === \"string\" ? args.command : undefined;\n}\n\n/** Prefers `file_path` over `path` when both are present; see the note on `getCommandArg` above. */\nfunction getPathArg(args: Record<string, unknown>): string | undefined {\n\tif (typeof args.file_path === \"string\") return args.file_path;\n\tif (typeof args.path === \"string\") return args.path;\n\treturn undefined;\n}\n\nfunction describeMatch(rule: PermissionRule): string {\n\tconst parts = [`tool=${rule.tool}`];\n\tif (rule.pattern !== undefined) parts.push(`pattern=${JSON.stringify(rule.pattern)}`);\n\tif (rule.paths !== undefined) parts.push(`paths=${JSON.stringify(rule.paths)}`);\n\treturn `matched rule (${parts.join(\", \")}) -> ${rule.action}`;\n}\n\n/**\n * A `tool: bash` rule's `pattern` is authored against bash command shapes, so\n * only its `deny` half is safe to reuse for `powershell` calls: a bash `deny`\n * over-matching onto a powershell command is the fail-safe direction, while a\n * bash `allow`/`approve` pattern (e.g. `ls *`) under-matching real\n * powershell syntax would otherwise create the illusion of coverage without\n * actually vetting powershell-specific danger. `tool: powershell` rules\n * (and `tool: \"*\"`) are unaffected and keep matching normally.\n */\nfunction bashDenyRuleAppliesToPowershell(rule: PermissionRule, toolName: string): boolean {\n\treturn toolName === \"powershell\" && rule.tool.toLowerCase() === \"bash\" && rule.action === \"deny\";\n}\n\nfunction toolMatchesRule(rule: PermissionRule, toolName: string): boolean {\n\treturn rule.tool === \"*\" || rule.tool.toLowerCase() === toolName || bashDenyRuleAppliesToPowershell(rule, toolName);\n}\n\nfunction ruleMatches(rule: PermissionRule, toolName: string, args: Record<string, unknown>, cwd: string): boolean {\n\tif (!toolMatchesRule(rule, toolName)) return false;\n\n\tif (rule.pattern !== undefined) {\n\t\tconst command = getCommandArg(args);\n\t\tif (command === undefined || !matchCommandPattern(command, rule.pattern, rule.action)) return false;\n\t}\n\n\tif (rule.paths !== undefined) {\n\t\tconst filePath = getPathArg(args);\n\t\tif (filePath === undefined) return false;\n\t\tconst matchable = toMatchablePath(filePath, cwd);\n\t\tif (!rule.paths.some((pattern) => minimatch(matchable, pattern, { dot: true }))) return false;\n\t}\n\n\treturn true;\n}\n\nexport interface PermissionGateOptions {\n\t/** Project root used to determine whether a path is \"within the project\" for default decisions. Defaults to `process.cwd()`. */\n\tcwd?: string;\n\t/** Session permission mode; see `PermissionMode`. Defaults to `\"default\"`. */\n\tmode?: PermissionMode;\n}\n\n/**\n * Evaluates tool calls against an ordered list of permission rules,\n * returning a `deny` / `allow` / `approve` decision.\n */\nexport class PermissionGate {\n\tprivate readonly rules: PermissionRule[];\n\tprivate readonly cwd: string;\n\tprivate readonly mode: PermissionMode;\n\n\tconstructor(rules: PermissionRule[] = [], options: PermissionGateOptions = {}) {\n\t\tthis.rules = rules;\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.mode = options.mode ?? \"default\";\n\t}\n\n\t/** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */\n\tevaluate(toolName: string, args: Record<string, unknown> = {}): PermissionDecision {\n\t\tconst normalizedTool = toolName.toLowerCase();\n\n\t\tif (normalizedTool === \"bash\" || normalizedTool === \"powershell\") {\n\t\t\tconst command = getCommandArg(args);\n\t\t\tif (command !== undefined && commandDenyScanTruncated(command)) {\n\t\t\t\tconst denyRuleApplies = this.rules.some(\n\t\t\t\t\t(rule) => rule.action === \"deny\" && toolMatchesRule(rule, normalizedTool),\n\t\t\t\t);\n\t\t\t\tif (denyRuleApplies) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"deny\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"command has more chained/wrapped pieces than the deny scan can fully cover, and a deny rule applies to this tool; failing closed rather than risk missing a match\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const rule of this.rules) {\n\t\t\tif (ruleMatches(rule, normalizedTool, args, this.cwd)) {\n\t\t\t\treturn this.applyMode({ action: rule.action, reason: describeMatch(rule) });\n\t\t\t}\n\t\t}\n\n\t\treturn this.applyMode(this.defaultDecision(normalizedTool, args));\n\t}\n\n\t/**\n\t * Applies the session mode to a decision. `deny` is never relaxed by any\n\t * mode; `yolo` downgrades every `approve` to `allow`.\n\t */\n\tprivate applyMode(decision: PermissionDecision): PermissionDecision {\n\t\tif (this.mode === \"yolo\" && decision.action === \"approve\") {\n\t\t\treturn { action: \"allow\", reason: `yolo mode: auto-allowed (${decision.reason})` };\n\t\t}\n\t\treturn decision;\n\t}\n\n\tprivate defaultDecision(toolName: string, args: Record<string, unknown>): PermissionDecision {\n\t\tif (DEFAULT_ALLOWED_TOOLS.has(toolName)) {\n\t\t\treturn { action: \"allow\", reason: `no rule matched; \"${toolName}\" is allowed by default` };\n\t\t}\n\n\t\tif (toolName === \"bash\") {\n\t\t\tif (this.mode === \"auto\") {\n\t\t\t\tconst command = getCommandArg(args);\n\t\t\t\tif (command === undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason: \"auto mode: bash call without a command string requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst dangerous = findDangerousPattern(command);\n\t\t\t\tif (dangerous !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason: `auto mode: command matched dangerous pattern ${JSON.stringify(dangerous)}, requires approval`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandHeadIsDynamic(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command position is a variable/parameter expansion, command substitution, or backtick substitution, which can resolve to anything; requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandInvokesOtherShell(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command invokes a pwsh/powershell/cmd interpreter, which the bash-shaped danger filter has no coverage for; requires approval, same as the powershell tool\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandDenyScanTruncated(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command has more chained/wrapped pieces than the deny scan can fully cover, requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandFeedsBareShellWithoutDashC(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"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\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { action: \"allow\", reason: \"auto mode: no rule matched and command passed the danger filter\" };\n\t\t\t}\n\t\t\treturn { action: \"approve\", reason: \"no rule matched; bash commands require approval by default\" };\n\t\t}\n\n\t\tif (toolName === \"powershell\") {\n\t\t\t// Unlike bash, powershell has no danger filter tuned for its own\n\t\t\t// syntax (DANGEROUS_COMMAND_PATTERNS is bash-shaped), so auto mode\n\t\t\t// cannot safely auto-allow it — every unmatched powershell call\n\t\t\t// requires approval in default and auto mode (yolo's applyMode still\n\t\t\t// turns this approve into allow, as for every tool).\n\t\t\treturn { action: \"approve\", reason: \"no rule matched; powershell commands always require approval\" };\n\t\t}\n\n\t\tif (PATH_SCOPED_TOOLS.has(toolName)) {\n\t\t\tconst filePath = getPathArg(args);\n\t\t\tif (filePath !== undefined && isWithinProject(filePath, this.cwd)) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project (or missing), requires approval\",\n\t\t\t};\n\t\t}\n\n\t\tif (READ_ONLY_PATH_TOOLS.has(toolName)) {\n\t\t\t// Unlike read/write/edit, these tools treat a missing `path` as the\n\t\t\t// cwd, so an absent path arg is within the project by definition.\n\t\t\tconst filePath = getPathArg(args) ?? \".\";\n\t\t\tif (isWithinProject(filePath, this.cwd)) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; read-only tool allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project, requires approval\",\n\t\t\t};\n\t\t}\n\n\t\treturn { action: \"approve\", reason: `no rule matched for tool \"${toolName}\"; defaults to approve` };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"permission-gate.js","sourceRoot":"","sources":["../../../src/core/multi-agent/permission-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAuBtD,sEAAsE;AACtE,MAAM,CAAC,MAAM,gBAAgB,GAA8B,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAEnF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAoC,MAAM,CAAC;AAEvF,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAK,gBAAsC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC7F,CAAC;AAED,4CAA4C;AAC5C,MAAM,UAAU,sBAAsB,CAAC,CAAiB,EAAE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AC;QACH,CAAC;QAED,IAAI,oBAAoB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxC,oEAAoE;YACpE,kEAAkE;YAClE,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;YACpC,MAAM,QAAQ,GAAG,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAC1D,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBACvE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,uEAAuE,EAAE,CAAC;YAC7G,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,SAAS;gBACjB,MAAM,EAAE,iEAAiE;aACzE,CAAC;QACH,CAAC;QAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,6BAA6B,QAAQ,wBAAwB,EAAE,CAAC;IACrG,CAAC;CACD","sourcesContent":["/**\n * Permission gate: a three-tier permission system that decides whether a\n * tool call may proceed automatically, must be blocked, or must be confirmed\n * by the user before it runs.\n *\n * SECURITY-CRITICAL: this module gates real bash/write tool calls. Prefer\n * fail-safe (approve/deny) over fail-open (allow) whenever a decision is\n * ambiguous.\n *\n * Configuration is read from `.draht/permissions.yml` (project) and\n * `~/.draht/agent/permissions.yml` (global), e.g.:\n *\n * ```yaml\n * rules:\n * - tool: bash\n * pattern: \"rm -rf *\"\n * action: deny\n * - tool: bash\n * pattern: \"git push *\"\n * action: approve\n * - tool: read\n * action: allow\n * - tool: write\n * paths: [\"src/**\"]\n * action: allow\n * - tool: write\n * action: approve\n * ```\n *\n * Rules are evaluated top-to-bottom; the first matching rule wins.\n *\n * On top of the rules sits a session-level `PermissionMode` (`ask` /\n * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and\n * `approve` outcomes are handled — `deny` rules are never relaxed.\n *\n * `pattern` matching against bash commands is textual (no real shell\n * parser), so `deny` and `allow`/`approve` patterns are matched with\n * deliberately asymmetric strategies to stay fail-safe: `deny` scans every\n * chained/wrapped/unwrapped piece of the command it can find, plus every\n * command a shell-aware read finds the shell runs (`collectDenyCandidates`;\n * paranoid, over-matching is safe), while `allow`/`approve` require an exact\n * chain-shape match and reject anything containing `$(...)`, backticks, or\n * redirection (strict, under-matching just falls through to the default\n * decision instead of silently authorizing more than intended). See the\n * doc comment on `matchCommandPattern` below for details and known limits —\n * in particular, `pattern` can never guarantee real path containment; use\n * `paths` for that.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { minimatch } from \"minimatch\";\nimport { parse } from \"yaml\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.ts\";\nimport { resolveToCwd } from \"../tools/path-utils.ts\";\n\n/** The three permission tiers a rule (or default) can resolve to. */\nexport type PermissionAction = \"deny\" | \"allow\" | \"approve\";\n\n/**\n * Session-level permission mode. Modes only relax the gate's *default*\n * decisions — explicit rules from `permissions.yml` always win first:\n *\n * - `ask`: rules as authored; unmatched bash/powershell requires approval.\n * - `auto`: unmatched bash is auto-allowed unless it trips the built-in\n * danger filter (`DANGEROUS_COMMAND_PATTERNS`), in which case it still\n * requires approval. `powershell` is excluded from this auto-allow — the\n * danger filter is bash-shaped and has no powershell-specific coverage, so\n * unmatched powershell calls always require approval, even in auto mode.\n * Unmatched `AUTO_ALLOWED_DELEGATION_TOOLS` calls are auto-allowed too.\n * Explicit `deny`/`approve` rules behave as authored.\n * - `yolo`: every `approve` (rule-based or default) is downgraded to\n * `allow`. Explicit `deny` rules still block — yolo is \"stop asking\",\n * not \"disable the gate\".\n */\nexport type PermissionMode = \"ask\" | \"auto\" | \"yolo\";\n\n/** Strictest first: `stricterPermissionMode` relies on this order. */\nexport const PERMISSION_MODES: readonly PermissionMode[] = [\"ask\", \"auto\", \"yolo\"];\n\n/**\n * The mode a session starts in when `DRAHT_PERMISSION_MODE` names none. A `PermissionGate`\n * constructed without a mode still uses `ask`, the strictest, so a caller that forgets to\n * pass the session's mode never gets a laxer gate than the session has. Never `yolo`: `/yolo`\n * switches back to this mode when nothing else was chosen.\n */\nexport const DEFAULT_SESSION_PERMISSION_MODE: Exclude<PermissionMode, \"yolo\"> = \"auto\";\n\nexport function isPermissionMode(value: unknown): value is PermissionMode {\n\treturn typeof value === \"string\" && (PERMISSION_MODES as readonly string[]).includes(value);\n}\n\n/** Whichever of the two modes asks more. */\nexport function stricterPermissionMode(a: PermissionMode, b: PermissionMode): PermissionMode {\n\treturn PERMISSION_MODES.indexOf(a) <= PERMISSION_MODES.indexOf(b) ? a : b;\n}\n\n/** A single permission rule as authored in `permissions.yml`. */\nexport interface PermissionRule {\n\t/** Tool identifier this rule applies to (e.g. \"bash\", \"read\", \"write\", \"edit\"), or \"*\" for any tool. */\n\ttool: string;\n\t/** Glob pattern matched against the bash command string (only meaningful for tools with a `command` arg). */\n\tpattern?: string;\n\t/** Glob patterns matched against the file path (only meaningful for tools with a `path`/`file_path` arg). */\n\tpaths?: string[];\n\t/** The action to take when this rule matches. */\n\taction: PermissionAction;\n}\n\n/** The result of evaluating a tool call against the permission rules. */\nexport interface PermissionDecision {\n\taction: PermissionAction;\n\treason: string;\n}\n\nconst VALID_ACTIONS: readonly PermissionAction[] = [\"deny\", \"allow\", \"approve\"];\nconst RULES_FILE_NAME = \"permissions.yml\";\nconst PATH_SCOPED_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n/** Read-only tools whose optional `path` arg defaults to the cwd when omitted. */\nconst READ_ONLY_PATH_TOOLS = new Set([\"grep\", \"find\", \"ls\"]);\n/**\n * Tools that are safe to run without confirmation because the call itself\n * only delegates: spawned child processes run this same gate over every tool\n * call they actually make. Explicit rules can still `deny`/`approve` these.\n * Workflows and duet batches are deliberately not included because they fan\n * out paid model requests; see `AUTO_ALLOWED_DELEGATION_TOOLS`.\n *\n * `polyphase_result` is also allowed by default: it returns a value to the parent workflow; no\n * side effects; children have no UI to approve it.\n */\nconst DEFAULT_ALLOWED_TOOLS = new Set([\"subagent\", \"polyphase_result\"]);\n/**\n * Delegating tools that fan out paid model requests: a workflow run and a duet batch. Like\n * `DEFAULT_ALLOWED_TOOLS`, they only start child processes that run this same gate over every\n * tool call they make, so `auto` mode starts them without asking; `ask` mode asks first,\n * for the spend. Explicit rules can still `deny`/`approve` these.\n */\nconst AUTO_ALLOWED_DELEGATION_TOOLS = new Set([\"workflow\", \"duet_delegate\"]);\n\nfunction isPermissionAction(value: unknown): value is PermissionAction {\n\treturn typeof value === \"string\" && (VALID_ACTIONS as readonly string[]).includes(value);\n}\n\nfunction validateRule(raw: unknown, index: number): PermissionRule {\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} must be an object`);\n\t}\n\tconst record = raw as Record<string, unknown>;\n\n\tif (typeof record.tool !== \"string\" || record.tool.length === 0) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} is missing a valid \"tool\" field`);\n\t}\n\tif (!isPermissionAction(record.action)) {\n\t\tthrow new Error(\n\t\t\t`permissions.yml: rule at index ${index} has an invalid \"action\" (must be one of ${VALID_ACTIONS.join(\", \")})`,\n\t\t);\n\t}\n\n\tconst rule: PermissionRule = { tool: record.tool, action: record.action };\n\n\tif (record.pattern !== undefined) {\n\t\tif (typeof record.pattern !== \"string\") {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has a non-string \"pattern\"`);\n\t\t}\n\t\trule.pattern = record.pattern;\n\t}\n\n\tif (record.paths !== undefined) {\n\t\tif (!Array.isArray(record.paths) || !record.paths.every((entry) => typeof entry === \"string\")) {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has an invalid \"paths\" (must be a string array)`);\n\t\t}\n\t\trule.paths = record.paths as string[];\n\t}\n\n\treturn rule;\n}\n\n/**\n * Parse a `permissions.yml` document (as a string) into an ordered list of\n * rules. Returns an empty array for empty documents or documents without a\n * `rules` key. Throws on malformed rule entries so misconfiguration fails\n * loudly rather than silently degrading the gate.\n */\nexport function parseRules(yamlText: string): PermissionRule[] {\n\tconst parsed = parse(yamlText) as { rules?: unknown } | null | undefined;\n\tif (parsed === null || parsed === undefined) return [];\n\tif (parsed.rules === undefined) return [];\n\tif (!Array.isArray(parsed.rules)) {\n\t\tthrow new Error('permissions.yml: \"rules\" must be an array');\n\t}\n\treturn parsed.rules.map((raw, index) => validateRule(raw, index));\n}\n\nfunction readRulesFile(filePath: string): PermissionRule[] {\n\tif (!existsSync(filePath)) return [];\n\treturn parseRules(readFileSync(filePath, \"utf-8\"));\n}\n\n/**\n * Load and merge permission rules from the global (`~/.draht/agent/permissions.yml`)\n * and project (`<projectDir>/.draht/permissions.yml`) config files.\n *\n * Loading order: global is read first, project is read after (so a project\n * can be authored as a delta on top of the global defaults). Merge order is\n * reversed relative to load order: project rules are placed *before* global\n * rules in the returned array, so that under first-match-wins evaluation the\n * project's rules take precedence over — i.e. \"override\" — the global ones.\n */\nexport function loadRules(projectDir?: string, globalDir?: string): PermissionRule[] {\n\tconst globalRulesPath = join(globalDir ?? getAgentDir(), RULES_FILE_NAME);\n\tconst projectRulesPath = join(projectDir ?? process.cwd(), CONFIG_DIR_NAME, RULES_FILE_NAME);\n\n\tconst globalRules = readRulesFile(globalRulesPath);\n\tconst projectRules = readRulesFile(projectRulesPath);\n\n\treturn [...projectRules, ...globalRules];\n}\n\n/**\n * Bash `pattern` matching against the raw command string can never be more\n * than textual — it has no real shell parser behind it. A previous\n * implementation matched the whole command string against the pattern with\n * minimatch after stripping every \"/\" (to stop \"*\" from being blocked by\n * minimatch's path-segment semantics). That was trivially bypassed: any\n * prefix at all (a leading space, `sudo`, `/bin/`, `env`, chaining with `;`\n * or `&&`, wrapping in `bash -c \"...\"`, double spaces, reordered combined\n * flags like `-fr` vs `-rf`, or different case) defeated the anchored match,\n * and — separately — a trailing-wildcard *allow* rule like\n * `{ pattern: \"npm test*\", action: \"allow\" }` matched anything appended\n * after it via `;`, `&&`, `|`, backticks, or `$(...)`, silently\n * auto-approving injected commands.\n *\n * To stay fail-safe rather than fail-open, `deny` and `allow`/`approve` are\n * matched with deliberately different, asymmetric strategies:\n *\n * - `deny` is matched *paranoidly*. The command is decomposed into every\n * independently-executed piece we can find — split on chaining operators\n * (`;`, `&&`, `||`, `|`, `&`, newlines); unwrapped from passthrough\n * prefixes (`sudo`, `env`, `nice`, ...) and leading `VAR=val`\n * assignments; unwrapped from `bash -c \"...\"` / `sh -c '...'` / `eval\n * \"...\"`; unwrapped from `$(...)`/backtick substitutions; resolved from\n * an absolute/relative path to a bare command name — recursively, up to\n * a bounded depth/count. The pattern matches if *any* resulting\n * candidate matches, after collapsing whitespace and canonicalizing\n * combined short flags (so `-rf`/`-fr` compare equal), case-insensitively.\n * Over-matching here is the safe failure mode.\n * - `allow`/`approve` are matched *strictly*: the command is rejected\n * outright if it contains any dynamic/opaque construct (`$(...)`,\n * backticks, redirection `<`/`>`), and otherwise must have the exact same\n * chain shape (same number of segments joined by the same operators) as\n * the pattern, with each segment matched independently. A rule authored\n * for `npm test*` therefore can never also authorize\n * `npm test; rm -rf /` — the extra chained segment has no counterpart in\n * the pattern, so the rule simply doesn't match (falling through to the\n * default decision) instead of silently allowing it.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): interpreter\n * escape hatches. Once a command hands control to a language runtime, the\n * payload is no longer shell and no shell-shaped pattern — `deny` rules\n * included — can see into it: `python -c \"os.system('rm -rf /')\"` never\n * surfaces `rm -rf /` as a match candidate, `python script.py` hides the\n * danger in file contents the gate never reads, and\n * `python -c \"shutil.rmtree('/')\"` involves no shell command at all. The\n * built-in danger filter flags *inline eval* invocations (`python -c`,\n * `node -e`, ...) so auto mode prompts on them, but script files and\n * in-language equivalents are out of reach by construction. The gate is a\n * guard against a confused agent, not a confinement boundary for a\n * malicious one — a hard boundary needs OS-level sandboxing of the bash\n * tool itself (Seatbelt/Landlock-style), not better string matching.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): `pattern` cannot\n * enforce real directory containment. A rule like\n * `{ pattern: \"cat /safe/dir/*\", action: \"allow\" }` will still match\n * `cat /safe/dir/../../../etc/passwd`, because from a glob's point of view\n * `..` is just more characters absorbed by the trailing `*` — there is no\n * shell/path awareness in a plain string pattern. Use the `paths` mechanism\n * (which resolves real paths via `resolve`/`relative`, see `toMatchablePath`\n * below) instead of `pattern` whenever a rule needs to be scoped to a\n * directory; don't rely on `pattern` for path containment.\n */\n\n/** Command names that merely forward to another command without changing what ultimately runs. */\nconst PASSTHROUGH_PREFIXES = new Set([\n\t\"sudo\",\n\t\"doas\",\n\t\"command\",\n\t\"exec\",\n\t\"nice\",\n\t\"nohup\",\n\t\"env\",\n\t\"time\",\n\t\"stdbuf\",\n\t\"ionice\",\n\t\"chrt\",\n\t\"setsid\",\n\t\"xargs\",\n\t\"timeout\",\n\t// busybox dispatches to its builtin applet by the same name and arguments\n\t// it was given (`busybox rm -rf /` behaves exactly like `rm -rf /`), so it\n\t// is a pure passthrough for deny-scan purposes.\n\t\"busybox\",\n\t// wsl/wsl.exe runs its arguments as a command inside the Linux subsystem,\n\t// same shape as sudo/env.\n\t\"wsl\",\n]);\n\n/** Shells whose `-c <command>` argument is itself a full command line to unwrap and re-check. */\nconst SHELL_C_WRAPPERS = new Set([\"bash\", \"sh\", \"zsh\", \"ksh\", \"dash\", \"fish\"]);\n\n/**\n * Every shell the run checks know: the `-c` wrappers and other shells that equally run a script,\n * stdin, or `-c`. The deny scan keeps to `SHELL_C_WRAPPERS`.\n */\nconst SCRIPT_SHELLS: ReadonlySet<string> = new Set([\n\t...SHELL_C_WRAPPERS,\n\t\"ash\",\n\t\"mksh\",\n\t\"pdksh\",\n\t\"oksh\",\n\t\"yash\",\n\t\"posh\",\n\t\"csh\",\n\t\"tcsh\",\n\t\"elvish\",\n\t\"nu\",\n\t\"xonsh\",\n]);\n\n/**\n * Non-POSIX shells whose command-line argument is itself a full command line\n * to unwrap and re-check. Catches bash wrapping another shell, e.g.\n * `bash -c \"pwsh -c 'rm -rf ~'\"`. Matched by regex rather than a fixed Set so\n * variants like `pwsh-preview`, `powershell_ise`, and `.exe`/path-prefixed\n * spellings (normalized by `basenameOfHeadToken`) are all covered.\n */\nconst OTHER_SHELL_WRAPPER_RE = /^(pwsh|powershell|powershell_ise|cmd)([-_].*)?$/;\n\nfunction isOtherShellWrapperName(basename: string): boolean {\n\treturn OTHER_SHELL_WRAPPER_RE.test(basename);\n}\n\n/** Constructs that make a command dynamic/opaque enough that allow/approve patterns must never match it. */\nconst DANGEROUS_CONSTRUCT_RE = /\\$\\(|`|<|>/;\n\n/** `true` for the operators that feed one command's output into the next: `|` and `|&`. */\nfunction isPipeOperator(operator: string | undefined): boolean {\n\treturn operator === \"|\" || operator === \"|&\";\n}\n\ninterface ChainSegment {\n\ttext: string;\n\t/** The operator immediately preceding this segment; `undefined` for the first segment. */\n\toperator?: string;\n}\n\n/** Quote-aware split of a command string on top-level chain operators (`;`, `&&`, `||`, `|`, `&`, newlines). */\nfunction splitChain(command: string): ChainSegment[] {\n\tconst segments: ChainSegment[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet operator: string | undefined;\n\tlet i = 0;\n\twhile (i < command.length) {\n\t\tconst ch = command[i];\n\t\tif (quote) {\n\t\t\tcurrent += ch;\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"' || ch === \"'\") {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < command.length) {\n\t\t\tcurrent += ch + command[i + 1];\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tconst two = command.slice(i, i + 2);\n\t\tif (two === \"&&\" || two === \"||\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = two;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = ch === \"\\n\" ? \";\" : ch;\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\tsegments.push({ text: current, operator });\n\treturn segments;\n}\n\nfunction collapseWhitespace(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * Canonicalizes combined single-dash short-flag clusters (`-rf` / `-fr`) by\n * sorting their letters. The sort is case-insensitive: matching elsewhere is\n * already case-insensitive (`globToRegExp`'s `i` flag), but a case-sensitive\n * sort would put uppercase letters before lowercase ones (ASCII order), so a\n * mixed-case cluster like `-Rf` would canonicalize to `-Rf` while `-rf`\n * canonicalizes to `-fr` — different letter *order*, which the `i` flag\n * can't paper over. Sorting case-insensitively (while keeping each letter's\n * original case) gives `-Rf` and `-rf` the same order (`-fR` / `-fr`), so\n * `-Rf`/`-fR`/`-RF`/... all canonicalize to match a plain `-rf` pattern.\n */\nfunction normalizeFlagClusters(text: string): string {\n\treturn text.replace(/(^|\\s)-([A-Za-z]{2,})(?=\\s|$)/g, (_match, pre: string, letters: string) => {\n\t\tconst sorted = [...letters].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n\t\treturn `${pre}-${sorted.join(\"\")}`;\n\t});\n}\n\nfunction normalizeForMatch(text: string): string {\n\treturn normalizeFlagClusters(collapseWhitespace(text));\n}\n\nfunction tokenize(text: string): string[] {\n\tconst trimmed = text.trim();\n\treturn trimmed.length === 0 ? [] : trimmed.split(/\\s+/);\n}\n\n/** A combined short-flag cluster token (`-rf`, `-R`), optionally glob-suffixed (`-r*`) by a danger-pattern author. */\nfunction parseShortFlagClusterToken(token: string): string | undefined {\n\treturn token.match(/^-([A-Za-z]+)\\*?$/)?.[1];\n}\n\nfunction parseLongFlagToken(token: string): string | undefined {\n\treturn token.match(/^--([A-Za-z][A-Za-z-]*)$/)?.[1]?.toLowerCase();\n}\n\ninterface FlagSet {\n\tshortFlags: Set<string>;\n\tlongFlags: Set<string>;\n}\n\n/** Collects every short/long flag found anywhere in `tokens`, regardless of order, clustering, or position. */\nfunction extractFlagSet(tokens: string[]): FlagSet {\n\tconst shortFlags = new Set<string>();\n\tconst longFlags = new Set<string>();\n\tfor (const token of tokens) {\n\t\tconst letters = parseShortFlagClusterToken(token);\n\t\tif (letters !== undefined) {\n\t\t\tfor (const ch of letters) shortFlags.add(ch.toLowerCase());\n\t\t\tcontinue;\n\t\t}\n\t\tconst long = parseLongFlagToken(token);\n\t\tif (long !== undefined) longFlags.add(long);\n\t}\n\treturn { shortFlags, longFlags };\n}\n\ninterface FlagClusterDenyPattern {\n\tcommand: string;\n\trequiredShortFlags: Set<string>;\n\trequiredLongFlags: Set<string>;\n}\n\n/**\n * Parses a deny `pattern` of the shape `<command> <flags...> [*]` (e.g.\n * `rm -rf *`, `rm -r*`, `chmod -R *`) into a required flag set, for matching\n * by `flagClusterPatternMatchesCandidate` below. Returns `undefined` for any\n * pattern that doesn't have this exact \"bare command name plus only\n * flags/wildcard\" shape, so those patterns keep using the generic glob\n * matcher unchanged.\n */\nfunction parseFlagClusterPattern(pattern: string): FlagClusterDenyPattern | undefined {\n\tconst [command, ...rest] = tokenize(pattern);\n\tif (command === undefined || /[*?]/.test(command)) return undefined;\n\n\tconst requiredShortFlags = new Set<string>();\n\tconst requiredLongFlags = new Set<string>();\n\tlet sawFlag = false;\n\tfor (const token of rest) {\n\t\tif (token === \"*\") continue;\n\t\tconst letters = parseShortFlagClusterToken(token);\n\t\tif (letters !== undefined) {\n\t\t\tsawFlag = true;\n\t\t\tfor (const ch of letters) requiredShortFlags.add(ch.toLowerCase());\n\t\t\tcontinue;\n\t\t}\n\t\tconst long = parseLongFlagToken(token);\n\t\tif (long !== undefined) {\n\t\t\tsawFlag = true;\n\t\t\trequiredLongFlags.add(long);\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (!sawFlag) return undefined;\n\treturn { command: command.toLowerCase(), requiredShortFlags, requiredLongFlags };\n}\n\n/** `rm`'s two spellings of \"recursive\"/\"force\" that are interchangeable for flag-set matching purposes. */\nconst SHORT_LONG_FLAG_EQUIVALENTS: ReadonlyMap<string, string> = new Map([\n\t[\"r\", \"recursive\"],\n\t[\"f\", \"force\"],\n]);\n\nfunction flagClusterPatternMatchesCandidate(flagPattern: FlagClusterDenyPattern, candidateText: string): boolean {\n\tconst tokens = tokenize(candidateText);\n\tconst commandToken = tokens[0];\n\tif (commandToken === undefined) return false;\n\tconst commandName = (\n\t\tcommandToken.includes(\"/\") ? commandToken.slice(commandToken.lastIndexOf(\"/\") + 1) : commandToken\n\t).toLowerCase();\n\tif (commandName !== flagPattern.command) return false;\n\n\tconst { shortFlags, longFlags } = extractFlagSet(tokens.slice(1));\n\tconst hasShort = (flag: string) =>\n\t\tshortFlags.has(flag) || longFlags.has(SHORT_LONG_FLAG_EQUIVALENTS.get(flag) ?? \"\");\n\tconst hasLong = (flag: string) => {\n\t\tif (longFlags.has(flag)) return true;\n\t\tfor (const [short, long] of SHORT_LONG_FLAG_EQUIVALENTS) {\n\t\t\tif (long === flag && shortFlags.has(short)) return true;\n\t\t}\n\t\treturn false;\n\t};\n\n\tfor (const flag of flagPattern.requiredShortFlags) if (!hasShort(flag)) return false;\n\tfor (const flag of flagPattern.requiredLongFlags) if (!hasLong(flag)) return false;\n\treturn true;\n}\n\n/** Resolves a leading `/some/path/cmd` (or `./cmd`, `../cmd`) first token down to its bare basename. */\nfunction resolveBasenameOfFirstToken(text: string): string {\n\tconst leadingWs = text.slice(0, text.length - text.trimStart().length);\n\tconst trimmed = text.trimStart();\n\tconst match = trimmed.match(/^(\\S+)([\\s\\S]*)$/);\n\tif (!match) return text;\n\tconst [, firstToken, rest] = match;\n\tif (!firstToken.includes(\"/\")) return text;\n\tconst basename = firstToken.slice(firstToken.lastIndexOf(\"/\") + 1);\n\treturn leadingWs + basename + rest;\n}\n\nfunction stripLeadingBackslashEscape(text: string): string {\n\treturn text.replace(/^(\\s*)\\\\(?=[A-Za-z])/, \"$1\");\n}\n\nfunction stripEnvAssignments(text: string): string {\n\treturn text.replace(/^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)+/, \"\");\n}\n\n/**\n * Flags that consume a separate following argument (rather than being a\n * standalone `-flag` token) for each passthrough wrapper, so\n * `stripPassthroughPrefix` doesn't mistake that argument for the start of\n * the wrapped command.\n */\nconst WRAPPER_FLAGS_WITH_ARG: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n\t[\"timeout\", new Set([\"-s\", \"-k\", \"--signal\", \"--kill-after\"])],\n\t[\"nice\", new Set([\"-n\"])],\n\t[\"ionice\", new Set([\"-c\", \"-n\", \"-p\"])],\n\t// policy flags (-b/-f/-i/-o/-r) take a priority; -p takes a target pid.\n\t[\"chrt\", new Set([\"-b\", \"-f\", \"-i\", \"-o\", \"-r\", \"-p\"])],\n\t[\"stdbuf\", new Set([\"-i\", \"-o\", \"-e\"])],\n\t[\"env\", new Set([\"-u\", \"-C\", \"-S\", \"--split-string\"])],\n\t[\"sudo\", new Set([\"-u\", \"-g\", \"-h\", \"-p\", \"-C\", \"-D\", \"-r\", \"-t\", \"-U\"])],\n]);\n\n/**\n * Strips one leading passthrough-wrapper command (e.g. `sudo`, `env FOO=1`)\n * and its own flags, if present, consuming each flag's own separate argument\n * (`WRAPPER_FLAGS_WITH_ARG`) rather than mistaking it for the wrapped\n * command. `timeout DURATION cmd...` additionally skips the required\n * duration positional, which isn't a `-flag` token, so `timeout 5 rm -rf /`\n * unwraps down to `rm -rf /` instead of leaving the bogus `5 rm -rf /`\n * behind.\n */\nfunction stripPassthroughPrefix(text: string): { stripped: string; changed: boolean } {\n\tconst trimmed = text.replace(/^\\s+/, \"\");\n\tconst tokens = tokenizeShellWords(trimmed);\n\tconst head = tokens[0];\n\tif (head === undefined) return { stripped: text, changed: false };\n\tconst basename = basenameOfHeadToken(head);\n\tif (!PASSTHROUGH_PREFIXES.has(basename)) return { stripped: text, changed: false };\n\n\tconst argFlags = WRAPPER_FLAGS_WITH_ARG.get(basename);\n\tlet i = 1;\n\twhile (i < tokens.length) {\n\t\tconst token = tokens[i];\n\t\tif (argFlags?.has(token)) {\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/^-/.test(token)) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\tif (basename === \"timeout\" && i < tokens.length) i++;\n\n\treturn { stripped: tokens.slice(i).map(requoteTokenIfNeeded).join(\" \"), changed: true };\n}\n\n/** Re-wraps a dequoted token in single quotes if it contains whitespace, so rejoining tokens with `\" \"` doesn't silently merge what was one quoted argument into several unquoted words. */\nfunction requoteTokenIfNeeded(token: string): string {\n\treturn /\\s/.test(token) ? `'${token.replace(/'/g, `'\\\\''`)}'` : token;\n}\n\n/**\n * Minimal POSIX-ish shell word tokenizer: splits `text` on unquoted\n * whitespace, honoring single quotes (fully literal, no escapes), double\n * quotes (backslash escapes the next character), and a bare backslash\n * outside quotes (escapes the next character). This is only used to locate\n * wrapper flags and the command-body token that follows them, not to\n * implement real shell grammar (no variable expansion, globbing, etc.).\n */\nfunction tokenizeShellWords(text: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet hasCurrent = false;\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tconst ch = text[i];\n\t\tif (/\\s/.test(ch)) {\n\t\t\tif (hasCurrent) {\n\t\t\t\ttokens.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t\thasCurrent = false;\n\t\t\t}\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\") {\n\t\t\thasCurrent = true;\n\t\t\ti++;\n\t\t\twhile (i < text.length && text[i] !== \"'\") {\n\t\t\t\tcurrent += text[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\thasCurrent = true;\n\t\t\ti++;\n\t\t\twhile (i < text.length && text[i] !== '\"') {\n\t\t\t\tif (text[i] === \"\\\\\" && i + 1 < text.length) {\n\t\t\t\t\tcurrent += text[i + 1];\n\t\t\t\t\ti += 2;\n\t\t\t\t} else {\n\t\t\t\t\tcurrent += text[i];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < text.length) {\n\t\t\thasCurrent = true;\n\t\t\tcurrent += text[i + 1];\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\thasCurrent = true;\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\tif (hasCurrent) tokens.push(current);\n\treturn tokens;\n}\n\n/**\n * Lowercased basename of a (possibly quoted/escaped, already-tokenized)\n * command-head token: split on both `/` and `\\` (Windows paths), lowercased,\n * with a trailing `.exe` stripped — so `C:\\Windows\\System32\\cmd.EXE`,\n * `./cmd`, and `cmd` all normalize to `cmd` for wrapper/interpreter lookup.\n */\nfunction basenameOfHeadToken(token: string): string {\n\tconst parts = token.split(/[/\\\\]/);\n\tconst base = (parts[parts.length - 1] ?? token).toLowerCase();\n\treturn base.endsWith(\".exe\") ? base.slice(0, -4) : base;\n}\n\n/** Shell options that consume the following token as their own argument, not as part of the command. */\nconst SHELL_DASH_O_FLAGS = new Set([\"-o\", \"-O\", \"+o\", \"+O\", \"--rcfile\", \"--init-file\"]);\n\n/**\n * Extracts the command-body token following a `-c` flag from an\n * already-tokenized shell invocation, if `text`'s head is in `wrapperSet` and\n * a `-c` flag (bare or clustered with other short flags, e.g. `-lc`, `-cx`,\n * `-ce`) appears anywhere before the first non-flag token — including after\n * `-o pipefail`, `-O extglob`, `--`, or `-l`. Trailing positional arguments\n * after the body (e.g. `$0` in `bash -c '...' x`) are ignored.\n */\nfunction extractShellBodyAfterDashC(text: string, wrapperSet: ReadonlySet<string>): string | undefined {\n\tconst tokens = tokenizeShellWords(text.trim());\n\tconst head = tokens[0];\n\tif (head === undefined || !wrapperSet.has(basenameOfHeadToken(head))) return undefined;\n\n\tlet sawDashC = false;\n\tfor (let i = 1; i < tokens.length; i++) {\n\t\tconst token = tokens[i];\n\t\tif (token === \"--\") continue;\n\t\tif (SHELL_DASH_O_FLAGS.has(token)) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/^-[A-Za-z]+$/.test(token)) {\n\t\t\tif (token.includes(\"c\")) sawDashC = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// Long (`--norc`, `--login`) and `+` options (`+x`) are flags too; skip them\n\t\t// so a later `-c` is still found.\n\t\tif (/^(?:--|\\+)[A-Za-z][\\w-]*$/.test(token)) continue;\n\t\treturn sawDashC ? token : undefined;\n\t}\n\treturn undefined;\n}\n\n/** Extracts the payload of a `<<< '...'` here-string or a `<<DELIM ... DELIM` heredoc, if present anywhere in `text`. */\nfunction extractHereStringOrHeredocPayload(text: string): string | undefined {\n\tconst hereString = text.match(/<<<\\s*(['\"]?)([\\s\\S]*?)\\1\\s*$/);\n\tif (hereString) return hereString[2];\n\tconst heredoc = text.match(/<<-?\\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\\1[^\\n]*\\n([\\s\\S]*?)\\n[ \\t]*\\2\\s*$/);\n\treturn heredoc ? heredoc[3] : undefined;\n}\n\n/** `true` when `text` invokes a known shell with no `-c`, but feeds it a here-string or heredoc body. */\nfunction feedsBareShellViaHereDocOrString(text: string): boolean {\n\tconst trimmed = text.trim();\n\tconst tokens = tokenizeShellWords(trimmed);\n\tconst head = tokens[0];\n\tif (head === undefined || !SHELL_C_WRAPPERS.has(basenameOfHeadToken(head))) return false;\n\tif (extractShellBodyAfterDashC(trimmed, SHELL_C_WRAPPERS) !== undefined) return false;\n\treturn /<<<|<</.test(trimmed);\n}\n\n/** `true` when any `|`-joined segment pipes into a known shell with no `-c` (`echo ... | bash`). */\nfunction pipedIntoBareShell(segments: readonly ChainSegment[]): boolean {\n\treturn segments.some((seg) => {\n\t\tif (!isPipeOperator(seg.operator)) return false;\n\t\tconst trimmed = seg.text.trim();\n\t\tconst tokens = tokenizeShellWords(trimmed);\n\t\tconst head = tokens[0];\n\t\tif (head === undefined || !SHELL_C_WRAPPERS.has(basenameOfHeadToken(head))) return false;\n\t\treturn extractShellBodyAfterDashC(trimmed, SHELL_C_WRAPPERS) === undefined;\n\t});\n}\n\n/**\n * `true` when `command` feeds a bare shell interpreter (`bash`, `sh`, `zsh`,\n * `dash`, `ksh`, `fish`) via a pipe, here-string, or heredoc, with no `-c`\n * flag — in the command itself or in any command line it runs (see\n * `scanExecutedCode`). The deny scan can extract and check the piped/here-doc\n * text (see `scanDenyCandidates`), but can't prove the absence of danger the\n * way a plain unwrapped command can — so auto mode must never silently allow it.\n */\nfunction commandFeedsBareShellWithoutDashC(command: string): boolean {\n\tconst feedsShell = (text: string) => {\n\t\tconst segments = splitChain(text);\n\t\treturn pipedIntoBareShell(segments) || segments.some((seg) => feedsBareShellViaHereDocOrString(seg.text));\n\t};\n\tif (feedsShell(command)) return true;\n\tconst executed = scanExecutedCode(command);\n\treturn (\n\t\texecuted.truncated ||\n\t\tpipedIntoBareShell(executed.segments) ||\n\t\texecuted.segments.some((seg) => feedsBareShellViaHereDocOrString(seg.text))\n\t);\n}\n\n/** Interpreters: each runs a script operand, inline code (`-c`, `-e`), or the program on stdin. */\nconst INTERPRETER_RE = /^(python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|ruby|perl|php)$/;\n\n/** The interpreter family `name` belongs to, the key of `INTERPRETER_ARG_FLAGS` and `INTERPRETER_INLINE_FLAGS`. */\nfunction interpreterFamily(name: string): string {\n\tif (name.startsWith(\"python\") || name.startsWith(\"pypy\")) return \"python\";\n\treturn name === \"nodejs\" ? \"node\" : name;\n}\n\n/** Interpreter flags that take the next word as their own argument (`python3 -W ignore`, `node -r ./x`). */\nconst INTERPRETER_ARG_FLAGS: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n\t[\"python\", new Set([\"-W\", \"-X\", \"--check-hash-based-pycs\"])],\n\t[\n\t\t\"node\",\n\t\tnew Set([\n\t\t\t\"-r\",\n\t\t\t\"--require\",\n\t\t\t\"--import\",\n\t\t\t\"--loader\",\n\t\t\t\"--experimental-loader\",\n\t\t\t\"-C\",\n\t\t\t\"--conditions\",\n\t\t\t\"--input-type\",\n\t\t\t\"--env-file\",\n\t\t\t\"--title\",\n\t\t]),\n\t],\n\t[\"bun\", new Set([\"-r\", \"--require\", \"--preload\", \"--cwd\", \"--env-file\", \"--tsconfig-override\"])],\n\t[\"deno\", new Set([\"--config\", \"--import-map\", \"--location\", \"--seed\", \"--v8-flags\", \"--env-file\", \"--cert\"])],\n\t[\"ruby\", new Set([\"-I\", \"-r\", \"-C\", \"-E\", \"-F\", \"--encoding\"])],\n\t[\"perl\", new Set([\"-I\"])],\n\t[\"php\", new Set([\"-d\", \"-c\", \"-z\"])],\n]);\n\n/** Interpreter flags that give the program inline or as a module, so it is no script operand and not stdin. */\nconst INTERPRETER_INLINE_FLAGS: ReadonlyMap<string, ReadonlySet<string>> = new Map([\n\t[\"python\", new Set([\"-c\", \"-m\"])],\n\t[\"node\", new Set([\"-e\", \"--eval\", \"-p\", \"--print\"])],\n\t[\"bun\", new Set([\"-e\", \"--eval\", \"-p\", \"--print\"])],\n\t[\"ruby\", new Set([\"-e\"])],\n\t[\"perl\", new Set([\"-e\", \"-E\"])],\n\t[\"php\", new Set([\"-r\"])],\n]);\n\n/** Operands that name stdin itself. */\nconst STDIN_OPERANDS: ReadonlySet<string> = new Set([\"-\", \"/dev/stdin\", \"/dev/fd/0\", \"/proc/self/fd/0\"]);\n\n/** A descriptor other than stdin by path (`/dev/fd/3`): what a process substitution expands to. */\nconst DESCRIPTOR_PATH_RE = /^\\/(?:dev\\/fd|proc\\/(?:self|\\d+)\\/fd)\\/[1-9]\\d*$/;\n\n/** A `<(...)` or `>(...)` process substitution: its command, and which way it is wired. */\ntype ProcessSubstitution = { direction: \"<\" | \">\"; body: string };\n\n/** A redirection word (`<<EOF`, `<<<`, `>`, `2>&1`, `&>>log`), never a process substitution. */\nconst REDIRECTION_RE = /^\\d*(?:<<<|<<-?|<>|<|&>>?|>>?|>&)(?!\\()/;\n\n/** Where a code runner takes the program it runs from; `code` is the command line a shell's `-c` runs. */\ntype ProgramSource =\n\t| { kind: \"operand\"; operand: string }\n\t| { kind: \"inline\"; code?: string }\n\t| { kind: \"stdin\"; fromDescriptor: boolean };\n\n/**\n * `true` when `words` redirect stdin from a process substitution or another descriptor\n * (`< <(...)`, `0</dev/fd/3`, `<&3`), or from a connection bash opens itself\n * (`< /dev/tcp/host/port`), never from a file or stdin itself.\n */\nfunction stdinFromDescriptor(words: string[]): boolean {\n\treturn words.some((word, i) => {\n\t\tconst redirection = word.match(/^0?<(?![<>(])(&?)(.*)$/);\n\t\tif (!redirection) return false;\n\t\tconst target = redirection[2] === \"\" ? (words[i + 1] ?? \"\") : redirection[2];\n\t\tif (redirection[1] === \"&\") return /^[1-9]\\d*$/.test(target);\n\t\treturn target.startsWith(\"<(\") || DESCRIPTOR_PATH_RE.test(target) || /^\\/dev\\/(?:tcp|udp)\\//.test(target);\n\t});\n}\n\n/**\n * What can open a command without being its name: `{` and `!`, a subshell's `(`, `coproc`, the\n * head of a loop that runs its body on the same line (`for x do`, `for ((...)) do`), the reserved\n * words before a command (`if`, `then`, `do`, ...) and `builtin`, a function header (`f() {`,\n * `function f {`), a case statement's head (`case $x in`), and a case pattern followed by its\n * command (`start|stop) ...`, `\"a b\") ...`). A word and `)` followed by a redirection or nothing\n * is the end of a subshell, not a case pattern: `(cd x && make) > log`.\n */\nconst COMPOUND_OPENERS: readonly RegExp[] = [\n\t/^\\s*[{!](?=\\s)/,\n\t/^\\s*\\(+/,\n\t/^\\s*coproc\\s+[A-Za-z_]\\w*\\s+\\{(?=\\s)/,\n\t/^\\s*(?:for|select)\\s+[A-Za-z_]\\w*\\s+do(?=\\s)/,\n\t/^\\s*for\\s*\\(\\([\\s\\S]*?\\)\\)\\s*do(?=\\s)/,\n\t/^\\s*(?:if|then|else|elif|while|until|do|coproc|builtin)(?=\\s)/,\n\t/^\\s*function\\s+[^\\s(){}]+(?:\\s*\\(\\s*\\))?(?:\\s*\\{(?=\\s))?/,\n\t/^\\s*[A-Za-z_][\\w.:-]*\\s*\\(\\s*\\)(?:\\s*\\{(?=\\s))?/,\n\t/^\\s*case\\s+\\S+\\s+in(?=\\s|$)/,\n\t/^\\s*\\(?(?:\"[^\"]*\"|'[^']*'|\\\\.|[^\\s()|;&<>\"'\\\\])+(?:\\s*\\|\\s*(?:\"[^\"]*\"|'[^']*'|\\\\.|[^\\s()|;&<>\"'\\\\])+)*\\)(?=\\s+[^\\s<>|&;)])/,\n];\n\n/**\n * `text` without the `)` that close a subshell around its command (`rm -rf ~)`,\n * `bash) < <(...)`): every `)` outside quotes with no `(` of its own before it.\n */\nfunction stripUnbalancedClosers(text: string): string {\n\tlet out = \"\";\n\tlet depth = 0;\n\tlet quote: \"'\" | '\"' | undefined;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst ch = text[i];\n\t\tif (ch === \"\\\\\" && quote !== \"'\" && i + 1 < text.length) {\n\t\t\tout += ch + text[i + 1];\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote !== undefined) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t} else if (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t} else if (ch === \"(\") {\n\t\t\tdepth++;\n\t\t} else if (ch === \")\") {\n\t\t\tif (depth === 0) continue;\n\t\t\tdepth--;\n\t\t}\n\t\tout += ch;\n\t}\n\treturn out;\n}\n\n/**\n * `text` without the compound-command syntax in front of its command (`COMPOUND_OPENERS`), and\n * without the `)` that closes a subshell after it: `if x; then rm -rf ~; fi` runs `rm -rf ~`,\n * `(rm -rf ~)` too.\n */\nfunction stripCompoundOpeners(text: string): string {\n\tlet stripped = text;\n\tfor (let guard = 0; guard < 16; guard++) {\n\t\tconst opener = COMPOUND_OPENERS.find((re) => re.test(stripped));\n\t\tif (opener === undefined) break;\n\t\tstripped = stripped.replace(opener, \"\");\n\t}\n\treturn stripUnbalancedClosers(stripped);\n}\n\n/**\n * `text` as the command it runs: compound-command syntax, leading assignments and passthrough\n * wrappers (`env`, `nice`, `time`, ...) stripped in whatever order they come. `beforeWrappers`\n * keeps the first wrapper, for `env -S`.\n */\nfunction unwrapCommand(text: string): { working: string; beforeWrappers: string } {\n\tlet working = text;\n\tlet beforeWrappers: string | undefined;\n\tfor (let guard = 0; guard < 8; guard++) {\n\t\tconst opened = stripEnvAssignments(stripLeadingBackslashEscape(stripCompoundOpeners(working)));\n\t\tbeforeWrappers ??= opened;\n\t\tconst { stripped, changed } = stripPassthroughPrefix(opened);\n\t\tconst next = changed ? stripped : opened;\n\t\tif (next === working) break;\n\t\tworking = next;\n\t}\n\treturn { working, beforeWrappers: beforeWrappers ?? working };\n}\n\n/** `text`'s words once `unwrapCommand` has stripped what runs it without being it. */\nfunction unwrappedWords(text: string): string[] {\n\treturn tokenizeShellWords(unwrapCommand(text).working.trim());\n}\n\n/**\n * Where the shell, interpreter, `source` or `.` that `words` start with takes its program\n * from: a script operand, inline code (`-c`, `-e`, `-m`; for a shell, with the command line its\n * `-c` runs), or stdin (no operand, `-` and its spellings, or a shell given `-s`), noting whether\n * stdin is redirected from a `<(...)` or another descriptor anywhere among the words. `undefined`\n * when `words` start with anything else. Option arguments (`bash -euo pipefail`,\n * `python3 -W ignore`) and redirections (`> out.txt`) are skipped, so neither passes for the script.\n */\nfunction programSource(words: string[]): ProgramSource | undefined {\n\tconst head = words[0];\n\tif (head === undefined) return undefined;\n\tconst name = basenameOfHeadToken(head);\n\tconst isShell = SCRIPT_SHELLS.has(name);\n\tif (!isShell && !INTERPRETER_RE.test(name) && name !== \"source\" && name !== \".\") return undefined;\n\tconst family = interpreterFamily(name);\n\tconst argFlags = INTERPRETER_ARG_FLAGS.get(family);\n\tconst inlineFlags = INTERPRETER_INLINE_FLAGS.get(family);\n\tconst fromDescriptor = stdinFromDescriptor(words);\n\tlet readsStdin = false;\n\tlet inlineShell = false;\n\tlet optionsDone = false;\n\tlet subcommandSkipped = false;\n\tfor (let i = 1; i < words.length; i++) {\n\t\tconst word = words[i];\n\t\tconst redirection = word.match(REDIRECTION_RE);\n\t\tif (redirection) {\n\t\t\tif (redirection[0] === word) i++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsDone) {\n\t\t\tif (word === \"--\") {\n\t\t\t\toptionsDone = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isShell && SHELL_DASH_O_FLAGS.has(word) && !/^[-+][oO]$/.test(word)) {\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isShell && /^[-+][A-Za-z]+$/.test(word)) {\n\t\t\t\t// A cluster: `c` runs the first operand as a command line, `s` the program on stdin,\n\t\t\t\t// and each `o` takes the next word as an option name (`-euo pipefail`).\n\t\t\t\tif (word.startsWith(\"-\") && word.includes(\"c\")) inlineShell = true;\n\t\t\t\telse if (word.startsWith(\"-\") && word.includes(\"s\")) readsStdin = true;\n\t\t\t\ti += (word.match(/[oO]/g) ?? []).length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (inlineFlags?.has(word)) return { kind: \"inline\" };\n\t\t\tif ((family === \"perl\" || family === \"ruby\") && /^-[A-Za-z]*[eE][A-Za-z]*$/.test(word))\n\t\t\t\treturn { kind: \"inline\" };\n\t\t\tif (argFlags?.has(word)) {\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (/^-./.test(word) || (isShell && /^\\+./.test(word))) continue;\n\t\t}\n\t\tif ((family === \"deno\" || family === \"bun\") && !subcommandSkipped && word === \"run\") {\n\t\t\tsubcommandSkipped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (inlineShell) return { kind: \"inline\", code: word };\n\t\tif (readsStdin || STDIN_OPERANDS.has(word)) return { kind: \"stdin\", fromDescriptor };\n\t\treturn { kind: \"operand\", operand: word };\n\t}\n\treturn inlineShell ? { kind: \"inline\" } : { kind: \"stdin\", fromDescriptor };\n}\n\n/**\n * `true` when a pipe, heredoc or here-string feeds a shell, interpreter or `source` the program\n * it runs from stdin (`curl ... | python3`, `python3 - <<'EOF'`, `source /dev/stdin <<<...`), in\n * the command or any command line it runs. The rule `commandFeedsBareShellWithoutDashC` applies\n * to the shells, and the reason `python* -c*` is a danger pattern: the deny scan can't vet a\n * program in another language. A runner given a script (`... | python3 -m json.tool`,\n * `python3 tool.py <<EOF`) reads data, not code.\n */\nfunction commandFeedsCodeFromStdin(command: string): boolean {\n\tconst executed = scanExecutedCode(command);\n\treturn (\n\t\texecuted.truncated ||\n\t\texecuted.segments.some((seg) => {\n\t\t\tif (programSource(unwrappedWords(seg.text))?.kind !== \"stdin\") return false;\n\t\t\treturn isPipeOperator(seg.operator) || /<<<|<</.test(seg.text);\n\t\t})\n\t);\n}\n\n/**\n * `true` when code runs straight out of a process substitution, in the command or any command\n * line it runs: a shell, interpreter, `source` or `.` whose script is `<(...)` (`bash <(curl ...)`,\n * `source <(...)`) or whose stdin is one (`bash < <(...)`), or a `>(...)` that runs what is written\n * into it (`tee >(sh)`). A descriptor path counts as one, being what `<(...)` expands to\n * (`bash /dev/fd/3 3< <(curl ...)`, `bash <&3`). The deny scan sees the substitution's command,\n * never the program it produces. A process substitution that only carries data\n * (`diff <(ls a) <(ls b)`, `python3 tool.py < <(git log)`) runs nothing.\n */\nfunction commandRunsProcessSubstitution(command: string): boolean {\n\tconst executed = scanExecutedCode(command);\n\tif (executed.truncated) return true;\n\tconst runsOne = executed.segments.some((seg) => {\n\t\tconst source = programSource(unwrappedWords(seg.text));\n\t\tif (source?.kind === \"operand\") {\n\t\t\treturn source.operand.startsWith(\"<(\") || DESCRIPTOR_PATH_RE.test(source.operand);\n\t\t}\n\t\treturn source?.kind === \"stdin\" && source.fromDescriptor;\n\t});\n\treturn (\n\t\trunsOne ||\n\t\texecuted.processSubstitutions.some(\n\t\t\t({ direction, body }) => direction === \">\" && programSource(unwrappedWords(body))?.kind === \"stdin\",\n\t\t)\n\t);\n}\n\n/**\n * Extracts the inner command line from a `pwsh -c \"...\"` / `powershell\n * -Command \"...\"` / `cmd /c \"...\"` style wrapper, if present. Accepts `-c`,\n * `-Command`, and `/c` case-insensitively, anywhere among the wrapper's\n * tokens, rather than the exact flag each shell prefers — for danger\n * detection, over-matching is the safe direction.\n */\nfunction extractOtherShellWrapperArg(text: string): string | undefined {\n\tconst trimmed = text.trim();\n\tif (!headIsOtherShellWrapper(trimmed)) return undefined;\n\tconst tokens = tokenizeShellWords(trimmed);\n\tfor (let i = 1; i < tokens.length - 1; i++) {\n\t\tconst token = tokens[i].toLowerCase();\n\t\tif (token === \"-c\" || token === \"-command\" || token === \"/c\") return tokens[i + 1];\n\t}\n\treturn undefined;\n}\n\n/**\n * Extracts the inner command line from an `eval \"...\"` / `eval '...'` /\n * `eval <unquoted words...>` wrapper, if present — bash's `eval` joins all of\n * its arguments with spaces and evaluates the result as a command, whether or\n * not they were quoted.\n */\nfunction extractEvalArg(text: string): string | undefined {\n\tconst trimmed = text.trim();\n\tconst quoted = trimmed.match(/^eval\\s+(['\"])([\\s\\S]*)\\1\\s*$/i);\n\tif (quoted) return quoted[2];\n\tconst unquoted = trimmed.match(/^eval\\s+(\\S[\\s\\S]*)$/i);\n\treturn unquoted ? unquoted[1] : undefined;\n}\n\n/** Extracts the contents of every `$(...)` and `` `...` `` command substitution found anywhere in `text`. */\nfunction extractSubstitutions(text: string): string[] {\n\tconst results: string[] = [];\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tif (text[i] === \"$\" && text[i + 1] === \"(\") {\n\t\t\tlet depth = 1;\n\t\t\tlet j = i + 2;\n\t\t\twhile (j < text.length && depth > 0) {\n\t\t\t\tif (text[j] === \"(\") depth++;\n\t\t\t\telse if (text[j] === \")\") depth--;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tresults.push(text.slice(i + 2, depth === 0 ? j - 1 : j));\n\t\t\ti = j;\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t}\n\tconst backtickMatches = text.match(/`([^`]*)`/g);\n\tif (backtickMatches) {\n\t\tfor (const m of backtickMatches) results.push(m.slice(1, -1));\n\t}\n\treturn results;\n}\n\n/**\n * Returns the literal output of a simple `echo ...` command. This covers a\n * substitution used as a command position, such as `$(echo rm -rf /)`, where\n * the output is subsequently executed by the outer shell.\n */\nfunction extractSimpleEchoOutput(text: string): string | undefined {\n\tconst match = text.match(/^\\s*echo\\s+([^$`]+?)\\s*$/i);\n\tif (!match) return undefined;\n\tconst captured = match[1];\n\tconst quoted = captured.match(/^(['\"])([\\s\\S]*)\\1$/);\n\treturn quoted ? quoted[2] : captured;\n}\n\nconst MAX_DENY_CANDIDATES = 50;\nconst MAX_DENY_DEPTH = 4;\n\ninterface DenyScanResult {\n\tcandidates: string[];\n\t/**\n\t * `true` when the candidate/depth cap cut the scan short before every\n\t * piece of `command` could be enumerated. Callers MUST treat a truncated\n\t * scan as \"unknown, not denied\" rather than \"not denied\" — see\n\t * `commandDenyScanTruncated` below.\n\t */\n\ttruncated: boolean;\n}\n\n/**\n * `splitChain`'s segments joined back with one space around every operator, so a pattern written\n * `curl * | *` also matches `curl x|sh`. `splitChain` reads `|&` as a pipe into an empty piece\n * sent to the background; here it is spelled `|`, so the pattern matches `curl x |& sh` too.\n */\nfunction spaceChainOperators(segments: readonly ChainSegment[]): string {\n\tconst parts: string[] = [];\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tconst seg = segments[i];\n\t\tif (seg.operator === \"|\" && seg.text === \"\" && segments[i + 1]?.operator === \"&\") {\n\t\t\tparts.push(`| ${segments[i + 1].text.trim()}`);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tparts.push(seg.operator === undefined ? seg.text.trim() : `${seg.operator} ${seg.text.trim()}`);\n\t}\n\treturn parts.join(\" \");\n}\n\n/**\n * Paranoidly enumerates every independently-executed \"piece\" of `command` a\n * `deny` rule should be checked against: the raw command, each chained\n * segment, prefix/wrapper-stripped variants of each segment, and the bodies\n * of any `bash -c` / `eval` / `$(...)` / backtick constructs — recursively,\n * bounded so adversarial input can't cause unbounded work.\n *\n * The bound is itself a fail-safe surface: a command with more pieces or\n * wrapper layers than the cap allows must not be treated as \"scanned clean\".\n * `truncated` on the result flags exactly that case.\n */\nfunction scanDenyCandidates(command: string): DenyScanResult {\n\tconst seen = new Set<string>();\n\tconst queue: Array<{ text: string; depth: number }> = [{ text: command, depth: 0 }];\n\tlet truncated = false;\n\n\twhile (queue.length > 0) {\n\t\tif (seen.size >= MAX_DENY_CANDIDATES) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst next = queue.shift();\n\t\tif (!next) break;\n\t\tconst { text, depth } = next;\n\t\tif (seen.has(text)) continue;\n\t\tseen.add(text);\n\t\tif (depth >= MAX_DENY_DEPTH) {\n\t\t\ttruncated = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst enqueue = (candidate: string) => {\n\t\t\tif (seen.has(candidate)) return;\n\t\t\tif (seen.size + queue.length >= MAX_DENY_CANDIDATES) {\n\t\t\t\ttruncated = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tqueue.push({ text: candidate, depth: depth + 1 });\n\t\t};\n\n\t\tconst segmentObjs = splitChain(text);\n\t\tconst segments = segmentObjs.map((s) => s.text);\n\t\tconst pieces = segments.length > 1 ? segments : [text];\n\t\tfor (const seg of segments) enqueue(seg);\n\n\t\tfor (let i = 0; i < segmentObjs.length; i++) {\n\t\t\tif (segmentObjs[i].operator !== \"|\") continue;\n\t\t\tconst prevText = segmentObjs[i - 1]?.text;\n\t\t\tif (prevText === undefined) continue;\n\t\t\tconst echoOutput = extractSimpleEchoOutput(prevText);\n\t\t\tif (echoOutput !== undefined) enqueue(echoOutput);\n\t\t}\n\n\t\tfor (const piece of pieces) {\n\t\t\tlet working = stripLeadingBackslashEscape(piece);\n\t\t\tworking = stripEnvAssignments(working);\n\t\t\tconst beforeWrapperStrip = working;\n\t\t\tfor (let guard = 0; guard < 5; guard++) {\n\t\t\t\tconst { stripped, changed } = stripPassthroughPrefix(working);\n\t\t\t\tif (!changed) break;\n\t\t\t\tworking = stripped;\n\t\t\t}\n\t\t\tenqueue(working);\n\n\t\t\tconst basenameResolved = resolveBasenameOfFirstToken(working);\n\t\t\tenqueue(basenameResolved);\n\n\t\t\tconst shellC =\n\t\t\t\textractShellBodyAfterDashC(working, SHELL_C_WRAPPERS) ??\n\t\t\t\textractShellBodyAfterDashC(basenameResolved, SHELL_C_WRAPPERS);\n\t\t\tif (shellC !== undefined) enqueue(shellC);\n\n\t\t\tconst hereRedirect = extractHereStringOrHeredocPayload(piece);\n\t\t\tif (hereRedirect !== undefined) enqueue(hereRedirect);\n\n\t\t\tconst otherShellArg = extractOtherShellWrapperArg(working) ?? extractOtherShellWrapperArg(basenameResolved);\n\t\t\tif (otherShellArg !== undefined) enqueue(otherShellArg);\n\n\t\t\tconst evalArg = extractEvalArg(working) ?? extractEvalArg(basenameResolved);\n\t\t\tif (evalArg !== undefined) enqueue(evalArg);\n\n\t\t\tconst findExecArg = extractFindExecArg(working) ?? extractFindExecArg(basenameResolved);\n\t\t\tif (findExecArg !== undefined) enqueue(findExecArg);\n\n\t\t\tconst envSplitStringArg = extractEnvSplitStringArg(beforeWrapperStrip);\n\t\t\tif (envSplitStringArg !== undefined) enqueue(envSplitStringArg);\n\n\t\t\tfor (const sub of extractSubstitutions(piece)) {\n\t\t\t\tenqueue(sub);\n\t\t\t\tconst echoOutput = extractSimpleEchoOutput(sub);\n\t\t\t\tif (echoOutput !== undefined) enqueue(echoOutput);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { candidates: [...seen], truncated };\n}\n\n/** One layer of shell text, read the way the shell reads it. */\ninterface LexedShellText {\n\t/**\n\t * The text split at its unquoted chain operators, with heredoc bodies cut out and each process\n\t * substitution collapsed to `<(_)`/`>(_)`.\n\t */\n\tsegments: ChainSegment[];\n\t/** Bodies of the `$(...)` and backtick substitutions the shell runs: outside single quotes, and in unquoted heredoc bodies. */\n\tsubstitutions: string[];\n\t/** Process substitutions outside quotes and heredoc bodies, and the way each is wired. */\n\tprocessSubstitutions: ProcessSubstitution[];\n\t/**\n\t * `true` when part of the text could not be read: a heredoc whose delimiter line never came or\n\t * whose delimiter could not be read, or substitutions nested past `MAX_LEX_NESTING`.\n\t */\n\tunreadable: boolean;\n\t/** Where reading stopped: the end of the text, or just past the `)` that closes a `$(`, `<(` or `>(`. */\n\tend: number;\n}\n\n/** A heredoc operator and what it takes to end its body. */\ninterface HeredocOperator {\n\tlength: number;\n\tdelimiter: string;\n\t/** Any quote or backslash in the delimiter word: the body is data, nothing in it runs. */\n\tquoted: boolean;\n\t/** `<<-`: leading tabs are stripped before the delimiter line is compared. */\n\tstripTabs: boolean;\n\t/** The delimiter word runs into `(`, which this reader cannot follow; the caller fails closed. */\n\tunreadable: boolean;\n}\n\n/**\n * The heredoc operator at `text[i]` (`<<EOF`, `<<-'EOF'`, `<< \"E O F\"`, `<<\\\\EOF`, `<<END-OF-DATA`):\n * the delimiter is the whole shell word after `<<`, quotes and backslashes removed.\n */\nfunction heredocAt(text: string, i: number): HeredocOperator | undefined {\n\tconst operator = text.slice(i).match(/^<<(-?)[ \\t]*/);\n\tif (!operator) return undefined;\n\tlet j = i + operator[0].length;\n\tlet delimiter = \"\";\n\tlet quoted = false;\n\twhile (j < text.length && !/[\\s;&|<>()]/.test(text[j])) {\n\t\tconst ch = text[j];\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquoted = true;\n\t\t\tconst close = text.indexOf(ch, j + 1);\n\t\t\tconst end = close === -1 ? text.length : close;\n\t\t\tdelimiter += text.slice(j + 1, end);\n\t\t\tj = end + 1;\n\t\t} else if (ch === \"\\\\\") {\n\t\t\tquoted = true;\n\t\t\tdelimiter += text[j + 1] ?? \"\";\n\t\t\tj += 2;\n\t\t} else {\n\t\t\tdelimiter += ch;\n\t\t\tj++;\n\t\t}\n\t}\n\tif (delimiter === \"\") return undefined;\n\treturn { length: j - i, delimiter, quoted, stripTabs: operator[1] === \"-\", unreadable: text[j] === \"(\" };\n}\n\n/** The index just past the `)` that closes the arithmetic opened by the `(` at `text[open]`. */\nfunction arithmeticEnd(text: string, open: number): number {\n\tlet depth = 0;\n\tfor (let j = open; j < text.length; j++) {\n\t\tif (text[j] === \"(\") depth++;\n\t\telse if (text[j] === \")\" && --depth === 0) return j + 1;\n\t}\n\treturn text.length;\n}\n\n/**\n * How deep `lexShellText` follows `$(`, `<(` and `>(` inside one another. Deeper text is reported\n * unreadable, so the checks ask instead of recursing until the stack overflows.\n */\nconst MAX_LEX_NESTING = 32;\n\n/** The `$(...)` and backtick substitutions in arithmetic or an unquoted heredoc body, which runs them all. */\nfunction substitutionsIn(text: string, nesting: number): { bodies: string[]; unreadable: boolean } {\n\tconst bodies: string[] = [];\n\tlet unreadable = false;\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tif (text[i] === \"$\" && text[i + 1] === \"(\" && text[i + 2] !== \"(\") {\n\t\t\tconst inner = lexShellText(text, i + 2, true, nesting + 1);\n\t\t\tif (inner.unreadable) unreadable = true;\n\t\t\tbodies.push(text.slice(i + 2, Math.max(i + 2, inner.end - 1)));\n\t\t\ti = inner.end;\n\t\t} else if (text[i] === \"`\") {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < text.length && text[j] !== \"`\") j += text[j] === \"\\\\\" ? 2 : 1;\n\t\t\tbodies.push(text.slice(i + 1, j));\n\t\t\ti = j + 1;\n\t\t} else {\n\t\t\ti += text[i] === \"\\\\\" ? 2 : 1;\n\t\t}\n\t}\n\treturn { bodies, unreadable };\n}\n\n/**\n * Reads one layer of shell text as the shell would, for the checks that ask whether something is\n * RUN, and splits it at its unquoted chain operators. Single-quoted text runs nothing; in double\n * quotes only `$(...)` and backticks run; a quoted heredoc's body is data and an unquoted one runs\n * only its substitutions; `$((...))` and `((...))` are arithmetic. A `$(`, `<(` or `>(` is read to\n * the `)` that really closes it, past quotes and heredocs (`untilCloseParen`). Unlike the deny scan,\n * which over-matches on purpose, a commit message or a file written through a heredoc must not\n * read as code here. A heredoc that never ends, a delimiter this reader cannot follow, or nesting\n * past `MAX_LEX_NESTING` is reported, and the checks then ask rather than trust a misread.\n */\nfunction lexShellText(text: string, start = 0, untilCloseParen = false, nesting = 0): LexedShellText {\n\tif (nesting > MAX_LEX_NESTING) {\n\t\treturn { segments: [], substitutions: [], processSubstitutions: [], unreadable: true, end: text.length };\n\t}\n\tconst segments: ChainSegment[] = [];\n\tconst substitutions: string[] = [];\n\tconst processSubstitutions: ProcessSubstitution[] = [];\n\tconst pendingHeredocs: HeredocOperator[] = [];\n\tlet unreadable = false;\n\tlet current = \"\";\n\tlet operator: string | undefined;\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet depth = 0;\n\t// Where an escape or a substitution just ended: a `#` there still belongs to that word.\n\tlet glued = -1;\n\t// Open `${` expansions: a `#` inside one (`${x#prefix}`, `${x:- #}`) is never a comment.\n\tlet braces = 0;\n\tconst endSegment = (next: string) => {\n\t\tsegments.push({ text: current, operator });\n\t\tcurrent = \"\";\n\t\toperator = next;\n\t};\n\t/** Reads the `$(`, `<(` or `>(` body that starts at `open` to its closing `)`; returns the index after it. */\n\tconst readNested = (open: number): number => {\n\t\tconst inner = lexShellText(text, open, true, nesting + 1);\n\t\tif (inner.unreadable) unreadable = true;\n\t\treturn inner.end;\n\t};\n\t// Element by element: spreading 100k substitutions into `push` overflows the stack.\n\tconst collectSubstitutionsIn = (body: string) => {\n\t\tconst found = substitutionsIn(body, nesting);\n\t\tfor (const substitution of found.bodies) substitutions.push(substitution);\n\t\tif (found.unreadable) unreadable = true;\n\t};\n\tlet i = start;\n\twhile (i < text.length) {\n\t\tconst ch = text[i];\n\t\tif (quote === \"'\") {\n\t\t\tcurrent += ch;\n\t\t\tif (ch === \"'\") quote = undefined;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < text.length) {\n\t\t\tcurrent += ch + text[i + 1];\n\t\t\ti += 2;\n\t\t\tglued = i;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"$\" && text[i + 1] === \"(\") {\n\t\t\tif (text[i + 2] === \"(\") {\n\t\t\t\tconst end = arithmeticEnd(text, i + 1);\n\t\t\t\tcollectSubstitutionsIn(text.slice(i + 3, end));\n\t\t\t\tcurrent += text.slice(i, end);\n\t\t\t\ti = end;\n\t\t\t\tglued = i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst end = readNested(i + 2);\n\t\t\tsubstitutions.push(text.slice(i + 2, Math.max(i + 2, end - 1)));\n\t\t\tcurrent += text.slice(i, end);\n\t\t\ti = end;\n\t\t\tglued = i;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"`\") {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < text.length && text[j] !== \"`\") j += text[j] === \"\\\\\" ? 2 : 1;\n\t\t\tsubstitutions.push(text.slice(i + 1, j));\n\t\t\tcurrent += text.slice(i, j + 1);\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') quote = undefined;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"$\" && text[i + 1] === \"{\") {\n\t\t\tbraces++;\n\t\t\tcurrent += \"${\";\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"}\" && braces > 0) {\n\t\t\tbraces--;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"#\" && braces === 0 && i !== glued && (i === start || /[\\s;&|()<>]/.test(text[i - 1]))) {\n\t\t\t// A comment runs to the end of its line, and an apostrophe in it opens no quote.\n\t\t\tconst newline = text.indexOf(\"\\n\", i);\n\t\t\ti = newline === -1 ? text.length : newline;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"$\" && text[i + 1] === \"$\") {\n\t\t\t// `$$` is the shell's pid: a quote right after it is a plain one, not `$'...'`.\n\t\t\tcurrent += \"$$\";\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"$\" && text[i + 1] === \"'\") {\n\t\t\t// ANSI-C quoting: like single quotes, but a backslash escapes the next character, `\\'` too.\n\t\t\tlet j = i + 2;\n\t\t\twhile (j < text.length && text[j] !== \"'\") j += text[j] === \"\\\\\" ? 2 : 1;\n\t\t\tcurrent += text.slice(i, j + 1);\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif ((ch === \"<\" || ch === \">\") && text[i + 1] === \"(\") {\n\t\t\tconst end = readNested(i + 2);\n\t\t\tprocessSubstitutions.push({ direction: ch, body: text.slice(i + 2, Math.max(i + 2, end - 1)) });\n\t\t\tcurrent += `${ch}(_)`;\n\t\t\ti = end;\n\t\t\tglued = i;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"(\" && text[i + 1] === \"(\") {\n\t\t\tconst end = arithmeticEnd(text, i);\n\t\t\tcollectSubstitutionsIn(text.slice(i + 2, end));\n\t\t\tcurrent += text.slice(i, end);\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"(\") {\n\t\t\tdepth++;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \")\") {\n\t\t\ti++;\n\t\t\tif (depth > 0) {\n\t\t\t\tdepth--;\n\t\t\t\tcurrent += ch;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (untilCloseParen) break;\n\t\t\tcurrent += ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (text.startsWith(\"<<<\", i)) {\n\t\t\tcurrent += \"<<<\";\n\t\t\ti += 3;\n\t\t\tcontinue;\n\t\t}\n\t\tconst heredoc = ch === \"<\" && text[i + 1] === \"<\" ? heredocAt(text, i) : undefined;\n\t\tif (heredoc) {\n\t\t\tif (heredoc.unreadable) unreadable = true;\n\t\t\tpendingHeredocs.push(heredoc);\n\t\t\tcurrent += text.slice(i, i + heredoc.length);\n\t\t\ti += heredoc.length;\n\t\t\tcontinue;\n\t\t}\n\t\tconst two = text.slice(i, i + 2);\n\t\tif (two === \"&&\" || two === \"||\" || two === \"|&\") {\n\t\t\tendSegment(two);\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// `&>file`, `2>&1` and `<&3` are redirections, not a background `&`. The character before\n\t\t// is the one `current` ends with (testing `current` itself would copy it on every `&`).\n\t\tif (ch === \"&\" && (text[i + 1] === \">\" || text[i - 1] === \"<\" || text[i - 1] === \">\")) {\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\") {\n\t\t\tendSegment(ch);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch !== \"\\n\") {\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tendSegment(\";\");\n\t\ti++;\n\t\t// The bodies follow this line, one per heredoc it opened, each up to its delimiter line. An\n\t\t// unquoted body is expanded as a whole once it ends, so a substitution may span its lines.\n\t\tfor (const pending of pendingHeredocs.splice(0)) {\n\t\t\tconst bodyStart = i;\n\t\t\tlet bodyEnd = text.length;\n\t\t\tlet terminated = false;\n\t\t\twhile (i < text.length) {\n\t\t\t\tconst newline = text.indexOf(\"\\n\", i);\n\t\t\t\tconst lineStart = i;\n\t\t\t\tconst line = text.slice(i, newline === -1 ? text.length : newline).replace(/\\r$/, \"\");\n\t\t\t\ti = newline === -1 ? text.length : newline + 1;\n\t\t\t\tif ((pending.stripTabs ? line.replace(/^\\t+/, \"\") : line) === pending.delimiter) {\n\t\t\t\t\tbodyEnd = lineStart;\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!terminated) unreadable = true;\n\t\t\tif (!pending.quoted) collectSubstitutionsIn(text.slice(bodyStart, bodyEnd));\n\t\t}\n\t}\n\tsegments.push({ text: current, operator });\n\treturn { segments, substitutions, processSubstitutions, unreadable, end: i };\n}\n\n/** Every command line the shell runs for a command, found by `scanExecutedCode`. */\ninterface ExecutedScan {\n\t/** The chain segments of the command and of each command line run inside it (`-c` bodies, `eval` arguments, substitutions), lexed. */\n\treadonly segments: readonly ChainSegment[];\n\t/** The process substitutions among them, and the way each is wired. */\n\treadonly processSubstitutions: readonly ProcessSubstitution[];\n\t/** Each segment's text, and the command it runs once `unwrapCommand` has stripped what leads it, for deny matching. */\n\treadonly commands: readonly string[];\n\t/**\n\t * `true` when the scan hit the same bounds as the deny scan, ran into more than\n\t * `MAX_EXECUTED_SEGMENTS` segments, or some text was unreadable (a heredoc that never ended,\n\t * nesting too deep), so something may have been read as data that the shell runs; callers then\n\t * fail closed.\n\t */\n\treadonly truncated: boolean;\n}\n\n/** How many segments the executed scan reads before it stops and reports itself truncated. */\nconst MAX_EXECUTED_SEGMENTS = 1000;\n\n/** The last command's executed scan: one evaluation asks several checks about the same command. */\nlet lastExecutedScan: { command: string; result: ExecutedScan } | undefined;\n\n/**\n * Finds every command line the shell RUNS for `command`: the command itself and, recursively,\n * `bash -c` bodies, `eval` arguments, `pwsh -c`/`env -S`/`find -exec` commands and\n * substitution bodies, each read by `lexShellText`, so neither a heredoc body nor quoted text is\n * mistaken for one.\n */\nfunction scanExecutedCode(command: string): ExecutedScan {\n\tif (lastExecutedScan?.command !== command) lastExecutedScan = { command, result: computeExecutedScan(command) };\n\treturn lastExecutedScan.result;\n}\n\nfunction computeExecutedScan(command: string): ExecutedScan {\n\tconst segments: ChainSegment[] = [];\n\tconst processSubstitutions: ProcessSubstitution[] = [];\n\tconst commands = new Set<string>();\n\tconst seen = new Set<string>();\n\tconst queue: Array<{ text: string; depth: number }> = [{ text: command, depth: 0 }];\n\tlet truncated = false;\n\t// Read by index, not `shift()`: a command with 100k identical substitutions queues every one.\n\tfor (let head = 0; head < queue.length; head++) {\n\t\tconst next = queue[head];\n\t\tif (seen.has(next.text)) continue;\n\t\tif (seen.size >= MAX_DENY_CANDIDATES || next.depth >= MAX_DENY_DEPTH) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\tseen.add(next.text);\n\t\tconst lexed = lexShellText(next.text);\n\t\tif (lexed.unreadable) truncated = true;\n\t\tif (segments.length + lexed.segments.length > MAX_EXECUTED_SEGMENTS) {\n\t\t\ttruncated = true;\n\t\t\tbreak;\n\t\t}\n\t\t// Element by element: a long script spread into `push` overflows the stack.\n\t\tfor (const seg of lexed.segments) segments.push(seg);\n\t\tfor (const substitution of lexed.processSubstitutions) processSubstitutions.push(substitution);\n\t\tconst runs = (body: string | undefined) => {\n\t\t\tif (body !== undefined && !seen.has(body)) queue.push({ text: body, depth: next.depth + 1 });\n\t\t};\n\t\tfor (const body of lexed.substitutions) runs(body);\n\t\tfor (const { body } of lexed.processSubstitutions) runs(body);\n\t\tfor (const seg of lexed.segments) {\n\t\t\tconst { working, beforeWrappers } = unwrapCommand(seg.text);\n\t\t\tconst basenameResolved = resolveBasenameOfFirstToken(working);\n\t\t\tfor (const text of [seg.text, working, basenameResolved]) if (text.trim() !== \"\") commands.add(text.trim());\n\t\t\truns(\n\t\t\t\textractShellBodyAfterDashC(working, SCRIPT_SHELLS) ??\n\t\t\t\t\textractShellBodyAfterDashC(basenameResolved, SCRIPT_SHELLS),\n\t\t\t);\n\t\t\truns(extractOtherShellWrapperArg(working) ?? extractOtherShellWrapperArg(basenameResolved));\n\t\t\truns(extractEvalArg(working) ?? extractEvalArg(basenameResolved));\n\t\t\truns(extractFindExecArg(working) ?? extractFindExecArg(basenameResolved));\n\t\t\truns(extractEnvSplitStringArg(beforeWrappers));\n\t\t\t// Past clustered options `extractShellBodyAfterDashC` stops at: `bash -euo pipefail -c '...'`.\n\t\t\tconst source = programSource(tokenizeShellWords(working.trim()));\n\t\t\tif (source?.kind === \"inline\") runs(source.code);\n\t\t}\n\t}\n\treturn { segments, processSubstitutions, commands: [...commands], truncated };\n}\n\n/** The last command's deny scan: one evaluation matches the same command against every pattern. */\nlet lastDenyScan:\n\t| { command: string; result: DenyScanResult; candidates?: readonly string[]; forms?: readonly string[] }\n\t| undefined;\n\nfunction cachedDenyScan(command: string): NonNullable<typeof lastDenyScan> {\n\tif (lastDenyScan?.command !== command) lastDenyScan = { command, result: scanDenyCandidates(command) };\n\treturn lastDenyScan;\n}\n\n/**\n * What deny rules and the danger filter match: the deny scan's candidates, and the command each\n * segment the executed scan finds the shell runs. The deny scan over-reads on purpose, but it\n * loses its place at an apostrophe in a heredoc or a comment, at `\\\"` or `$'...'`, never looks\n * inside `<(...)`, and keeps `if ...; then`, `{ ...; }` or `( ... )` in front of a command; the\n * executed scan reads all of those as the shell does. Only the deny scan's own bounds make a\n * command truncated.\n */\nfunction collectDenyCandidates(command: string): readonly string[] {\n\tconst scan = cachedDenyScan(command);\n\tscan.candidates ??= [...new Set([...scan.result.candidates, ...scanExecutedCode(command).commands])];\n\treturn scan.candidates;\n}\n\n/**\n * Every candidate normalized for glob matching, and its chain again with spaced operators, so a\n * pattern written `curl * | *` also matches `curl x|sh` and `curl x |& sh`.\n */\nfunction matchableDenyForms(command: string): readonly string[] {\n\tconst scan = cachedDenyScan(command);\n\tscan.forms ??= collectDenyCandidates(command).flatMap((candidate) => {\n\t\tconst plain = normalizeForMatch(candidate);\n\t\tconst spaced = normalizeForMatch(spaceChainOperators(splitChain(candidate)));\n\t\treturn spaced === plain ? [plain] : [plain, spaced];\n\t});\n\treturn scan.forms;\n}\n\n/**\n * `true` when `command` has more chained pieces or wrapper layers than\n * `scanDenyCandidates` could fully enumerate. A truncated scan can never be\n * trusted to say \"no deny/danger match\" — the unscanned remainder might hide\n * one — so callers must fail closed (deny or require approval) rather than\n * fall through to an auto-allow default.\n */\nfunction commandDenyScanTruncated(command: string): boolean {\n\treturn cachedDenyScan(command).result.truncated;\n}\n\n/**\n * Raw first whitespace-delimited token of `text`, with at most one matching\n * pair of surrounding quotes stripped — deliberately *not* run through\n * `tokenizeShellWords`'s backslash-escape collapsing, so a literal Windows\n * path separator (`C:\\Windows\\System32\\cmd.exe`) survives for\n * `basenameOfHeadToken` to split on, instead of being eaten as a POSIX\n * shell escape character.\n */\nfunction rawFirstToken(text: string): string | undefined {\n\tconst token = text.trimStart().match(/^\\S+/)?.[0];\n\tif (token === undefined) return undefined;\n\tconst quoted = token.match(/^(['\"])([\\s\\S]*)\\1$/);\n\treturn quoted ? quoted[2] : token;\n}\n\n/**\n * `true` when `basename(head(text))` is a recognized `pwsh`/`powershell`/\n * `cmd` spelling, checking both the POSIX-escape-aware token (`p\\wsh` ->\n * `pwsh`) and the raw token (`C:\\Windows\\...\\cmd.exe` -> `cmd`), since the\n * two normalizations disagree on what a bare `\\` means.\n */\nfunction headIsOtherShellWrapper(text: string): boolean {\n\tconst dequotedHead = tokenizeShellWords(text.trimStart())[0];\n\tif (dequotedHead !== undefined && isOtherShellWrapperName(basenameOfHeadToken(dequotedHead))) return true;\n\tconst raw = rawFirstToken(text);\n\treturn raw !== undefined && isOtherShellWrapperName(basenameOfHeadToken(raw));\n}\n\n/**\n * `true` when `command` (bash tool) invokes `pwsh`/`powershell`/`cmd` at any\n * unwrapped layer, e.g. `pwsh -c \"Remove-Item -Recurse ~\"` or\n * `bash -c \"cmd /c del ...\"`. Auto mode's danger filter\n * (`DANGEROUS_COMMAND_PATTERNS`) is bash-shaped and has no coverage for these\n * interpreters' own syntax, the same reason unmatched `powershell` tool calls\n * always require approval — so a bash-tool call that merely shells out to one\n * of them must not get a free pass auto mode never meant to give it.\n */\nfunction commandInvokesOtherShell(command: string): boolean {\n\treturn collectDenyCandidates(command).some((candidate) => headIsOtherShellWrapper(candidate));\n}\n\n/**\n * A shell variable/parameter expansion, command substitution, or backtick substitution in command\n * position; with `specialParameters`, positional and special parameters (`$1`, `$@`) too.\n */\nfunction isDynamicCommandHead(token: string, options: { specialParameters: boolean }): boolean {\n\tconst pattern = options.specialParameters ? /^(\\$\\(|\\$\\{|\\$[A-Za-z_0-9@*#?$!-]|`)/ : /^(\\$\\(|\\$\\{|\\$[A-Za-z_]|`)/;\n\treturn pattern.test(token);\n}\n\n/**\n * `true` when any chain segment's command position (after stripping leading\n * `VAR=val` assignments) is a variable/expansion rather than a literal\n * command name (`$p`, `${HOME:+pwsh}`, `$(...)`, a backtick substitution), at\n * any layer the shell runs (`scanExecutedCode`): `bash -c \"$(curl ...)\"` and `eval \"$(curl ...)\"`\n * run another command's output. What actually runs then depends on the\n * environment or on that output, so no pattern — deny, danger filter, or\n * interpreter check — can reason about it; auto mode must require approval\n * instead of silently resolving to whatever the variable happens to hold.\n */\nfunction commandHeadIsDynamic(command: string): boolean {\n\t// The raw command's segments include heredoc lines, where `$5` or `\"$@\"` is text: special\n\t// parameters count only in what the lexed scan finds the shell runs, past `then`, `{` or `nohup`.\n\tconst rawHeadIsDynamic = splitChain(command).some((seg) => {\n\t\tconst head = tokenizeShellWords(stripEnvAssignments(stripLeadingBackslashEscape(seg.text)).trim())[0];\n\t\treturn head !== undefined && isDynamicCommandHead(head, { specialParameters: false });\n\t});\n\tif (rawHeadIsDynamic) return true;\n\tconst executed = scanExecutedCode(command);\n\treturn (\n\t\texecuted.truncated ||\n\t\texecuted.segments.some((seg) => {\n\t\t\tconst heads = [\n\t\t\t\ttokenizeShellWords(stripEnvAssignments(stripLeadingBackslashEscape(seg.text)).trim())[0],\n\t\t\t\tunwrappedWords(seg.text)[0],\n\t\t\t];\n\t\t\treturn heads.some((head) => head !== undefined && isDynamicCommandHead(head, { specialParameters: true }));\n\t\t})\n\t);\n}\n\n/** Extracts the `<cmd>` from `find ... -exec <cmd> ... ;`/`+`/`-execdir <cmd> ... ;`, if present. */\nfunction extractFindExecArg(text: string): string | undefined {\n\tconst tokens = tokenizeShellWords(text.trim());\n\tconst head = tokens[0];\n\tif (head === undefined || basenameOfHeadToken(head) !== \"find\") return undefined;\n\tconst execIndex = tokens.findIndex((token) => token === \"-exec\" || token === \"-execdir\");\n\tif (execIndex === -1) return undefined;\n\tconst cmdTokens: string[] = [];\n\tfor (let i = execIndex + 1; i < tokens.length; i++) {\n\t\tconst token = tokens[i];\n\t\tif (token === \";\" || token === \"+\") break;\n\t\tcmdTokens.push(token);\n\t}\n\treturn cmdTokens.length > 0 ? cmdTokens.join(\" \") : undefined;\n}\n\n/** Extracts `env -S '<cmd>'` / `env --split-string '<cmd>'`'s argument, which `env` itself parses as a command line. */\nfunction extractEnvSplitStringArg(text: string): string | undefined {\n\tconst tokens = tokenizeShellWords(text.trim());\n\tconst head = tokens[0];\n\tif (head === undefined || basenameOfHeadToken(head) !== \"env\") return undefined;\n\tfor (let i = 1; i < tokens.length; i++) {\n\t\tif (tokens[i] === \"-S\" || tokens[i] === \"--split-string\") return tokens[i + 1];\n\t}\n\treturn undefined;\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = \"\";\n\tfor (const ch of pattern) {\n\t\tif (ch === \"*\") source += \".*\";\n\t\telse if (ch === \"?\") source += \".\";\n\t\telse source += ch.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\t}\n\treturn new RegExp(`^${source}$`, \"is\");\n}\n\nfunction matchDenyPattern(command: string, pattern: string): boolean {\n\tconst candidates = collectDenyCandidates(command);\n\tconst flagPattern = parseFlagClusterPattern(pattern);\n\tif (\n\t\tflagPattern !== undefined &&\n\t\tcandidates.some((candidate) => flagClusterPatternMatchesCandidate(flagPattern, candidate))\n\t) {\n\t\treturn true;\n\t}\n\tconst regex = globToRegExp(normalizeForMatch(pattern));\n\treturn matchableDenyForms(command).some((form) => regex.test(form));\n}\n\n/**\n * Strictly matches `command` against an `allow`/`approve` `pattern`: any\n * dynamic/opaque construct disqualifies the match outright, and the command\n * must have the same chain shape (segment count and operators) as the\n * pattern, with every segment matching independently. This is what stops a\n * rule like `{ pattern: \"npm test*\", action: \"allow\" }` from also\n * authorizing `npm test; rm -rf /` or `` npm test `rm -rf /` ``.\n */\nfunction matchAllowPattern(command: string, pattern: string): boolean {\n\tif (DANGEROUS_CONSTRUCT_RE.test(command)) return false;\n\n\tconst commandSegments = splitChain(command);\n\tconst patternSegments = splitChain(pattern);\n\tif (commandSegments.length !== patternSegments.length) return false;\n\n\tfor (let i = 0; i < commandSegments.length; i++) {\n\t\tif (commandSegments[i].operator !== patternSegments[i].operator) return false;\n\t\tconst cmdText = normalizeForMatch(commandSegments[i].text);\n\t\tconst cmdResolved = normalizeForMatch(resolveBasenameOfFirstToken(commandSegments[i].text));\n\t\tconst regex = globToRegExp(normalizeForMatch(patternSegments[i].text));\n\t\tif (!regex.test(cmdText) && !regex.test(cmdResolved)) return false;\n\t}\n\treturn true;\n}\n\nfunction matchCommandPattern(command: string, pattern: string, action: PermissionAction): boolean {\n\treturn action === \"deny\" ? matchDenyPattern(command, pattern) : matchAllowPattern(command, pattern);\n}\n\n/**\n * Built-in danger filter backing `auto` mode. These are matched with the\n * same paranoid strategy as `deny` rules (chain splitting, wrapper\n * unwrapping, substitution extraction), so `echo hi && rm -rf /` or\n * `bash -c \"sudo dd ...\"` still trip the filter.\n *\n * This is a *prompt* heuristic, not a security boundary: it decides which\n * unmatched commands fall back to approval instead of auto-allow. It can\n * never enumerate every destructive command — anything that must be hard\n * blocked belongs in a `deny` rule in `permissions.yml`.\n */\nexport const DANGEROUS_COMMAND_PATTERNS: readonly string[] = [\n\t// recursive/forced deletion (flag clusters normalize to sorted letters,\n\t// so `-rf`/`-fr` become `-fr` and are caught by the `-f*` prefix; bare\n\t// `-r`/`-R` by the `-r*` prefix via case-insensitive matching)\n\t\"rm -r*\",\n\t\"rm -f*\",\n\t// privilege escalation\n\t\"sudo *\",\n\t\"doas *\",\n\t\"su *\",\n\t// raw disk / filesystem surgery\n\t\"dd *\",\n\t\"mkfs*\",\n\t// system state\n\t\"shutdown*\",\n\t\"reboot*\",\n\t\"halt*\",\n\t\"poweroff*\",\n\t// blanket permission changes\n\t\"chmod 777 *\",\n\t\"chmod -R *\",\n\t\"chown -R *\",\n\t// outward-facing / history-rewriting git and publishing\n\t\"git push*\",\n\t\"git reset --hard*\",\n\t\"git clean*\",\n\t\"npm publish*\",\n\t\"yarn publish*\",\n\t\"pnpm publish*\",\n\t// pipe-to-shell installers\n\t\"curl * | *\",\n\t\"wget * | *\",\n\t// inline interpreter eval — the code payload is another language the gate\n\t// cannot parse, so `python -c \"os.system('rm -rf /')\"` would otherwise\n\t// sail through as \"not shell-dangerous\". Running a script *file*\n\t// (`python script.py`) is deliberately NOT flagged: it is everyday dev\n\t// work, and the gate cannot see file contents anyway (see the module doc\n\t// on interpreter escape hatches).\n\t\"python* -c*\",\n\t\"pypy* -c*\",\n\t\"node -e*\",\n\t\"node --eval*\",\n\t\"node -p*\",\n\t\"nodejs -e*\",\n\t\"nodejs --eval*\",\n\t\"nodejs -p*\",\n\t\"bun -e*\",\n\t\"bun --eval*\",\n\t\"deno eval*\",\n\t\"ruby -e*\",\n\t\"perl -e*\",\n\t\"php -r*\",\n];\n\n/**\n * Returns the first built-in dangerous pattern the command matches, or\n * `undefined` if the command passes the filter.\n */\nexport function findDangerousPattern(command: string): string | undefined {\n\treturn DANGEROUS_COMMAND_PATTERNS.find((pattern) => matchDenyPattern(command, pattern));\n}\n\n/**\n * `filePath` relative to `cwd`, resolved EXACTLY as the built-in tools resolve it (`resolveToCwd`:\n * `~` expansion, a leading `@`, `file://` URLs). The gate must judge the file the tool will open:\n * resolved naively, `~/.ssh/id_rsa` read as `<cwd>/~/.ssh/id_rsa`, inside the project, while the\n * read tool opened the real key.\n */\nfunction relativeToProject(filePath: string, cwd: string): string {\n\treturn relative(resolve(cwd), resolveToCwd(filePath, cwd));\n}\n\n/** A path argument as a forward-slash path relative to `cwd`, for glob matching. */\nfunction toMatchablePath(filePath: string, cwd: string): string {\n\treturn relativeToProject(filePath, cwd).split(sep).join(\"/\");\n}\n\n/** Whether `filePath` names a location inside `cwd`, as the tool will resolve it. */\nfunction isWithinProject(filePath: string, cwd: string): boolean {\n\tconst rel = relativeToProject(filePath, cwd);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\n/**\n * NOTE: this assumes the tool-call args carry a `command` string under the\n * exact key `command`. Verify every gated tool's argument shape matches\n * these hardcoded key names — a mismatch doesn't error, it just silently\n * fails to match any `pattern`/`paths` rule and falls through to the\n * (fail-safe) default decision.\n */\nfunction getCommandArg(args: Record<string, unknown>): string | undefined {\n\treturn typeof args.command === \"string\" ? args.command : undefined;\n}\n\n/**\n * Every path argument the call carries. Both keys count, whichever the tool reads: the built-in\n * tools read `path`, others `file_path`. Judging only one of them (`file_path` used to win) let a\n * call name an outside path in the key its tool reads and an inside one in the key the gate read.\n */\nfunction getPathArgs(args: Record<string, unknown>): string[] {\n\tconst paths: string[] = [];\n\tfor (const key of [\"file_path\", \"path\"] as const) {\n\t\tconst value = args[key];\n\t\tif (typeof value === \"string\" && !paths.includes(value)) paths.push(value);\n\t}\n\treturn paths;\n}\n\nfunction describeMatch(rule: PermissionRule): string {\n\tconst parts = [`tool=${rule.tool}`];\n\tif (rule.pattern !== undefined) parts.push(`pattern=${JSON.stringify(rule.pattern)}`);\n\tif (rule.paths !== undefined) parts.push(`paths=${JSON.stringify(rule.paths)}`);\n\treturn `matched rule (${parts.join(\", \")}) -> ${rule.action}`;\n}\n\n/**\n * A `tool: bash` rule's `pattern` is authored against bash command shapes, so\n * only its `deny` half is safe to reuse for `powershell` calls: a bash `deny`\n * over-matching onto a powershell command is the fail-safe direction, while a\n * bash `allow`/`approve` pattern (e.g. `ls *`) under-matching real\n * powershell syntax would otherwise create the illusion of coverage without\n * actually vetting powershell-specific danger. `tool: powershell` rules\n * (and `tool: \"*\"`) are unaffected and keep matching normally.\n */\nfunction bashDenyRuleAppliesToPowershell(rule: PermissionRule, toolName: string): boolean {\n\treturn toolName === \"powershell\" && rule.tool.toLowerCase() === \"bash\" && rule.action === \"deny\";\n}\n\nfunction toolMatchesRule(rule: PermissionRule, toolName: string): boolean {\n\treturn rule.tool === \"*\" || rule.tool.toLowerCase() === toolName || bashDenyRuleAppliesToPowershell(rule, toolName);\n}\n\nfunction ruleMatches(rule: PermissionRule, toolName: string, args: Record<string, unknown>, cwd: string): boolean {\n\tif (!toolMatchesRule(rule, toolName)) return false;\n\n\tif (rule.pattern !== undefined) {\n\t\tconst command = getCommandArg(args);\n\t\tif (command === undefined || !matchCommandPattern(command, rule.pattern, rule.action)) return false;\n\t}\n\n\tif (rule.paths !== undefined) {\n\t\tconst filePaths = getPathArgs(args);\n\t\tif (filePaths.length === 0) return false;\n\t\tconst globs = rule.paths;\n\t\tconst covered = (filePath: string) => {\n\t\t\tconst matchable = toMatchablePath(filePath, cwd);\n\t\t\treturn globs.some((pattern) => minimatch(matchable, pattern, { dot: true }));\n\t\t};\n\t\t// The same asymmetry as `pattern`: a deny rule fires on ANY path it names; an allow/approve\n\t\t// rule only when it covers EVERY path the call names, so it never authorizes one it does not.\n\t\tif (rule.action === \"deny\" ? !filePaths.some(covered) : !filePaths.every(covered)) return false;\n\t}\n\n\treturn true;\n}\n\nexport interface PermissionGateOptions {\n\t/** Project root used to determine whether a path is \"within the project\" for default decisions. Defaults to `process.cwd()`. */\n\tcwd?: string;\n\t/** Session permission mode; see `PermissionMode`. Defaults to `\"ask\"`. */\n\tmode?: PermissionMode;\n}\n\n/**\n * Evaluates tool calls against an ordered list of permission rules,\n * returning a `deny` / `allow` / `approve` decision.\n */\nexport class PermissionGate {\n\tprivate readonly rules: PermissionRule[];\n\tprivate readonly cwd: string;\n\tprivate readonly mode: PermissionMode;\n\n\tconstructor(rules: PermissionRule[] = [], options: PermissionGateOptions = {}) {\n\t\tthis.rules = rules;\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.mode = options.mode ?? \"ask\";\n\t}\n\n\t/** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */\n\tevaluate(toolName: string, args: Record<string, unknown> = {}): PermissionDecision {\n\t\tconst normalizedTool = toolName.toLowerCase();\n\n\t\tif (normalizedTool === \"bash\" || normalizedTool === \"powershell\") {\n\t\t\tconst command = getCommandArg(args);\n\t\t\tif (command !== undefined && commandDenyScanTruncated(command)) {\n\t\t\t\tconst denyRuleApplies = this.rules.some(\n\t\t\t\t\t(rule) => rule.action === \"deny\" && toolMatchesRule(rule, normalizedTool),\n\t\t\t\t);\n\t\t\t\tif (denyRuleApplies) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"deny\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"command has more chained/wrapped pieces than the deny scan can fully cover, and a deny rule applies to this tool; failing closed rather than risk missing a match\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const rule of this.rules) {\n\t\t\tif (ruleMatches(rule, normalizedTool, args, this.cwd)) {\n\t\t\t\treturn this.applyMode({ action: rule.action, reason: describeMatch(rule) });\n\t\t\t}\n\t\t}\n\n\t\treturn this.applyMode(this.defaultDecision(normalizedTool, args));\n\t}\n\n\t/**\n\t * Applies the session mode to a decision. `deny` is never relaxed by any\n\t * mode; `yolo` downgrades every `approve` to `allow`.\n\t */\n\tprivate applyMode(decision: PermissionDecision): PermissionDecision {\n\t\tif (this.mode === \"yolo\" && decision.action === \"approve\") {\n\t\t\treturn { action: \"allow\", reason: `yolo mode: auto-allowed (${decision.reason})` };\n\t\t}\n\t\treturn decision;\n\t}\n\n\tprivate defaultDecision(toolName: string, args: Record<string, unknown>): PermissionDecision {\n\t\tif (DEFAULT_ALLOWED_TOOLS.has(toolName)) {\n\t\t\treturn { action: \"allow\", reason: `no rule matched; \"${toolName}\" is allowed by default` };\n\t\t}\n\n\t\tif (this.mode === \"auto\" && AUTO_ALLOWED_DELEGATION_TOOLS.has(toolName)) {\n\t\t\treturn {\n\t\t\t\taction: \"allow\",\n\t\t\t\treason: `auto mode: no rule matched; \"${toolName}\" only starts agents that run this gate themselves`,\n\t\t\t};\n\t\t}\n\n\t\tif (toolName === \"bash\") {\n\t\t\tif (this.mode === \"auto\") {\n\t\t\t\tconst command = getCommandArg(args);\n\t\t\t\tif (command === undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason: \"auto mode: bash call without a command string requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst dangerous = findDangerousPattern(command);\n\t\t\t\tif (dangerous !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason: `auto mode: command matched dangerous pattern ${JSON.stringify(dangerous)}, requires approval`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (scanExecutedCode(command).truncated) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command nests deeper or runs more pieces than the scan covers, or opens a heredoc that never ends; requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandHeadIsDynamic(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command position is a variable/parameter expansion, command substitution, or backtick substitution, which can resolve to anything; requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandInvokesOtherShell(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command invokes a pwsh/powershell/cmd interpreter, which the bash-shaped danger filter has no coverage for; requires approval, same as the powershell tool\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandDenyScanTruncated(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command has more chained/wrapped pieces than the deny scan can fully cover, requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandFeedsBareShellWithoutDashC(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"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\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandFeedsCodeFromStdin(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command feeds an interpreter its program through stdin (pipe, heredoc or here-string), which the deny scan can't vet; requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (commandRunsProcessSubstitution(command)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\"auto mode: command runs code straight out of a process substitution, which the deny scan can't vet; requires approval\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { action: \"allow\", reason: \"auto mode: no rule matched and command passed the danger filter\" };\n\t\t\t}\n\t\t\treturn { action: \"approve\", reason: \"no rule matched; bash commands require approval by default\" };\n\t\t}\n\n\t\tif (toolName === \"powershell\") {\n\t\t\t// Unlike bash, powershell has no danger filter tuned for its own\n\t\t\t// syntax (DANGEROUS_COMMAND_PATTERNS is bash-shaped), so auto mode\n\t\t\t// cannot safely auto-allow it — every unmatched powershell call\n\t\t\t// requires approval in ask and auto mode (yolo's applyMode still\n\t\t\t// turns this approve into allow, as for every tool).\n\t\t\treturn { action: \"approve\", reason: \"no rule matched; powershell commands always require approval\" };\n\t\t}\n\n\t\tif (PATH_SCOPED_TOOLS.has(toolName)) {\n\t\t\tconst filePaths = getPathArgs(args);\n\t\t\tif (filePaths.length > 0 && filePaths.every((filePath) => isWithinProject(filePath, this.cwd))) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project (or missing), requires approval\",\n\t\t\t};\n\t\t}\n\n\t\tif (READ_ONLY_PATH_TOOLS.has(toolName)) {\n\t\t\t// Unlike read/write/edit, these tools treat a missing `path` as the\n\t\t\t// cwd, so an absent path arg is within the project by definition.\n\t\t\tconst filePaths = getPathArgs(args);\n\t\t\tconst searched = filePaths.length > 0 ? filePaths : [\".\"];\n\t\t\tif (searched.every((filePath) => isWithinProject(filePath, this.cwd))) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; read-only tool allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project, requires approval\",\n\t\t\t};\n\t\t}\n\n\t\treturn { action: \"approve\", reason: `no rule matched for tool \"${toolName}\"; defaults to approve` };\n\t}\n}\n"]}
|