TypeScript
fix: better shell syntax handling for labels (#9371)
Yash Singh0cb02abf5b3a
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.tsindex a0e68e3f82b..868aaa8db84 100644--- a/apps/mobile/src/lib/threadActivity.test.ts+++ b/apps/mobile/src/lib/threadActivity.test.ts@@ -1990,6 +1990,49 @@ describe("buildThreadFeed", () => {},);+ it("preserves serialized shell wrappers with non-matching boundary quotes", () => {+ const turnId = TurnId.make("turn-serialized-shell-wrapper");+ const command =+ "/bin/zsh -lc 'git status\nsed -n '\"'1,20p' apps/web/src/components/DiffPanel.tsx\"";+ const thread = makeThread({+ id: ThreadId.make("thread-serialized-shell-wrapper"),+ projectId: ProjectId.make("project-1"),+ title: "Serialized shell wrapper",+ latestTurn: {+ turnId,+ state: "running",+ requestedAt: "2026-04-01T00:00:00.000Z",+ startedAt: "2026-04-01T00:00:00.000Z",+ completedAt: null,+ assistantMessageId: null,+ },+ activities: [+ makeActivity({+ id: EventId.make("serialized-shell-wrapper"),+ kind: "tool.updated",+ tone: "tool",+ summary: "Ran command",+ createdAt: "2026-04-01T00:00:01.000Z",+ turnId,+ payload: {+ itemType: "command_execution",+ status: "inProgress",+ data: { item: { command } },+ },+ }),+ ],+ });++ const feed = buildThreadFeed(thread);+ expect(feed[0]).toMatchObject({+ type: "activity-group",+ activities: [{ workEntry: { command } }],+ });+ if (feed[0]?.type === "activity-group") {+ expect(feed[0].activities[0]?.workEntry.rawCommand).toBeUndefined();+ }+ });+it.each([["inProgress", true],["completed", false],diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex 5eb3c0cbf7b..564ab5e58ff 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -1001,6 +1001,11 @@ function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): strireturn null;}+ const openingQuote = command[0];+ if ((openingQuote === "'" || openingQuote === '"') && !command.endsWith(openingQuote)) {+ return null;+ }+const unwrapped = trimMatchingOuterQuotes(command);return unwrapped.length > 0 ? unwrapped : null;}diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.tsindex baa57e8f99f..5dade8459e0 100644--- a/apps/web/src/session-logic.test.ts+++ b/apps/web/src/session-logic.test.ts@@ -1578,6 +1578,26 @@ describe("deriveWorkLogEntries", () => {expect(entry?.rawCommand).toBeUndefined();});+ it("preserves serialized shell wrappers with non-matching boundary quotes", () => {+ const command =+ "/bin/zsh -lc 'git status\nsed -n '\"'1,20p' apps/web/src/components/DiffPanel.tsx\"";+ const activities: OrchestrationThreadActivity[] = [+ makeActivity({+ id: "command-tool-serialized-wrapper",+ kind: "tool.completed",+ summary: "Ran command",+ payload: {+ itemType: "command_execution",+ data: { item: { command } },+ },+ }),+ ];++ const [entry] = deriveWorkLogEntries(activities);+ expect(entry?.command).toBe(command);+ expect(entry?.rawCommand).toBeUndefined();+ });+it("keeps compact Codex tool metadata used for icons and labels", () => {const activities: OrchestrationThreadActivity[] = [makeActivity({diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex fcaa5e9e175..c6c7410bebe 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -1381,6 +1381,11 @@ function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): strireturn null;}+ const openingQuote = command[0];+ if ((openingQuote === "'" || openingQuote === '"') && !command.endsWith(openingQuote)) {+ return null;+ }+const unwrapped = trimMatchingOuterQuotes(command);return unwrapped.length > 0 ? unwrapped : null;}diff --git a/packages/client-runtime/src/work-log/commandLabel.test.ts b/packages/client-runtime/src/work-log/commandLabel.test.tsindex 1cee96e2f2b..15380032d06 100644--- a/packages/client-runtime/src/work-log/commandLabel.test.ts+++ b/packages/client-runtime/src/work-log/commandLabel.test.ts@@ -17,6 +17,7 @@ describe("commandProgramName", () => {["env CI=1 /bin/zsh -lc '\"/Applications/My Tools/bin/check\" --verbose'", "check"],["bash -lc \"zsh -c 'git status'\"", "git"],['"C:\\Program Files\\Git\\bin\\bash.exe" -lc "git status"', "git"],+ ["/bin/zsh -lc 'git status\nsed -n '\"'1,20p' apps/web/src/components/DiffPanel.tsx\"", "git"],])("unwraps shell scripts without executing them: %s", (command, program) => {expect(commandProgramName(command)).toBe(program);});@@ -32,6 +33,9 @@ describe("commandProgramName", () => {["bash -- -c 'git status'", "bash"],["bash --rcfile config.sh", "bash"],["my-shell -c 'git status'", "my-shell"],+ ["$HOME/.bun/bin/bun test", "bun"],+ ['"$ANDROID_HOME/emulator/emulator" -list-avds', "emulator"],+ ["${ROOT}/bin/tool --version", "tool"],])("preserves ordinary programs and actual shell launches: %s", (command, program) => {expect(commandProgramName(command)).toBe(program);});@@ -47,6 +51,402 @@ describe("commandProgramName", () => {expect(commandProgramName(command)).toBeNull();});+ it.each([+ "if test -f package.json; then vp test; fi",+ "[ -f package.json ]",+ "[[ -f package.json ]]",+ "test -f package.json",+ 'for file in *; do echo "$file"; done',+ "while true; do sleep 1; done",+ "until false; do sleep 1; done",+ "case $name in test) vp test;; esac",+ 'select item in one two; do echo "$item"; done',+ "function check() { vp test; }",+ "check() { vp test; }",+ "k(){ echo ok; }; k",+ "{ vp test; }",+ "(vp test)",+ "(( count += 1 ))",+ "! vp test",+ ":",+ ". ./script.sh",+ "source ./script.sh",+ "eval 'vp test'",+ "cd packages/client-runtime",+ "export NODE_ENV=test",+ "local name=value",+ "set -e",+ "alias ll='ls -la'",+ "repeat 3 echo ok",+ "and vp test",+ "return 1",+ "break",+ "continue",+ "true",+ "false",+ ])("falls back for shell syntax and internal control commands: %s", (command) => {+ expect(commandProgramName(command)).toBeNull();+ });++ it.each([+ ['rg -n "if|for|while" src', "rg"],+ ["printf '%s\\n' 'a;b|c'", "printf"],+ ["node -e \"if (true) console.log('ok')\"", "node"],+ ["echo '$(git status)'", "echo"],+ ["vp test && git status", "vp"],+ ["vp test || git status", "vp"],+ ["rg needle src | head", "rg"],+ ["vp test; git status", "vp"],+ ["vp test &", "vp"],+ ["vp test\ngit status", "vp"],+ ['echo "$(git status)"', "echo"],+ ["echo `git status`", "echo"],+ ["cat <(rg needle src)", "cat"],+ ])("uses the first executable-looking program: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["cd packages/client-runtime && vp test run", "vp"],+ ['cd "a path with spaces"; git status', "git"],+ ["cd apps/web\npnpm test", "pnpm"],+ ["cd first && cd second && bun test", "bun"],+ ["CI=1 cd apps/web && npm test", "npm"],+ ["PATH+=:/tools npm test", "npm"],+ ["PATH+=:/tools && npm test", "npm"],+ ['TMP=$(mktemp -d); cd "$TMP"; npm pack ./package', "npm"],+ ["cd $(find . -type d | head -1) && git status", "git"],+ ["cd `find . -type d | head -1` && node script.js", "node"],+ ["cd /tmp 2>&1 && npm test", "npm"],+ ["cd /tmp 2<&0 && pnpm test", "pnpm"],+ ["cd /tmp &>/dev/null && bun test", "bun"],+ ["cd work |& npm test", "npm"],+ ["cd /tmp && # use the selected workspace\nnpm test", "npm"],+ ["export CI=1; # first note\n# second note\npnpm test", "pnpm"],+ ["cd&&npm test", "npm"],+ ["export CI=1;pnpm test", "pnpm"],+ ["cd ${ROOT:-path;with;semicolons} && bun test", "bun"],+ ["cd ${ROOT:-path&&fallback} && node app.js", "node"],+ ["cd @(first|second) && npm test", "npm"],+ ["cd /tmp \\\n&& npm test", "npm"],+ ["/bin/zsh -lc 'cd apps/web && vp test run'", "vp"],+ ])("skips leading cd commands and uses the next useful program: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["source ~/.nvm/nvm.sh && nvm use", "nvm"],+ [". ./.env && pnpm test", "pnpm"],+ ["export CI=1 && vp test run", "vp"],+ ["unset DEBUG; node app.js", "node"],+ ["export CI=1 && cd apps/web && pnpm test", "pnpm"],+ ["/bin/zsh -lc 'source ~/.nvm/nvm.sh && nvm use'", "nvm"],+ ])("skips shell setup commands and uses the next useful program: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["set -eu; npm test", "npm"],+ [": && npm test", "npm"],+ ["true && npm test", "npm"],+ ["false || npm test", "npm"],+ ["false; npm test", "npm"],+ ["sudo -n true && npm test", "npm"],+ ["sudo -n true; echo checked", "echo"],+ ["test -d node_modules || vp i", "vp"],+ ["[ -d node_modules ] || vp i", "vp"],+ ])("skips non-descriptive shell commands before a useful program: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each(+ ["cd /tmp", "export CI=1", "unset DEBUG", "source env.sh", ". env.sh"].flatMap((setup) =>+ ["&&", " || ", ";", "\n", "|", " |& ", " & "].map(+ (operator) => [`${setup}${operator}npm test`, "npm"] as const,+ ),+ ),+ )("handles shell setup followed by every command separator: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["command git status", "git"],+ ["command -p git status", "git"],+ ["command -- git status", "git"],+ ["builtin printf ok", "printf"],+ ["builtin -- echo ok", "echo"],+ ["command cd /tmp && npm test", "npm"],+ ["builtin cd /tmp && pnpm test", "pnpm"],+ ["exec node app.js", "node"],+ ["exec -cl -a worker node app.js", "node"],+ ["exec env CI=1 /opt/tools/check --verbose", "check"],+ ['exec "C:\\Program Files\\nodejs\\node.exe" app.js', "node.exe"],+ ["exec sh -c 'cd /tmp && npm test'", "npm"],+ ["exec sh -c 'cd /tmp\nnpm test'", "npm"],+ ["exec bash -c 'set -e\nnpm test'", "npm"],+ ])("unwraps shell command wrappers: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["timeout 10 pnpm test", "pnpm"],+ ["timeout 10s python3 script.py", "python3"],+ ["gtimeout 1.5 node app.js", "node"],+ ["nohup npx expo start >/tmp/metro.log 2>&1 &", "npx"],+ ["nohup -- env CI=1 bun test", "bun"],+ ["arch -x86_64 ./build/app-under-test", "app-under-test"],+ ["arch -arch arm64 /opt/tools/check", "check"],+ ["bundle exec pod install", "pod"],+ ["timeout 30 nohup env CI=1 node app.js", "node"],+ ["timeout 60 script -q /dev/null env CI=1 node app.js", "node"],+ ])("unwraps process-launch wrappers: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["& 'C:\\Program Files\\nodejs\\node.exe' script.js", "node.exe"],+ ['& "$env:WINDIR\\Microsoft.NET\\Framework64\\v4\\csc.exe" file.cs', "csc.exe"],+ ])("resolves literal PowerShell call operators: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["$env:CI='1'; npm test", "npm"],+ ["$value = 'configured'; node app.js", "node"],+ ["$process = Get-Process node; $process.Id", "Get-Process"],+ ["$tmp = Join-Path $env:TEMP repo; git clone example", "Join-Path"],+ ["$html = (Invoke-WebRequest https://example.com).Content", "Invoke-WebRequest"],+ ["$process = Start-Process -FilePath .\\app.exe -PassThru; $process.Id", "app.exe"],+ ])("labels commands inside simple PowerShell assignments: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["cmd /c bcdedit /enum", "bcdedit"],+ ["cmd /c cd C:\\work && npm test", "npm"],+ ['cmd.exe /d /s /c "cd C:\\work && npm test"', "npm"],+ [+ 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\\work\\scripts\\doctor.ps1"',+ "doctor.ps1",+ ],+ ['pwsh -NoProfile -Command "Set-Location C:\\work; pnpm test"', "pnpm"],+ ["pwsh -Command Set-Location C:\\work; pnpm test", "pnpm"],+ ])("unwraps Windows shell launchers: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["Set-Location C:\\work; npm test", "npm"],+ ["Push-Location C:\\work; node app.js", "node"],+ ["Start-Process -FilePath node -ArgumentList server.js", "node"],+ ["Start-Process -ArgumentList '-FilePath helper' node", "node"],+ ["Start-Process -ErrorAction Stop -FilePath node", "node"],+ ["Start-Process -NoNewWindow -WorkingDirectory C:\\work node", "node"],+ ['Start-Process "C:\\Program Files\\Example\\app.exe"', "app.exe"],+ ['Start-Process -FilePath ".\\dist\\Example App.exe" -PassThru', "Example App.exe"],+ [".\\.venv\\Scripts\\python.exe script.py", "python.exe"],+ ["$env:LOCALAPPDATA\\Programs\\tool.exe --version", "tool.exe"],+ ['"=== CHECK FILE ==="; Get-Content file.txt', "Get-Content"],+ ["$x = @'\ndata'; Get-Fake\n'@\nGet-Process", "Get-Process"],+ ["@'\nprint('ok; still data')\n'@ | python -", "python"],+ ])("handles common PowerShell setup and launch commands: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["timeout --help", "timeout"],+ ["nohup --version", "nohup"],+ ["arch", "arch"],+ ["bundle install", "bundle"],+ ["script output.log", "script"],+ ["/usr/bin/timeout 10 node app.js", "timeout"],+ ])("keeps process-launch wrappers when no safe payload is present: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ "command -v git",+ "command -V git",+ "command -a git",+ "command -pv git",+ "builtin -p",+ "exec",+ "exec > output.log",+ "exec --",+ "exec cd /tmp && npm test",+ "exec env CI=1 cd /tmp && npm test",+ "exec CI=1 npm test",+ "env CI=1 cd /tmp && npm test",+ "env CI=1; npm test",+ "sudo cd /tmp && npm test",+ "command CI=1 npm test",+ "command false && npm test",+ "cmd /c false && npm test",+ "cd /tmp <<EOF\nunterminated heredoc",+ "cd /tmp && >/tmp/log",+ "(xcrun simctl io booted recordVideo /tmp/video.mp4 &) ; wait",+ "export CI=1 && (bundle exec pod install || pod install)",+ "$PY scripts/check.py",+ "${TOOL} --version",+ "%TOOL% --version",+ "!TOOL! --version",+ "& $tool --version",+ "& { Get-Process }",+ "$value = 'configured'",+ "$headers = @{ 'Accept' = 'application/json'; 'Content-Type' = 'application/json' }; Invoke-WebRequest https://example.com",+ '"sha256(value)=$hash"',+ "broken{",+ "@echo off",+ ":: comment",+ "time -- npm test",+ "time -v npm test",+ "coproc npm test",+ "coproc worker { npm test; }",+ "cd [first|second] && pnpm test",+ "npm) --version",+ "try { Invoke-WebRequest https://example.com } catch { Write-Error $_ }",+ "for($i=0; $i -lt 2; $i++){ Start-Sleep 1 }",+ "# comment only",+ ])("does not treat shell lookup and commandless wrapper forms as executions: %s", (command) => {+ expect(commandProgramName(command)).toBeNull();+ });++ it.each([+ ["parallel -j4", "parallel"],+ ["hash --help", "hash"],+ ["process --help", "process"],+ ["rem comment", "rem"],+ ["Exec node app.js", "Exec"],+ ["CD /tmp && npm test", "CD"],+ ])("does not hide legitimate or case-distinct program names: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["env sh -c 'cd /tmp && npm test'", "npm"],+ ["sudo zsh -lc 'export CI=1 && pnpm test'", "pnpm"],+ ])("parses shell setup inside an explicitly launched shell: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["nocorrect pnpm test", "pnpm"],+ ["noglob bun test", "bun"],+ ["time node app.js", "node"],+ ["time -p deno test", "deno"],+ ["time nocorrect npm test", "npm"],+ ])("skips shell precommand modifiers: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it("uses the command after leading shell comments", () => {+ expect(commandProgramName("# first comment\n # second comment\ngit status")).toBe("git");+ });++ it.each([+ ["CI=1 # note\nnpm test", "npm"],+ ["CI=1 # it's configured\nnpm test", "npm"],+ ['CI=1 # "unterminated quote\nbun test', "bun"],+ [">/tmp/log # note\npnpm test", "pnpm"],+ [">/tmp/log # it's configured\ndeno test", "deno"],+ ])("skips comments after commandless shell setup: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["./cd /tmp && npm test", "cd"],+ ["/opt/exec node app.js", "exec"],+ ["/usr/bin/time npm test", "time"],+ ["/usr/bin/test -f package.json", "test"],+ ])("does not treat qualified paths as shell syntax: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it("skips a shell array assignment before the command", () => {+ expect(commandProgramName("items=(one two); npm test")).toBe("npm");+ });++ it.each([+ ['EMU="/opt/android/emulator"; "$EMU" -list-avds', "emulator"],+ ["AAPT=/opt/android/aapt2\n$AAPT dump badging app.apk", "aapt2"],+ [+ 'SSH=(ssh -i /tmp/key -o IdentitiesOnly=yes); HOST=user@example; "${SSH[@]}" "$HOST" uptime',+ "ssh",+ ],+ ["SCP=(/usr/bin/scp -i /tmp/key); if true; then ${SCP[@]} file user@example:/tmp; fi", "scp"],+ ['TOOL="/Applications/My Tool/bin/check"; "$TOOL" --verbose', "check"],+ ])("resolves literal command aliases from earlier shell segments: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ 'TOOL=$(pick-command); "$TOOL" --version',+ 'TOOL="git status"; "$TOOL"',+ "# TOOL=git\n$TOOL status",+ 'TOOL=git true; "$TOOL" status',+ 'TOOL=git; TOOL=$(pick-command); "$TOOL" status',+ 'TOOL=git; unset TOOL; "$TOOL" status',+ ])("does not evaluate dynamic or non-persistent command aliases: %s", (command) => {+ expect(commandProgramName(command)).toBeNull();+ });++ it("does not retain aliases assigned inside control flow", () => {+ expect(commandProgramName('TOOL=git; if false; then\nTOOL=npm\nfi\n"$TOOL" status')).toBe(+ "git",+ );+ });++ it.each([+ ["ROOT=${BASE:-path with spaces}; npm test", "npm"],+ ["ROOT=`printf 'path with spaces'`; pnpm test", "pnpm"],+ ])("keeps expansions inside assignment words: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ [">/tmp/log && npm test", "npm"],+ ["2>/tmp/error.log; pnpm test", "pnpm"],+ ["cd /tmp && >/tmp/log npm test", "npm"],+ ["cd /tmp && > /tmp/log pnpm test", "pnpm"],+ ["cd /tmp && 2>&1 bun test", "bun"],+ ["cd /tmp && 2>& 1 node app.js", "node"],+ ["cd /tmp && &>/tmp/log git status", "git"],+ ["cd /tmp && *>>/tmp/log vp test", "vp"],+ ["cd /tmp && {output}>/tmp/log deno test", "deno"],+ ["cd /tmp && <<<input ruby script.rb", "ruby"],+ ])("skips redirections before the next command: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each([+ ["cd /tmp <<EOF\nnot-a-command\nEOF\nnpm test", "npm"],+ ["cd /tmp <<'EOF'\nnot-a-command\nEOF\npnpm test", "pnpm"],+ ["cd /tmp <<'EOF'\nnot-a-command\\\nEOF\npnpm test", "pnpm"],+ ["cd /tmp <<-EOF\n\tnot-a-command\n\tEOF\nbun test", "bun"],+ ["cd /tmp <<A <<B\none\nA\ntwo\nB\ngit status", "git"],+ ["cd /tmp <<EOF; # setup\nnot-a-command\nEOF\nnpm test", "npm"],+ ["cd /tmp <<EOF && pnpm test\nnot-a-command\nEOF\nbun test", "pnpm"],+ ])("skips heredoc bodies before finding the next command: %s", (command, program) => {+ expect(commandProgramName(command)).toBe(program);+ });++ it.each(["cd apps/web && [ -f package.json ]", "cd apps/web || exit 1", "cd one && cd two"])(+ "falls back when no useful program follows cd: %s",+ (command) => {+ expect(commandProgramName(command)).toBeNull();+ },+ );++ it.each([+ "if test -f package.json\nthen\n npm test\nfi",+ "[[ -d first && -d second ]] && npm test",+ 'for file in *\ndo\n echo "$file"\ndone',+ "while true\ndo\n sleep 1\ndone",+ "cd /tmp; build () { npm test; }",+ ])("does not label commands inside multiline shell control flow: %s", (command) => {+ expect(commandProgramName(command)).toBeNull();+ });+it("bounds nested shell unwrapping", () => {let command = "git status";for (let depth = 0; depth < 9; depth += 1) {@@ -54,4 +454,26 @@ describe("commandProgramName", () => {}expect(commandProgramName(command)).toBeNull();});++ it("does not spend the shell nesting budget on setup commands", () => {+ const command = [+ ...Array.from({ length: 10 }, (_, index) => `export VALUE_${index}=configured`),+ "npm test",+ ].join("\n");++ expect(commandProgramName(command)).toBe("npm");+ });++ it("bounds the number of top-level setup segments", () => {+ const command = [+ ...Array.from({ length: 2_000 }, (_, index) => `export VALUE_${index}=configured`),+ "npm test",+ ].join(";");++ expect(commandProgramName(command)).toBeNull();+ });++ it("bounds nested command wrappers", () => {+ expect(commandProgramName(`${"command ".repeat(9)}git status`)).toBeNull();+ });});diff --git a/packages/client-runtime/src/work-log/commandLabel.ts b/packages/client-runtime/src/work-log/commandLabel.tsindex d3cd945bf3f..c074def03eb 100644--- a/packages/client-runtime/src/work-log/commandLabel.ts+++ b/packages/client-runtime/src/work-log/commandLabel.ts@@ -1,7 +1,203 @@type CommandWrapper = "env" | "sudo";+type CommandProgramContext = "exec" | "shell";++const MAX_COMMAND_SEGMENTS = 64;const SHELL_PROGRAMS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish"]);+const WINDOWS_SHELL_PROGRAMS = new Set([+ "cmd",+ "cmd.exe",+ "powershell",+ "powershell.exe",+ "pwsh",+ "pwsh.exe",+]);const SHELL_OPTIONS_WITH_VALUE = new Set(["-o", "-O", "--rcfile", "--init-file"]);+const SHELL_COMMAND_WRAPPERS = new Set(["builtin", "command", "exec"]);+const SHELL_PRECOMMAND_MODIFIERS = new Set(["nocorrect", "noglob", "time"]);+const POWERSHELL_SETUP_PROGRAMS = new Set(["pop-location", "push-location", "set-location"]);+const POWERSHELL_FLAGS = new Set(["-mta", "-nologo", "-noninteractive", "-noprofile", "-sta"]);+const POWERSHELL_OPTIONS_WITH_VALUE = new Set([+ "-configurationname",+ "-executionpolicy",+ "-inputformat",+ "-outputformat",+ "-version",+ "-windowstyle",+ "-workingdirectory",+]);+const START_PROCESS_FLAGS = new Set([+ "-confirm",+ "-debug",+ "-loaduserprofile",+ "-nonewwindow",+ "-passthru",+ "-usenewenvironment",+ "-verbose",+ "-wait",+ "-whatif",+]);+const START_PROCESS_OPTIONS_WITH_VALUE = new Set([+ "-argumentlist",+ "-credential",+ "-environment",+ "-erroraction",+ "-errorvariable",+ "-informationaction",+ "-informationvariable",+ "-outbuffer",+ "-outvariable",+ "-pipelinevariable",+ "-progressaction",+ "-redirectstandarderror",+ "-redirectstandardinput",+ "-redirectstandardoutput",+ "-verb",+ "-warningaction",+ "-warningvariable",+ "-windowstyle",+ "-workingdirectory",+]);+const SKIPPABLE_SUDO_PROBES = new Set(["[", "[[", "test", "true"]);+const NON_PROGRAM_PREFIX_CHARACTERS = "<>(){}[];|&$`#!%@:";+const NON_PROGRAM_SUFFIX_CHARACTERS = "){]}`";++// These tokens describe shell syntax or shell-local control flow, not a useful+// executable name. Falling back to "command" is less misleading than labels+// such as "Ran if", "Ran [", or "Ran function".+const NON_DESCRIPTIVE_SHELL_PROGRAMS = new Set([+ "!",+ "#",+ ".",+ ":",+ "[",+ "[[",+ "alias",+ "and",+ "autoload",+ "begin",+ "bg",+ "bind",+ "bindkey",+ "break",+ "builtin",+ "caller",+ "case",+ "catch",+ "cd",+ "command",+ "compgen",+ "complete",+ "compopt",+ "continue",+ "coproc",+ "declare",+ "dirs",+ "disown",+ "do",+ "done",+ "elif",+ "else",+ "enable",+ "end",+ "esac",+ "eval",+ "exec",+ "exit",+ "export",+ "false",+ "fc",+ "fg",+ "fi",+ "finally",+ "for",+ "foreach",+ "function",+ "getopts",+ "history",+ "if",+ "in",+ "jobs",+ "let",+ "local",+ "logout",+ "mapfile",+ "nocorrect",+ "noglob",+ "not",+ "or",+ "popd",+ "pushd",+ "read",+ "readarray",+ "readonly",+ "repeat",+ "return",+ "select",+ "set",+ "setopt",+ "shift",+ "shopt",+ "source",+ "switch",+ "suspend",+ "test",+ "then",+ "time",+ "times",+ "trap",+ "try",+ "true",+ "type",+ "typeset",+ "ulimit",+ "umask",+ "unalias",+ "until",+ "unset",+ "unsetopt",+ "wait",+ "while",+]);++// Unlike setup builtins, these can make later segments part of control flow or+// otherwise unreachable, so do not use a later program as the command label.+const TERMINAL_SHELL_PROGRAMS = new Set([+ "and",+ "begin",+ "break",+ "case",+ "catch",+ "continue",+ "coproc",+ "do",+ "done",+ "elif",+ "else",+ "end",+ "esac",+ "eval",+ "exec",+ "exit",+ "false",+ "fi",+ "finally",+ "for",+ "foreach",+ "function",+ "if",+ "in",+ "not",+ "or",+ "repeat",+ "return",+ "select",+ "switch",+ "then",+ "try",+ "until",+ "while",+]);function shellCommandArgumentIndex(tokens: ReadonlyArray<string>, start: number): number | null {for (let index = start; index < tokens.length; index += 1) {@@ -32,7 +228,9 @@ function tokenizeShellCommand(command: string): string[] | null {let current = "";let quote: '"' | "'" | null = null;let escaping = false;+ let inBackticks = false;let substitutionDepth = 0;+ let parameterExpansionDepth = 0;let tokenStarted = false;for (let index = 0; index < input.length; index += 1) {@@ -45,9 +243,9 @@ function tokenizeShellCommand(command: string): string[] | null {}if (character === "\\" && quote !== "'") {const nextCharacter = input[index + 1];- const isWindowsDrivePath = quote === null && /^[A-Za-z]:/.test(current);+ const isWindowsPath = quote === null && /^(?:[A-Za-z]:|\.{1,2})(?:\\[^\s]*)?$/u.test(current);if (- (quote === '"' || isWindowsDrivePath) &&+ (quote === '"' || isWindowsPath) &&nextCharacter !== undefined &&nextCharacter !== '"' &&nextCharacter !== "\\" &&@@ -63,6 +261,12 @@ function tokenizeShellCommand(command: string): string[] | null {tokenStarted = true;continue;}+ if (inBackticks) {+ current += character;+ if (character === "`") inBackticks = false;+ tokenStarted = true;+ continue;+ }if (quote !== null) {if (character === quote) {quote = null;@@ -72,6 +276,31 @@ function tokenizeShellCommand(command: string): string[] | null {tokenStarted = true;continue;}+ if (character === "`") {+ current += character;+ inBackticks = true;+ tokenStarted = true;+ continue;+ }+ if (character === "$" && input[index + 1] === "{") {+ current += "${";+ parameterExpansionDepth += 1;+ tokenStarted = true;+ index += 1;+ continue;+ }+ if (character === "{" && parameterExpansionDepth > 0) {+ current += character;+ parameterExpansionDepth += 1;+ tokenStarted = true;+ continue;+ }+ if (character === "}" && parameterExpansionDepth > 0) {+ current += character;+ parameterExpansionDepth -= 1;+ tokenStarted = true;+ continue;+ }if (character === "$" && input[index + 1] === "(") {current += "$(";substitutionDepth += 1;@@ -79,6 +308,12 @@ function tokenizeShellCommand(command: string): string[] | null {index += 1;continue;}+ if (character === "(") {+ current += character;+ substitutionDepth += 1;+ tokenStarted = true;+ continue;+ }if (character === ")" && substitutionDepth > 0) {current += character;substitutionDepth -= 1;@@ -91,7 +326,7 @@ function tokenizeShellCommand(command: string): string[] | null {continue;}if (/\s/u.test(character)) {- if (substitutionDepth > 0) {+ if (substitutionDepth > 0 || parameterExpansionDepth > 0) {current += character;tokenStarted = true;continue;@@ -107,28 +342,843 @@ function tokenizeShellCommand(command: string): string[] | null {tokenStarted = true;}- if (quote !== null || escaping || substitutionDepth > 0) return null;+ if (+ quote !== null ||+ escaping ||+ inBackticks ||+ substitutionDepth > 0 ||+ parameterExpansionDepth > 0+ ) {+ return null;+ }if (tokenStarted) tokens.push(current);return tokens;}-export function commandProgramName(command: string, depth = 0): string | null {- if (depth >= 8) return null;- const tokens = tokenizeShellCommand(command);+type ShellCommandSplit = {+ readonly firstCommand: string;+ readonly remainingCommand: string | null;+ readonly separator: string | null;+};++type Heredoc = {+ readonly delimiter: string;+ readonly stripTabs: boolean;+};++type ShellSeparator = {+ readonly index: number;+ readonly length: number;+};++type ShellCommentRange = {+ readonly start: number;+ readonly end: number;+};++function commandWithoutShellComments(+ command: string,+ end: number,+ comments: ReadonlyArray<ShellCommentRange>,+): string {+ let result = "";+ let cursor = 0;+ for (const comment of comments) {+ if (comment.start >= end) break;+ result += command.slice(cursor, comment.start);+ cursor = Math.min(comment.end, end);+ }+ return result + command.slice(cursor, end);+}++function readHeredocDelimiter(+ command: string,+ start: number,+ stripTabs: boolean,+): { readonly heredoc: Heredoc; readonly end: number } | null {+ let index = start;+ while (command[index] === " " || command[index] === "\t") index += 1;++ let delimiter = "";+ let quote: '"' | "'" | null = null;+ let escaping = false;+ for (; index < command.length; index += 1) {+ const character = command[index]!;+ if (escaping) {+ delimiter += character;+ escaping = false;+ continue;+ }+ if (character === "\\" && quote !== "'") {+ escaping = true;+ continue;+ }+ if (quote !== null) {+ if (character === quote) quote = null;+ else delimiter += character;+ continue;+ }+ if (character === '"' || character === "'") {+ quote = character;+ continue;+ }+ if (/\s/u.test(character) || ";&|<>()".includes(character)) break;+ delimiter += character;+ }++ if (!delimiter || quote !== null || escaping) return null;+ return { heredoc: { delimiter, stripTabs }, end: index };+}++function commandAfterHeredocs(+ command: string,+ start: number,+ heredocs: ReadonlyArray<Heredoc>,+): string | null {+ let cursor = start;+ for (const heredoc of heredocs) {+ let foundDelimiter = false;+ while (cursor <= command.length) {+ const newlineIndex = command.indexOf("\n", cursor);+ const lineEnd = newlineIndex === -1 ? command.length : newlineIndex;+ const line = command.slice(cursor, lineEnd).replace(/\r$/u, "");+ const comparableLine = heredoc.stripTabs ? line.replace(/^\t+/u, "") : line;+ cursor = newlineIndex === -1 ? command.length : newlineIndex + 1;+ if (comparableLine === heredoc.delimiter) {+ foundDelimiter = true;+ break;+ }+ if (newlineIndex === -1) break;+ }+ if (!foundDelimiter) return null;+ }++ return command.slice(cursor).trim() || null;+}++function splitFirstShellCommand(command: string): ShellCommandSplit {+ let quote: '"' | "'" | null = null;+ let powerShellHereStringQuote: '"' | "'" | null = null;+ let escaping = false;+ let inBackticks = false;+ let inComment = false;+ let substitutionDepth = 0;+ let parameterExpansionDepth = 0;+ const heredocs: Heredoc[] = [];+ const comments: ShellCommentRange[] = [];+ let commentStart = 0;+ let separatorBeforeHeredocs: ShellSeparator | null = null;++ for (let index = 0; index < command.length; index += 1) {+ const character = command[index]!;+ if (powerShellHereStringQuote !== null) {+ if (+ character === powerShellHereStringQuote &&+ command[index + 1] === "@" &&+ (index === 0 || command[index - 1] === "\n")+ ) {+ powerShellHereStringQuote = null;+ index += 1;+ }+ continue;+ }+ if (inComment) {+ if (character !== "\n") continue;+ inComment = false;+ comments.push({ start: commentStart, end: index });+ }+ if (escaping) {+ escaping = false;+ continue;+ }+ if (character === "\\" && quote !== "'") {+ escaping = true;+ continue;+ }+ if (inBackticks) {+ if (character === "`") inBackticks = false;+ continue;+ }+ if (quote !== null) {+ if (character === quote) quote = null;+ continue;+ }+ if (+ character === "@" &&+ (command[index + 1] === '"' || command[index + 1] === "'") &&+ (command[index + 2] === "\n" || (command[index + 2] === "\r" && command[index + 3] === "\n"))+ ) {+ powerShellHereStringQuote = command[index + 1] as '"' | "'";+ index += 1;+ continue;+ }+ if (character === '"' || character === "'") {+ quote = character;+ continue;+ }+ if (character === "`") {+ inBackticks = true;+ continue;+ }+ if (+ character === "#" &&+ (index === 0 || /\s/u.test(command[index - 1]!) || ";&|(".includes(command[index - 1]!))+ ) {+ inComment = true;+ commentStart = index;+ continue;+ }+ if (character === "$" && command[index + 1] === "{") {+ parameterExpansionDepth += 1;+ index += 1;+ continue;+ }+ if (character === "{" && parameterExpansionDepth > 0) {+ parameterExpansionDepth += 1;+ continue;+ }+ if (character === "}" && parameterExpansionDepth > 0) {+ parameterExpansionDepth -= 1;+ continue;+ }+ if (character === "(") {+ substitutionDepth += 1;+ continue;+ }+ if (character === ")" && substitutionDepth > 0) {+ substitutionDepth -= 1;+ continue;+ }+ if (substitutionDepth > 0 || parameterExpansionDepth > 0) continue;++ if (character === "<" && command[index + 1] === "<" && command[index + 2] !== "<") {+ const stripTabs = command[index + 2] === "-";+ const delimiter = readHeredocDelimiter(command, index + (stripTabs ? 3 : 2), stripTabs);+ if (delimiter === null) {+ return { firstCommand: command.trim(), remainingCommand: null, separator: null };+ }+ heredocs.push(delimiter.heredoc);+ index = delimiter.end - 1;+ continue;+ }++ const isDoubleOperator =+ (character === "&" && command[index + 1] === "&") ||+ (character === "|" && (command[index + 1] === "|" || command[index + 1] === "&"));+ const isRedirectionAmpersand =+ character === "&" &&+ (command[index - 1] === ">" || command[index - 1] === "<" || command[index + 1] === ">");+ if ((!isDoubleOperator && !";&|\n".includes(character)) || isRedirectionAmpersand) continue;++ if (character === "\n" && heredocs.length > 0) {+ const separator = separatorBeforeHeredocs;+ const firstCommand = commandWithoutShellComments(+ command,+ separator?.index ?? index,+ comments,+ ).trimStart();+ const commandBeforeHeredocs = separator+ ? command.slice(separator.index + separator.length, index).trim()+ : "";+ const commandFollowingHeredocs = commandAfterHeredocs(command, index + 1, heredocs);+ const remainingCommand = [commandBeforeHeredocs, commandFollowingHeredocs]+ .filter((part): part is string => Boolean(part))+ .join("\n");+ return {+ firstCommand,+ remainingCommand: remainingCommand || null,+ separator: separator+ ? command.slice(separator.index, separator.index + separator.length)+ : "\n",+ };+ }+ if (heredocs.length > 0) {+ separatorBeforeHeredocs ??= {+ index,+ length: isDoubleOperator ? 2 : 1,+ };+ if (isDoubleOperator) index += 1;+ continue;+ }++ const firstCommand = commandWithoutShellComments(command, index, comments).trimStart();+ let nextCommandIndex = index + (isDoubleOperator ? 2 : 1);+ while (/\s/u.test(command[nextCommandIndex] ?? "")) nextCommandIndex += 1;+ const nextCommand = command.slice(nextCommandIndex).trim();+ return {+ firstCommand,+ remainingCommand: nextCommand || null,+ separator: isDoubleOperator ? command.slice(index, index + 2) : character,+ };+ }++ if (inComment) comments.push({ start: commentStart, end: command.length });+ return {+ firstCommand: commandWithoutShellComments(command, command.length, comments).trim(),+ remainingCommand: null,+ separator: null,+ };+}++function commandWithoutLeadingShellComments(command: string): string | null {+ let remainingCommand = command.trimStart();+ while (remainingCommand.startsWith("#")) {+ const newlineIndex = remainingCommand.indexOf("\n");+ if (newlineIndex === -1) return null;+ remainingCommand = remainingCommand.slice(newlineIndex + 1).trimStart();+ }+ return remainingCommand || null;+}++function withoutShellLineContinuations(command: string): string {+ let normalizedCommand = "";+ let quote: '"' | "'" | null = null;+ let escaping = false;++ for (let index = 0; index < command.length; index += 1) {+ const character = command[index]!;+ if (escaping) {+ normalizedCommand += character;+ escaping = false;+ continue;+ }+ if (character === "\\" && quote !== "'") {+ if (command[index + 1] === "\n") {+ index += 1;+ continue;+ }+ if (command[index + 1] === "\r" && command[index + 2] === "\n") {+ index += 2;+ continue;+ }+ normalizedCommand += character;+ escaping = true;+ continue;+ }+ if (quote !== null) {+ if (character === quote) quote = null;+ } else if (character === '"' || character === "'") {+ quote = character;+ }+ normalizedCommand += character;+ }++ return normalizedCommand;+}++function indexAfterShellRedirection(tokens: ReadonlyArray<string>, index: number): number | null {+ const token = tokens[index];+ if (!token || /^[<>]\(/u.test(token)) return null;+ const match = token.match(+ /^(?:(?:(?:\d+|\*|\{[A-Za-z_][A-Za-z0-9_]*\})?(?:<<<|<<-|<<|<>|>>|>\||<&|>&|<|>))|&>>|&>)(.*)$/u,+ );+ if (!match) return null;+ if (match[1]) return index + 1;+ return tokens[index + 1] === undefined ? tokens.length + 1 : index + 2;+}++function serializeShellTokens(tokens: ReadonlyArray<string>): string {+ return tokens.map((token) => `'${token.replaceAll("'", "'\\''")}'`).join(" ");+}++function transparentWrapperCommandIndex(+ wrapper: string,+ tokens: ReadonlyArray<string>,+ index: number,+): number | null {+ if (wrapper === "bundle") {+ return tokens[index + 1] === "exec" && tokens[index + 2] !== undefined ? index + 2 : null;+ }++ if (wrapper === "nohup") {+ let targetIndex = index + 1;+ if (tokens[targetIndex] === "--") targetIndex += 1;+ const target = tokens[targetIndex];+ return target && !target.startsWith("-") ? targetIndex : null;+ }++ if (wrapper === "script") {+ // BSD `script` takes an output file before the optional command. Requiring+ // an option and both operands avoids guessing about a plain `script file`.+ return /^-[adkpqr]+$/u.test(tokens[index + 1] ?? "") && tokens[index + 3] !== undefined+ ? index + 3+ : null;+ }++ if (wrapper === "arch") {+ if (/^-(?:arm64|arm64e|i386|x86_64)$/u.test(tokens[index + 1] ?? "")) {+ return tokens[index + 2] !== undefined ? index + 2 : null;+ }+ return tokens[index + 1] === "-arch" && tokens[index + 3] !== undefined ? index + 3 : null;+ }++ if (wrapper === "timeout" || wrapper === "gtimeout") {+ return /^(?:\d+(?:\.\d*)?|\.\d+)[smhd]?$/u.test(tokens[index + 1] ?? "") &&+ tokens[index + 2] !== undefined+ ? index + 2+ : null;+ }++ return null;+}++function staticProgramName(value: string): string | null {+ const trimmedValue = value.trim();+ if (!trimmedValue || /^[A-Za-z][A-Za-z0-9+.-]*:(?![\\/])/u.test(trimmedValue)) return null;+ const program = trimmedValue.split(/[\\/]/u).at(-1);+ if (+ !program ||+ (/\s/u.test(program) && !/[\\/]/u.test(trimmedValue)) ||+ NON_PROGRAM_PREFIX_CHARACTERS.includes(program[0] ?? "") ||+ NON_PROGRAM_SUFFIX_CHARACTERS.includes(program.at(-1) ?? "")+ ) {+ return null;+ }+ return program;+}++function leadingPowerShellLiteral(command: string): string | null {+ const input = command.trimStart();+ const quote = input[0];+ if (quote !== '"' && quote !== "'") return staticProgramName(input.match(/^\S+/u)?.[0] ?? "");++ let value = "";+ for (let index = 1; index < input.length; index += 1) {+ const character = input[index]!;+ if (character === "`" && input[index + 1] !== undefined) {+ value += input[index + 1];+ index += 1;+ continue;+ }+ if (character === quote) {+ if (quote === "'" && input[index + 1] === "'") {+ value += "'";+ index += 1;+ continue;+ }+ return staticProgramName(value);+ }+ value += character;+ }+ return null;+}++function powerShellCallOperatorProgramName(command: string): string | null | undefined {+ const match = command.match(/^\s*&\s+([\s\S]*)$/u);+ return match ? leadingPowerShellLiteral(match[1]!) : undefined;+}++type PowerShellAssignment = {+ readonly matched: boolean;+ readonly program: string | null;+};++function powerShellAssignmentProgramName(+ command: string,+ depth: number,+ remainingCommand: string | null,+ segmentsRemaining: number,+): PowerShellAssignment {+ const assignment = command.match(+ /^\s*\$(?:(env|global|local|script):)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*([\s\S]*)$/iu,+ );+ if (!assignment) return { matched: false, program: null };++ // Environment assignments are setup. Their right-hand side is a value, not+ // a command, so prefer the next top-level segment when one exists.+ if (assignment[1]?.toLowerCase() === "env") {+ return {+ matched: true,+ program: remainingCommand+ ? commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1)+ : null,+ };+ }++ const value = assignment[2]!.trim();+ // The POSIX-oriented segment splitter does not balance PowerShell arrays or+ // hashtables. Do not mistake a key after an internal semicolon for a command.+ if (/^(?:\[ordered\]\s*)?@\s*[{(]/iu.test(value)) {+ return { matched: true, program: null };+ }+ const calledProgram = powerShellCallOperatorProgramName(value);+ if (calledProgram !== undefined) return { matched: true, program: calledProgram };++ const directCommand = value.match(/^(?:@?\(\s*)?([A-Za-z][A-Za-z0-9_.-]*)\b/u)?.[1];+ if (directCommand && !NON_DESCRIPTIVE_SHELL_PROGRAMS.has(directCommand.toLowerCase())) {+ const parsedCommand = commandProgramNameInternal(value, depth + 1, "shell", segmentsRemaining);+ return { matched: true, program: parsedCommand ?? directCommand };+ }++ return {+ matched: true,+ program: remainingCommand+ ? commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1)+ : null,+ };+}++type WindowsShellPayload = {+ readonly matched: boolean;+ readonly program: string | null;+};++function windowsShellPayloadProgramName(+ shell: string,+ tokens: ReadonlyArray<string>,+ start: number,+ depth: number,+ remainingCommand: string | null,+ separator: string | null,+ segmentsRemaining: number,+): WindowsShellPayload {+ const parsePayload = (payload: string | undefined): string | null => {+ if (!payload) return null;+ const command =+ remainingCommand && separator ? `${payload} ${separator} ${remainingCommand}` : payload;+ return commandProgramNameInternal(command, depth + 1, "shell", segmentsRemaining);+ };++ if (shell === "cmd" || shell === "cmd.exe") {+ for (let index = start; index < tokens.length; index += 1) {+ const option = tokens[index]!.toLowerCase();+ if (option !== "/c" && option !== "/k") continue;+ const payload = tokens[index + 1];+ return {+ matched: true,+ program: parsePayload(payload),+ };+ }+ return { matched: false, program: null };+ }++ for (let index = start; index < tokens.length; index += 1) {+ const option = tokens[index]!.toLowerCase();+ if (option === "-command" || option === "-c") {+ const payload = tokens[index + 1];+ return {+ matched: true,+ program: parsePayload(payload),+ };+ }+ if (option === "-file" || option === "-f") {+ return { matched: true, program: staticProgramName(tokens[index + 1] ?? "") };+ }+ if (option === "-encodedcommand" || option === "-enc" || option === "-e") {+ return { matched: true, program: null };+ }+ if (POWERSHELL_OPTIONS_WITH_VALUE.has(option)) {+ index += 1;+ continue;+ }+ if (POWERSHELL_FLAGS.has(option)) continue;+ if (!option.startsWith("-")) {+ return { matched: true, program: staticProgramName(tokens[index]!) };+ }+ }+ return { matched: false, program: null };+}++function startProcessProgramName(tokens: ReadonlyArray<string>, start: number): string | null {+ for (let index = start; index < tokens.length; index += 1) {+ const token = tokens[index]!;+ const option = token.toLowerCase();+ if (option === "-filepath") return staticProgramName(tokens[index + 1] ?? "");+ if (START_PROCESS_FLAGS.has(option)) continue;+ if (START_PROCESS_OPTIONS_WITH_VALUE.has(option)) {+ if (tokens[index + 1] === undefined) return null;+ index += 1;+ continue;+ }+ if (token.startsWith("-")) return null;+ return staticProgramName(token);+ }+ return null;+}++function literalAssignmentProgram(+ token: string,+): { readonly name: string; readonly program: string | null } | null {+ const assignment = token.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/su);+ if (!assignment) return null;+ const name = assignment[1]!;+ let value = assignment[2]!.trim();+ if (!value || /[$`]/u.test(value)) return { name, program: null };++ if (value.startsWith("(") && value.endsWith(")")) {+ const arrayTokens = tokenizeShellCommand(value.slice(1, -1));+ value = arrayTokens?.[0] ?? "";+ } else if (/\s/u.test(value) && !/[\\/]/u.test(value)) {+ return { name, program: null };+ }++ return { name, program: staticProgramName(value) };+}++function referencedCommandAlias(token: string): string | null {+ const reference = token.match(+ /^\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)(?:\[@\])?\})$/u,+ );+ return reference?.[1] ?? reference?.[2] ?? null;+}++// Recover only literal aliases declared by an earlier top-level shell segment.+// This covers common `SSH=(ssh ...)` and `TOOL=/path/to/tool` forms without+// evaluating expansions or trying to model general shell state.+function literalCommandAliasProgramName(command: string): string | null {+ const aliases = new Map<string, string>();+ let remainingCommand: string | null = command;+ let controlFlowDepth = 0;++ for (let segmentCount = 0; remainingCommand && segmentCount < 64; segmentCount += 1) {+ const commandWithoutComments = commandWithoutLeadingShellComments(remainingCommand);+ if (commandWithoutComments === null) return null;+ const commandSplit = splitFirstShellCommand(commandWithoutComments);+ const tokens = tokenizeShellCommand(withoutShellLineContinuations(commandSplit.firstCommand));+ if (tokens === null) return null;++ let commandIndex = tokens[0] === "do" || tokens[0] === "then" ? 1 : 0;+ while (commandIndex < tokens.length) {+ const indexAfterRedirection = indexAfterShellRedirection(tokens, commandIndex);+ if (indexAfterRedirection !== null && indexAfterRedirection <= tokens.length) {+ commandIndex = indexAfterRedirection;+ continue;+ }+ if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(tokens[commandIndex] ?? "")) {+ commandIndex += 1;+ continue;+ }+ break;+ }++ const aliasName = referencedCommandAlias(tokens[commandIndex] ?? "");+ const aliasedProgram = aliasName ? aliases.get(aliasName) : undefined;+ if (aliasedProgram) return aliasedProgram;++ const leadingToken = tokens[0];+ if (leadingToken === "fi" || leadingToken === "done" || leadingToken === "esac") {+ controlFlowDepth = Math.max(0, controlFlowDepth - 1);+ }+ if (+ leadingToken === "if" ||+ leadingToken === "for" ||+ leadingToken === "while" ||+ leadingToken === "until" ||+ leadingToken === "select" ||+ leadingToken === "case"+ ) {+ controlFlowDepth += 1;+ }++ if (controlFlowDepth === 0 && leadingToken === "unset") {+ for (const name of tokens.slice(1)) aliases.delete(name);+ }++ const assignmentStart = tokens[0] === "export" ? 1 : 0;+ const assignments = tokens.slice(assignmentStart).map(literalAssignmentProgram);+ if (+ controlFlowDepth === 0 &&+ assignments.length > 0 &&+ assignments.every((assignment) => assignment !== null)+ ) {+ for (const assignment of assignments) {+ if (assignment.program) aliases.set(assignment.name, assignment.program);+ else aliases.delete(assignment.name);+ }+ }++ remainingCommand = commandSplit.remainingCommand;+ }++ return null;+}++function wrappedShellCommandProgramName(+ wrapper: string,+ tokens: ReadonlyArray<string>,+ start: number,+ depth: number,+ remainingCommand: string | null,+ segmentsRemaining: number,+): string | null {+ let index = start;++ if (wrapper === "command") {+ while (index < tokens.length) {+ const option = tokens[index]!;+ if (option === "--") {+ index += 1;+ break;+ }+ if (!option.startsWith("-") || option === "-") break;+ if (option !== "-p") return null;+ index += 1;+ }+ } else if (wrapper === "builtin") {+ if (tokens[index] === "--") index += 1;+ else if (tokens[index]?.startsWith("-")) return null;+ } else if (wrapper === "exec") {+ while (index < tokens.length) {+ const option = tokens[index]!;+ if (option === "--") {+ index += 1;+ break;+ }+ if (option === "-a") {+ if (tokens[index + 1] === undefined) return null;+ index += 2;+ continue;+ }+ if (/^-a.+/u.test(option) || /^-[cl]+$/u.test(option)) {+ index += 1;+ continue;+ }+ if (option.startsWith("-") && option !== "-") return null;+ break;+ }+ }++ const wrappedTokens = tokens.slice(index);+ if (wrappedTokens.length === 0) return null;+ let targetIndex = 0;+ while (targetIndex < wrappedTokens.length) {+ const indexAfterRedirection = indexAfterShellRedirection(wrappedTokens, targetIndex);+ if (indexAfterRedirection === null || indexAfterRedirection > wrappedTokens.length) break;+ targetIndex = indexAfterRedirection;+ }+ const target = wrappedTokens[targetIndex];+ if (target && /^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(target)) return null;++ const wrappedProgram = commandProgramNameInternal(+ serializeShellTokens(wrappedTokens),+ depth + 1,+ wrapper === "exec" ? "exec" : "shell",+ segmentsRemaining,+ );+ if (wrappedProgram !== null) return wrappedProgram;++ if (+ wrapper !== "exec" &&+ target &&+ target === target.toLowerCase() &&+ NON_DESCRIPTIVE_SHELL_PROGRAMS.has(target) &&+ !TERMINAL_SHELL_PROGRAMS.has(target) &&+ remainingCommand+ ) {+ return commandProgramNameInternal(remainingCommand, depth, "shell", segmentsRemaining - 1);+ }+ return null;+}++function parseCommandProgramName(+ command: string,+ depth: number,+ context: CommandProgramContext,+ segmentsRemaining: number,+): string | null {+ if (depth >= 8 || segmentsRemaining <= 0) return null;+ const commandWithoutComments = commandWithoutLeadingShellComments(command);+ if (commandWithoutComments === null) return null;+ if (+ /^(?:catch|finally|for|foreach|function|if|param|switch|try|while)\s*[{(]/iu.test(+ commandWithoutComments,+ )+ ) {+ return null;+ }+ if (/^[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/u.test(commandWithoutComments)) return null;+ // `&&` and `||` inside a `[[ ... ]]` expression are not top-level command+ // separators. Keep the label conservative instead of scanning the test body.+ if (commandWithoutComments.startsWith("[[")) return null;+ const commandSplit = splitFirstShellCommand(commandWithoutComments);+ if (/^@["'](?:\r?\n)/u.test(commandSplit.firstCommand.trimStart())) {+ return commandSplit.remainingCommand+ ? commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ "shell",+ segmentsRemaining - 1,+ )+ : null;+ }+ const powerShellAssignment = powerShellAssignmentProgramName(+ commandSplit.firstCommand,+ depth,+ commandSplit.remainingCommand,+ segmentsRemaining,+ );+ if (powerShellAssignment.matched) return powerShellAssignment.program;+ const windowsPath = commandSplit.firstCommand.match(+ /^\s*((?:\.{1,2}|%[A-Za-z_][A-Za-z0-9_]*%|\$env:[A-Za-z_][A-Za-z0-9_]*)\\\S+)/iu,+ )?.[1];+ if (windowsPath) return staticProgramName(windowsPath);+ const tokens = tokenizeShellCommand(withoutShellLineContinuations(commandSplit.firstCommand));if (tokens === null) return null;+ const firstCharacter = commandSplit.firstCommand.trimStart()[0];+ if (+ tokens.length === 1 &&+ (firstCharacter === '"' || firstCharacter === "'") &&+ /[\s()=]/u.test(tokens[0] ?? "") &&+ !/[\\/]/u.test(tokens[0] ?? "")+ ) {+ return commandSplit.remainingCommand+ ? commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ context,+ segmentsRemaining - 1,+ )+ : null;+ }let index = 0;let wrapper: CommandWrapper | null = null;+ let executionContext = context;+ let sawAssignment = false;+ let sawRedirection = false;while (index < tokens.length) {const token = tokens[index];if (!token) return null;- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) {+ const indexAfterRedirection = indexAfterShellRedirection(tokens, index);+ if (indexAfterRedirection !== null) {+ if (indexAfterRedirection > tokens.length) return null;+ sawRedirection = true;+ index = indexAfterRedirection;+ continue;+ }+ if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(token)) {+ sawAssignment = true;index += 1;continue;}+ if (executionContext === "shell" && token === ":") {+ return commandSplit.remainingCommand+ ? commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ executionContext,+ segmentsRemaining - 1,+ )+ : null;+ }+ if (+ NON_PROGRAM_PREFIX_CHARACTERS.includes(token[0] ?? "") &&+ !(token.startsWith("$") && token.includes("/"))+ ) {+ return executionContext === "shell" && token.startsWith("[") && commandSplit.remainingCommand+ ? commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ executionContext,+ segmentsRemaining - 1,+ )+ : null;+ }const tokenProgram = token.split(/[\\/]/).at(-1);+ const isUnqualifiedToken = token === tokenProgram;if (tokenProgram === "env" || tokenProgram === "sudo") {wrapper = tokenProgram;+ executionContext = "exec";index += 1;continue;}@@ -140,10 +1190,17 @@ export function commandProgramName(command: string, depth = 0): string | null {if (wrapper !== null && token.startsWith("-")) {if (wrapper === "env" && (token === "-S" || token === "--split-string")) {const splitCommand = tokens[index + 1];- return splitCommand ? commandProgramName(splitCommand, depth + 1) : null;+ return splitCommand+ ? commandProgramNameInternal(splitCommand, depth + 1, executionContext, segmentsRemaining)+ : null;}if (wrapper === "env" && token.startsWith("--split-string=")) {- return commandProgramName(token.slice("--split-string=".length), depth + 1);+ return commandProgramNameInternal(+ token.slice("--split-string=".length),+ depth + 1,+ executionContext,+ segmentsRemaining,+ );}if (COMMAND_WRAPPER_OPTIONS_WITH_VALUE[wrapper].has(token)) {if (tokens[index + 1] === undefined) return null;@@ -182,11 +1239,131 @@ export function commandProgramName(command: string, depth = 0): string | null {const scriptIndex = shellCommandArgumentIndex(tokens, index + 1);if (scriptIndex !== null) {const script = tokens[scriptIndex];- return script ? commandProgramName(script, depth + 1) : null;+ return script+ ? commandProgramNameInternal(script, depth + 1, "shell", segmentsRemaining)+ : null;+ }+ }+ const lowerTokenProgram = tokenProgram?.toLowerCase();+ if (lowerTokenProgram && WINDOWS_SHELL_PROGRAMS.has(lowerTokenProgram)) {+ const payload = windowsShellPayloadProgramName(+ lowerTokenProgram,+ tokens,+ index + 1,+ depth,+ commandSplit.remainingCommand,+ commandSplit.separator,+ segmentsRemaining,+ );+ if (payload.matched) return payload.program;+ }+ if (lowerTokenProgram === "start-process") {+ const startedProgram = startProcessProgramName(tokens, index + 1);+ if (startedProgram !== null) return startedProgram;+ }+ if (+ executionContext === "shell" &&+ isUnqualifiedToken &&+ tokenProgram &&+ SHELL_PRECOMMAND_MODIFIERS.has(tokenProgram)+ ) {+ index += 1;+ if (tokenProgram === "time" && tokens[index] === "-p") index += 1;+ if (tokens[index]?.startsWith("-")) return null;+ continue;+ }+ if (isUnqualifiedToken && tokenProgram) {+ const targetIndex = transparentWrapperCommandIndex(tokenProgram, tokens, index);+ if (targetIndex !== null) {+ const wrappedProgram = commandProgramNameInternal(+ serializeShellTokens(tokens.slice(targetIndex)),+ depth + 1,+ "exec",+ segmentsRemaining,+ );+ if (wrappedProgram !== null) return wrappedProgram;}}+ if (isUnqualifiedToken && tokenProgram && SHELL_COMMAND_WRAPPERS.has(tokenProgram)) {+ return wrappedShellCommandProgramName(+ tokenProgram,+ tokens,+ index + 1,+ depth,+ commandSplit.remainingCommand,+ segmentsRemaining,+ );+ }+ if (+ (executionContext === "shell" ||+ (wrapper === "sudo" && tokenProgram && SKIPPABLE_SUDO_PROBES.has(tokenProgram))) &&+ isUnqualifiedToken &&+ tokenProgram &&+ NON_DESCRIPTIVE_SHELL_PROGRAMS.has(tokenProgram) &&+ (!TERMINAL_SHELL_PROGRAMS.has(tokenProgram) ||+ (tokenProgram === "false" && commandSplit.separator !== "&&")) &&+ commandSplit.remainingCommand+ ) {+ return commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ "shell",+ segmentsRemaining - 1,+ );+ }+ if (+ executionContext === "shell" &&+ isUnqualifiedToken &&+ lowerTokenProgram &&+ POWERSHELL_SETUP_PROGRAMS.has(lowerTokenProgram) &&+ commandSplit.remainingCommand+ ) {+ return commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ "shell",+ segmentsRemaining - 1,+ );+ }+ if (+ !tokenProgram ||+ (isUnqualifiedToken && NON_DESCRIPTIVE_SHELL_PROGRAMS.has(tokenProgram)) ||+ NON_PROGRAM_PREFIX_CHARACTERS.includes(tokenProgram[0] ?? "") ||+ NON_PROGRAM_SUFFIX_CHARACTERS.includes(tokenProgram.at(-1) ?? "") ||+ tokenProgram.endsWith("()") ||+ /^[A-Za-z_][A-Za-z0-9_]*\(\)\{$/u.test(tokenProgram)+ ) {+ return null;+ }return tokenProgram || null;}+ if ((sawAssignment || sawRedirection) && wrapper === null && commandSplit.remainingCommand) {+ return commandProgramNameInternal(+ commandSplit.remainingCommand,+ depth,+ executionContext,+ segmentsRemaining - 1,+ );+ }return null;}++function commandProgramNameInternal(+ command: string,+ depth: number,+ context: CommandProgramContext,+ segmentsRemaining = MAX_COMMAND_SEGMENTS,+): string | null {+ if (segmentsRemaining <= 0) return null;+ const calledProgram = powerShellCallOperatorProgramName(command);+ if (calledProgram !== undefined) return calledProgram;+ return (+ parseCommandProgramName(command, depth, context, segmentsRemaining) ??+ (context === "shell" ? literalCommandAliasProgramName(command) : null)+ );+}++export function commandProgramName(command: string, depth = 0): string | null {+ return commandProgramNameInternal(command, depth, "shell", MAX_COMMAND_SEGMENTS);+}