π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(local-file-shell): keep %VAR% literal inside PowerShell quoted literals (#20098)
Arvin Xu0793b9b1ae03
diff --git a/packages/local-file-shell/src/shell/__tests__/utils.test.ts b/packages/local-file-shell/src/shell/__tests__/utils.test.tsindex 2bc041b5a2d..4231c2efa0b 100644--- a/packages/local-file-shell/src/shell/__tests__/utils.test.ts+++ b/packages/local-file-shell/src/shell/__tests__/utils.test.ts@@ -278,6 +278,165 @@ describe('normalizeEnvVarRefs', () => {const command = 'foreach ($path in Get-ChildItem) { Write-Output $path }';expect(normalizeEnvVarRefs(command, env, 'pwsh')).toBe(command);});++ // Regression: a .cmd batch file written through a single-quoted here-string+ // had its `%PATH%` rewritten to `${env:PATH}`, which PowerShell then wrote+ // to disk verbatim β the batch file lost its PATH.+ it('should leave %VAR% inside a single-quoted here-string verbatim', () => {+ const command = [+ "$dsh = @'",+ '@echo off',+ 'set "DSH_HOME=%USERPROFILE%\\.dsh"',+ 'set "PATH=D:\\DeepSeekHarness\\npm-global;%PATH%"',+ '\'@; [IO.File]::WriteAllText("$env:TEMP\\dsh.cmd", $dsh)',+ 'Write-Output "%USERPROFILE%"',+ ].join('\r\n');++ expect(normalizeEnvVarRefs(command, env, 'pwsh')).toBe(+ [+ "$dsh = @'",+ '@echo off',+ 'set "DSH_HOME=%USERPROFILE%\\.dsh"',+ 'set "PATH=D:\\DeepSeekHarness\\npm-global;%PATH%"',+ '\'@; [IO.File]::WriteAllText("$env:TEMP\\dsh.cmd", $dsh)',+ 'Write-Output "${env:USERPROFILE}"',+ ].join('\r\n'),+ );+ });++ it('should leave %VAR% inside a double-quoted here-string verbatim', () => {+ const command = '$bat = @"\nset "PATH=C:\\tools;%PATH%"\necho $name\n"@\necho %PATH%';++ expect(normalizeEnvVarRefs(command, env, 'powershell')).toBe(+ '$bat = @"\nset "PATH=C:\\tools;%PATH%"\necho $name\n"@\necho ${env:PATH}',+ );+ });++ it('should lex $( ) subexpressions inside a double-quoted here-string as code', () => {+ // The here-string body is literal, but `$( ... )` inside it is executed.+ expect(+ normalizeEnvVarRefs(+ '$s = @"\nset PATH=%PATH%\nvalue: $(Write-Output %PATH%)\n"@\necho %PATH%',+ env,+ 'pwsh',+ ),+ ).toBe('$s = @"\nset PATH=%PATH%\nvalue: $(Write-Output ${env:PATH})\n"@\necho ${env:PATH}');+ // Literals inside the subexpression still stay verbatim.+ expect(normalizeEnvVarRefs(`$s = @"\n$('%PATH%' + "%PATH%") %PATH%\n"@`, env, 'pwsh')).toBe(+ `$s = @"\n$('%PATH%' + "\${env:PATH}") %PATH%\n"@`,+ );+ });++ it("should leave %VAR% inside single-quoted strings verbatim ('' is an escaped quote)", () => {+ expect(normalizeEnvVarRefs("Write-Output '%PATH%'", env, 'pwsh')).toBe(+ "Write-Output '%PATH%'",+ );+ expect(+ normalizeEnvVarRefs("Set-Content a.cmd 'it''s %PATH%'; echo %PATH%", env, 'pwsh'),+ ).toBe("Set-Content a.cmd 'it''s %PATH%'; echo ${env:PATH}");+ });++ it('should lex $( ) subexpressions inside double-quoted strings as code', () => {+ expect(+ normalizeEnvVarRefs(`Write-Output "$('%PATH%') and $(("%PATH%"))" %PATH%`, env, 'pwsh'),+ ).toBe(`Write-Output "$('%PATH%') and $(("\${env:PATH}"))" \${env:PATH}`);+ });++ it('should recognize a comment right after a standalone subtraction operator', () => {+ // `2 -# β¦` is subtraction followed by a comment (verified in pwsh: the+ // expression continues on the next line), while `a-#b` stays a bare word.+ expect(+ normalizeEnvVarRefs("$x = 2 -# don't expand %PATH%\n1\nWrite-Output %PATH%", env, 'pwsh'),+ ).toBe("$x = 2 -# don't expand %PATH%\n1\nWrite-Output ${env:PATH}");+ expect(normalizeEnvVarRefs('Write-Output a-#b %PATH%', env, 'pwsh')).toBe(+ 'Write-Output a-#b ${env:PATH}',+ );+ });++ it.each(['/', '%', '*'])(+ 'should recognize a comment right after a standalone %s operator',+ (op) => {+ expect(+ normalizeEnvVarRefs(+ `$x = 4 ${op}# don't expand %PATH%\n2\nWrite-Output %PATH%`,+ env,+ 'pwsh',+ ),+ ).toBe(`$x = 4 ${op}# don't expand %PATH%\n2\nWrite-Output \${env:PATH}`);+ expect(normalizeEnvVarRefs(`Write-Output a${op}#b %PATH%`, env, 'pwsh')).toBe(+ `Write-Output a${op}#b \${env:PATH}`,+ );+ },+ );++ it.each(['1', '0xFF', '1.5e3', '10kb', '$y', '$env:PATH', '${my var}', '=1'])(+ 'should recognize a comment right after the completed expression token %s',+ (token) => {+ // `$x = 1# β¦` is a number followed by a comment: the apostrophe in the+ // comment must not open a string that swallows the following lines.+ expect(+ normalizeEnvVarRefs(+ `$x = ${token}# don't expand %PATH%\nWrite-Output %PATH%`,+ env,+ 'pwsh',+ ),+ ).toBe(`$x = ${token}# don't expand %PATH%\nWrite-Output \${env:PATH}`);+ },+ );++ it('should keep # inside a bare word that contains digits', () => {+ expect(normalizeEnvVarRefs('tool v1#b a1#b %PATH%', env, 'pwsh')).toBe(+ 'tool v1#b a1#b ${env:PATH}',+ );+ });++ it('should keep # inside a bare argument that already started, even after punctuation', () => {+ // Verified in pwsh: `key=#literal`, `a+#b`, `x:#y` print as one word each.+ expect(normalizeEnvVarRefs('tool key=#literal %PATH%', env, 'pwsh')).toBe(+ 'tool key=#literal ${env:PATH}',+ );+ expect(normalizeEnvVarRefs('tool a+#b x:#y %PATH%', env, 'pwsh')).toBe(+ 'tool a+#b x:#y ${env:PATH}',+ );+ // β¦but a token terminator or a standalone `=` starts a new token.+ expect(normalizeEnvVarRefs("$x =# don't %PATH%\n5\nWrite-Output %PATH%", env, 'pwsh')).toBe(+ "$x =# don't %PATH%\n5\nWrite-Output ${env:PATH}",+ );+ expect(normalizeEnvVarRefs("echo a,# don't %PATH%\nWrite-Output %PATH%", env, 'pwsh')).toBe(+ "echo a,# don't %PATH%\nWrite-Output ${env:PATH}",+ );+ });++ it('should end a block comment at the first #> (PowerShell block comments do not nest)', () => {+ expect(normalizeEnvVarRefs('<# a <# b #> Write-Output %PATH% #>', env, 'pwsh')).toBe(+ '<# a <# b #> Write-Output ${env:PATH} #>',+ );+ });++ it('should recognize a comment right after an operator', () => {+ expect(+ normalizeEnvVarRefs("$x = 1 +# don't expand %PATH%\n2\nWrite-Output %PATH%", env, 'pwsh'),+ ).toBe("$x = 1 +# don't expand %PATH%\n2\nWrite-Output ${env:PATH}");+ // `#` inside a bare word is not a comment.+ expect(normalizeEnvVarRefs('echo a#b %PATH%', env, 'pwsh')).toBe('echo a#b ${env:PATH}');+ });++ it('should still rewrite %VAR% in bare words and ordinary double-quoted strings', () => {+ expect(normalizeEnvVarRefs('cd "%USERPROFILE%\\Desktop"', env, 'pwsh')).toBe(+ 'cd "${env:USERPROFILE}\\Desktop"',+ );+ // An apostrophe inside a double-quoted string or a comment must not open+ // a single-quoted literal that swallows the rest of the command.+ expect(+ normalizeEnvVarRefs(+ 'Write-Output "it\'s here"; # don\'t\ncd %USERPROFILE%; dir "%ProgramFiles(x86)%"',+ env,+ 'pwsh',+ ),+ ).toBe(+ 'Write-Output "it\'s here"; # don\'t\ncd ${env:USERPROFILE}; dir "${env:ProgramFiles(x86)}"',+ );+ });});describe('cmd target (fallback)', () => {diff --git a/packages/local-file-shell/src/shell/utils.ts b/packages/local-file-shell/src/shell/utils.tsindex 213f5d68914..bdeac0665e2 100644--- a/packages/local-file-shell/src/shell/utils.ts+++ b/packages/local-file-shell/src/shell/utils.ts@@ -295,6 +295,194 @@ export const getShellInfo = async (): Promise<ShellInfo> =>? detectWindowsShell(): { displayName: '/bin/sh', path: '/bin/sh', type: 'sh' };+/**+ * Locate the spans of a PowerShell script whose text PowerShell takes+ * literally with respect to cmd-style `%VAR%`: single-quoted strings (`''` is+ * an escaped quote), single- and double-quoted here-strings, and comments.+ * Returns sorted, non-overlapping `[start, end)` ranges.+ *+ * Ordinary double-quoted strings are scanned over (so an apostrophe inside+ * `"it's"` does not open a single-quoted string) but not reported: `%VAR%`+ * inside them is still a reference the author expected to expand. Their+ * `$( ... )` subexpressions are code, so they are lexed like the top level.+ * This is a lexer-grade approximation, not a parser β an unterminated literal+ * extends to the end of the script, which errs on the side of leaving text+ * untouched.+ */+/**+ * A completed PowerShell expression token after which `#` opens a comment+ * (`$x = 1# β¦`, `$x = $y# β¦`), optionally preceded by operator characters+ * (`$x =1# β¦`): a numeric literal (decimal, hex, exponent, type suffix and+ * multiplier like `1.5e3`, `0xFF`, `10kb`) or a variable (`$name`,+ * `$env:NAME`, `${any name}`).+ */+const COMPLETED_EXPRESSION_TOKEN =+ /^[-+*/%=!<>]*(?:(?:0x[\da-f]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?)(?:u?[lsy]|[dnu])?(?:kb|mb|gb|tb|pb)?|\$(?:\{[^}]*\}|[\w?:]+))$/i;++/**+ * Whether a `#` at `index` begins a PowerShell comment, i.e. sits at the start+ * of a token or right after a completed expression token, rather than inside a+ * bare word (see the call site).+ */+const startsPowerShellComment = (script: string, index: number): boolean => {+ let j = index - 1;+ while (j >= 0 && !/[\s;|&(){},]/.test(script[j])) j -= 1;+ const run = script.slice(j + 1, index);+ return run === '' || /^[-+*/%=!<>]+$/.test(run) || COMPLETED_EXPRESSION_TOKEN.test(run);+};++const findPowerShellLiteralRanges = (script: string): Array<[number, number]> => {+ const ranges: Array<[number, number]> = [];+ const length = script.length;++ /** Scan an expandable `"..."` body from `i`; returns the index after the closing quote. */+ const scanExpandableString = (from: number): number => {+ let i = from;+ while (i < length) {+ const char = script[i];+ if (char === '`') {+ i += 2;+ } else if (char === '$' && script[i + 1] === '(') {+ i = scanCode(i + 2, true);+ } else if (char === '"') {+ if (script[i + 1] !== '"') return i + 1;+ i += 2;+ } else {+ i += 1;+ }+ }+ return length;+ };++ /**+ * Scan a `@"..."@` here-string whose body starts at `bodyStart`; returns the+ * index after the closing `"@`. The body text is literal, but its `$( ... )`+ * subexpressions are executed, so they are lexed as code and left out of the+ * literal ranges.+ */+ const scanExpandableHereString = (openerStart: number, bodyStart: number): number => {+ let segmentStart = openerStart;+ let i = bodyStart;+ while (i < length) {+ const char = script[i];+ if (char === '\n' && script[i + 1] === '"' && script[i + 2] === '@') {+ ranges.push([segmentStart, i + 3]);+ return i + 3;+ }+ if (char === '`') {+ i += 2;+ } else if (char === '$' && script[i + 1] === '(') {+ ranges.push([segmentStart, i + 2]);+ i = scanCode(i + 2, true);+ segmentStart = i;+ } else {+ i += 1;+ }+ }+ ranges.push([segmentStart, length]);+ return length;+ };++ /**+ * Scan code from `i`. Inside a subexpression, stops after the `)` that+ * closes it; returns the index where scanning ended.+ */+ function scanCode(from: number, inSubexpression: boolean): number {+ let depth = 0;+ let i = from;++ while (i < length) {+ const char = script[i];++ // Backtick escapes the next character (`` `' `` is a literal apostrophe).+ if (char === '`') {+ i += 2;+ continue;+ }++ // Here-string: `@'` / `@"` must be followed by a line break; it closes+ // at `'@` / `"@` at the start of a line.+ if (char === '@' && (script[i + 1] === "'" || script[i + 1] === '"')) {+ const quote = script[i + 1];+ const opener = /^[\t ]*\r?\n/.exec(script.slice(i + 2));+ if (opener) {+ if (quote === '"') {+ i = scanExpandableHereString(i, i + 2 + opener[0].length);+ continue;+ }+ const close = script.indexOf(`\n${quote}@`, i + 2 + opener[0].length - 1);+ const end = close === -1 ? length : close + 3;+ ranges.push([i, end]);+ i = end;+ continue;+ }+ }++ if (char === "'") {+ let j = i + 1;+ while (j < length) {+ if (script[j] === "'") {+ if (script[j + 1] === "'") {+ j += 2;+ continue;+ }+ break;+ }+ j += 1;+ }+ const end = Math.min(j + 1, length);+ ranges.push([i, end]);+ i = end;+ continue;+ }++ if (char === '"') {+ i = scanExpandableString(i + 1);+ continue;+ }++ // Comments: `<# ... #>` blocks, and `#` to the end of the line unless it+ // sits inside a bare word (`a#b` is one argument). Skipped so an+ // apostrophe in a comment does not swallow the code after it.+ if (char === '<' && script[i + 1] === '#') {+ const close = script.indexOf('#>', i + 2);+ const end = close === -1 ? length : close + 2;+ ranges.push([i, end]);+ i = end;+ continue;+ }+ // `#` opens a comment only where a new token starts: after whitespace or+ // a token terminator (`; | & ( ) { } ,`), or after a run made only of+ // operator characters that is itself a token (`2 -# β¦`, `$x =# β¦`).+ // Once a bare word has started, `#` is part of it (`a-#b`, `key=#v`,+ // `x:#y`). Command-mode arguments like `-#x` are misread as comments,+ // which only leaves the rest of that line unrewritten β the safe side.+ if (char === '#' && startsPowerShellComment(script, i)) {+ const newline = script.indexOf('\n', i);+ const end = newline === -1 ? length : newline;+ ranges.push([i, end]);+ i = end;+ continue;+ }++ if (inSubexpression) {+ if (char === '(') depth += 1;+ if (char === ')') {+ if (depth === 0) return i + 1;+ depth -= 1;+ }+ }++ i += 1;+ }++ return length;+ }++ scanCode(0, false);+ return ranges;+};+/*** Rewrite environment variable references in a command string to the **target* shell's native syntax**, for the syntaxes that shell cannot resolve itself.@@ -307,7 +495,12 @@ export const getShellInfo = async (): Promise<ShellInfo> =>* `$env:VAR`, `$VAR` and `${VAR}` are valid PowerShell syntax that PowerShell* resolves itself β rewriting them here would corrupt legitimate scripts (the* `$env:FOO='bar'` assignment form, or script-local variables like- * `foreach ($path in ...)` colliding with the `PATH` env var).+ * `foreach ($path in ...)` colliding with the `PATH` env var). The rewrite+ * applies to bare words and ordinary `"..."` strings only: single-quoted+ * strings (`'...'`), here-strings (`@'...'@` and `@"..."@`) and comments are+ * left verbatim. PowerShell never expands `%VAR%` there, and those blocks are+ * usually file content β e.g. a `.cmd` batch file written through a+ * here-string, whose `set "PATH=...;%PATH%"` must reach disk unchanged.* - cmd target: PowerShell/bash forms (`$env:VAR`, `${VAR}`, `$VAR`) are* rewritten to `%VAR%`; existing `%VAR%` is already cmd-native.* - Git Bash target: cmd-style `%VAR%` and PowerShell-style `$env:VAR` are@@ -366,9 +559,18 @@ export const normalizeEnvVarRefs = (if (shell === 'pwsh' || shell === 'powershell') {// cmd style: %VAR% β the name may contain parentheses, e.g. %ProgramFiles(x86)%.// `${env:VAR}` expands as a single token even when the value has spaces.- return command.replaceAll(/%([A-Z_][\w()]*)%/gi, (match, name: string) =>- envNames.has(name.toLowerCase()) ? `\${env:${name}}` : match,- );+ const rewrite = (code: string): string =>+ code.replaceAll(/%([A-Z_][\w()]*)%/gi, (match, name: string) =>+ envNames.has(name.toLowerCase()) ? `\${env:${name}}` : match,+ );++ let result = '';+ let cursor = 0;+ for (const [start, end] of findPowerShellLiteralRanges(command)) {+ result += rewrite(command.slice(cursor, start)) + command.slice(start, end);+ cursor = end;+ }+ return result + rewrite(command.slice(cursor));}// cmd.exe target: rewrite to cmd-native %VAR%.