Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep agent prompts away from cmd.exe on Windows .cmd shims (#12346)
[._.]/ Adam Eivy36d34a2f6685
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 56dc4c8ea3..69a30d854d 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -279,6 +279,8 @@ export const WINDOWS_RISK_RULES = [/^scripts\/fix-windows-console(?:\.test)?\.js$/,/^scripts\/ps1-bom\.test\.js$/,/^server\/lib\/(?:bufferedSpawn|detachedSpawn|childProcess|bashResolver|processEnv|platform|spawnCwd|cliProviderRun|grok)\b/,+ // The cmd.exe wrap and npm-shim bypass every Windows CLI launch goes through.+ /^server\/lib\/aiToolkit\/internal\/windowsSafeSpawn\.js$/,// Path SEMANTICS differ per platform in ways pinPlatform() cannot fake: NTFS// and APFS are case-insensitive while ext4 is not, and git reports paths its// own way (drive-letter case, 8.3 short names like C:\Users\RUNNER~1). Adiff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex 8df9d4a954..894d4ea135 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -1558,6 +1558,7 @@ describe('Windows escalation on a full plan (#7440)', () => {'scripts/fix-windows-console.js','scripts/ps1-bom.test.js','server/lib/bufferedSpawn.js',+ 'server/lib/aiToolkit/internal/windowsSafeSpawn.js','server/lib/pathSafety.js','server/lib/mockPathsDataRoot.js','server/services/cosAgentIndex.completionOrder.test.js',diff --git a/server/lib/aiToolkit/internal/windowsSafeSpawn.js b/server/lib/aiToolkit/internal/windowsSafeSpawn.jsindex 43ffd8a328..d766106d49 100644--- a/server/lib/aiToolkit/internal/windowsSafeSpawn.js+++ b/server/lib/aiToolkit/internal/windowsSafeSpawn.js@@ -5,8 +5,8 @@* This toolkit leaf stays self-contained so host callers can depend inward* without requiring toolkit code to import PortOS modules.*/-import { existsSync } from 'fs';-import { join, isAbsolute, delimiter } from 'path';+import { existsSync, readFileSync } from 'fs';+import { join, dirname, isAbsolute, delimiter } from 'path';// Prefer native executables to batch shims; ignore npm's POSIX extensionless stubs.const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];@@ -33,27 +33,75 @@ export function resolveWindowsExecutable(command, isWin32 = process.platform ===const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;const CMD_METACHAR_RE = /[&|<>^()]/g;const NEEDS_NODE_QUOTING_RE = /[\s"]/;+// cmd.exe cannot carry these as data: Node escapes an embedded `"` as `\"`,+// which cmd.exe does not honor, so the quote ends the quoted span and the rest+// is parsed as commands; `%VAR%` expands even inside quotes; CR/LF end the+// command line. Prompts routinely contain all of them (#12346).+const CMD_UNCARRYABLE_RE = /["%\r\n]/;+// The script/binary an npm cmd-shim forwards `%*` to, in both the current+// (`"%dp0%\…" %*`) and legacy (`"%~dp0\…" %*`) cmd-shim layouts.+const CMD_SHIM_TARGET_RE = /"%~?dp0%?\\([^"]+)"\s+%\*/g;+const CMD_SHIM_NODE_RE = /%~?dp0%?\\node\.exe"/i;-function escapeCmdMetacharsIfUnquoted(value) {+function escapeCmdMetachars(value, carets) {const str = String(value);if (NEEDS_NODE_QUOTING_RE.test(str)) return str;- return str.replace(CMD_METACHAR_RE, '^$&');+ return str.replace(CMD_METACHAR_RE, `${carets}$&`);+}++/**+ * The direct launch an npm-style cmd-shim performs — `[node.exe, script]` for+ * a node shim, `[target.exe]` for a native one — or `null` when the file is+ * unreadable or not a shim this recognizes. Mirrors the shim's own interpreter+ * choice: a `node.exe` beside it, else `node` on PATH, else this process's node.+ */+function resolveCmdShimLaunch(shimPath) {+ let source;+ try { source = readFileSync(shimPath, 'utf8'); } catch { return null; }+ const targets = [...source.matchAll(CMD_SHIM_TARGET_RE)].map((m) => m[1]);+ const target = targets.at(-1);+ if (!target) return null;+ const shimDir = dirname(shimPath);+ const targetPath = join(shimDir, ...target.split('\\'));+ if (!existsSync(targetPath)) return null;+ if (CMD_SHIM_NODE_RE.test(source)) {+ const localNode = join(shimDir, 'node.exe');+ const pathNode = resolveWindowsExecutable('node', true);+ const nodeExe = existsSync(localNode) ? localNode+ : (pathNode && /\.exe$/i.test(pathNode) ? pathNode : process.execPath);+ return { command: nodeExe, args: [targetPath] };+ }+ return /\.exe$/i.test(targetPath) ? { command: targetPath, args: [] } : null;}/*** A `.cmd`/`.bat` target must run through `cmd.exe /c`, or `spawn` under* `shell: false` cannot execute it at all. Every other command/argv pair* passes through unchanged. No shell:true workaround is needed: spawning- * cmd.exe directly lets Node quote whitespace/quotes in each argument.- * Caret escaping protects metacharacters only in values Node leaves unquoted;- * escaping already-quoted values would introduce literal carets.+ * cmd.exe directly lets Node quote whitespace in each argument, and+ * metacharacters inside those quotes stay literal.+ *+ * Unquoted argument metacharacters are caret-escaped TWICE: cmd.exe /c+ * consumes one level, then the batch file re-parses the expanded `%*`. The+ * command path is not re-parsed and gets one level. An argument cmd.exe+ * cannot carry at all (CMD_UNCARRYABLE_RE — agent prompts on argv) bypasses+ * cmd.exe by launching the shim's target directly; when the shim is not one+ * that can be resolved, the launch is refused rather than handing untrusted+ * text to cmd.exe's parser.*/export function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {- if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {- return {- command: 'cmd.exe',- args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],- };+ if (!isWin32 || !WIN_BATCH_EXT_RE.test(command)) return { command, args };+ if (args.some((arg) => CMD_UNCARRYABLE_RE.test(String(arg)))) {+ const direct = resolveCmdShimLaunch(command);+ if (!direct) {+ const error = new Error(`Cannot pass this argument safely through cmd.exe to ${command}: it contains a double quote, percent sign, or line break, and the batch file is not an npm shim that can be launched directly. Install the CLI with npm or as a native .exe.`);+ error.code = 'WINDOWS_BATCH_ARG_UNSAFE';+ throw error;+ }+ return { command: direct.command, args: [...direct.args, ...args] };}- return { command, args };+ return {+ command: 'cmd.exe',+ args: ['/c', escapeCmdMetachars(command, '^'), ...args.map((arg) => escapeCmdMetachars(arg, '^^^'))],+ };}diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 083494ed67..352619d4cc 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -2083,7 +2083,7 @@ describe('AI Toolkit runner — built-in executeCliRun spawn (#1865)', () => {child.emit('close', 0);await completed;expect(command).toBe('cmd.exe');- expect(args).toEqual(['/c', shim.replace('&', '^&'), 'plain^&value', 'quoted & value']);+ expect(args).toEqual(['/c', shim.replace('&', '^&'), 'plain^^^&value', 'quoted & value']);expect(options.shell).toBeFalsy();expect(options.env.PATH).toBe(shimDir);} finally {diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex e74bca06b8..749500b300 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';import { spawn as nodeSpawn } from 'node:child_process';import { ChildProcess } from './childProcess.js';-import { mkdtemp, rm, writeFile } from 'fs/promises';+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';@@ -399,12 +399,13 @@ describe('prepareWindowsSafeSpawn', () => {expect(result).toEqual({ command: 'opencode', args: ['exec', '-'] });});- it('caret-escapes a cmd.exe metacharacter in an arg with NO whitespace (Node would leave it unquoted)', () => {+ it('double-caret-escapes a cmd.exe metacharacter in an arg with NO whitespace (Node would leave it unquoted)', () => {// foo&calc has no whitespace, so Node's own argv quoting would NOT wrap- // it in literal quotes — the bare `&` would reach cmd.exe's raw command- // line and be interpreted as a command separator without this.+ // it in literal quotes. cmd.exe /c consumes one caret level and the batch+ // file's `%*` re-parse consumes the second; a single caret let the `&`+ // run as a command separator inside the shim (#12346).const result = prepareWindowsSafeSpawn('C:\\npm\\opencode.cmd', ['foo&calc'], true);- expect(result.args).toEqual(['/c', 'C:\\npm\\opencode.cmd', 'foo^&calc']);+ expect(result.args).toEqual(['/c', 'C:\\npm\\opencode.cmd', 'foo^^^&calc']);});it('does NOT escape metacharacters in an arg that already contains whitespace (Node will quote it)', () => {@@ -417,7 +418,7 @@ describe('prepareWindowsSafeSpawn', () => {it('escapes multiple metacharacters in an unquoted arg', () => {const result = prepareWindowsSafeSpawn('C:\\npm\\tool.cmd', ['a|b>c<d'], true);- expect(result.args).toEqual(['/c', 'C:\\npm\\tool.cmd', 'a^|b^>c^<d']);+ expect(result.args).toEqual(['/c', 'C:\\npm\\tool.cmd', 'a^^^|b^^^>c^^^<d']);});it('never escapes off Windows, even for an unquoted metacharacter arg', () => {@@ -433,6 +434,84 @@ describe('prepareWindowsSafeSpawn', () => {});});+// The body npm's cmd-shim writes for a node bin, and the legacy layout older+// npm and pnpm still emit. Both forward `%*` to the script.+const NPM_CMD_SHIM = [+ '@ECHO off',+ 'GOTO start',+ ':find_dp0',+ 'SET dp0=%~dp0',+ 'EXIT /b',+ ':start',+ 'SETLOCAL',+ 'CALL :find_dp0',+ 'IF EXIST "%dp0%\\node.exe" (',+ ' SET "_prog=%dp0%\\node.exe"',+ ') ELSE (',+ ' SET "_prog=node"',+ ' SET PATHEXT=%PATHEXT:;.JS;=;%',+ ')',+ 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\fake-cli\\bin\\cli.js" %*',+ '',+].join('\r\n');+const LEGACY_CMD_SHIM = [+ '@IF EXIST "%~dp0\\node.exe" (',+ ' "%~dp0\\node.exe" "%~dp0\\node_modules\\fake-cli\\bin\\cli.js" %*',+ ') ELSE (',+ ' node "%~dp0\\node_modules\\fake-cli\\bin\\cli.js" %*',+ ')',+ '',+].join('\r\n');+const HOSTILE_PROMPT = 'Summarize this " & calc & " and %PATH%\nthen stop';++describe('prepareWindowsSafeSpawn — argv cmd.exe cannot carry (#12346)', () => {+ let shimDir;+ let script;++ beforeEach(async () => {+ shimDir = await mkdtemp(join(tmpdir(), 'cmd-shim-'));+ script = join(shimDir, 'node_modules', 'fake-cli', 'bin', 'cli.js');+ await mkdir(join(shimDir, 'node_modules', 'fake-cli', 'bin'), { recursive: true });+ await writeFile(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)));\n');+ });++ afterEach(async () => {+ await rm(shimDir, { recursive: true, force: true });+ });++ it.each([+ ['current', NPM_CMD_SHIM],+ ['legacy', LEGACY_CMD_SHIM],+ ])('launches the %s npm shim target directly instead of handing a quoted prompt to cmd.exe', async (_layout, body) => {+ const shim = join(shimDir, 'fake-cli.cmd');+ await writeFile(shim, body);+ await writeFile(join(shimDir, 'node.exe'), '');+ const result = prepareWindowsSafeSpawn(shim, ['--print', HOSTILE_PROMPT], true);+ expect(result).toEqual({ command: join(shimDir, 'node.exe'), args: [script, '--print', HOSTILE_PROMPT] });+ });++ it('refuses a batch file it cannot bypass rather than passing the prompt to cmd.exe', async () => {+ const shim = join(shimDir, 'custom.bat');+ await writeFile(shim, '@echo off\r\necho %*\r\n');+ expect(() => prepareWindowsSafeSpawn(shim, ['--prompt', HOSTILE_PROMPT], true))+ .toThrow(expect.objectContaining({ code: 'WINDOWS_BATCH_ARG_UNSAFE' }));+ });++ it.runIf(process.platform === 'win32')('delivers hostile arguments verbatim through a real npm shim', async () => {+ const shim = join(shimDir, 'fake-cli.cmd');+ await writeFile(shim, NPM_CMD_SHIM);+ const payloads = [HOSTILE_PROMPT, 'a&echo.INJECTED', 'with space & (parens) | pipe', 'c^d'];+ for (const payload of payloads) {+ const { command, args } = prepareWindowsSafeSpawn(shim, ['--print', payload]);+ const child = nodeSpawn(command, args, { windowsHide: true });+ let stdout = '';+ child.stdout.on('data', (chunk) => { stdout += chunk; });+ await new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve); });+ expect(JSON.parse(stdout)).toEqual(['--print', payload]);+ }+ });+});+describe('prepareCliSpawn (composed resolve+wrap — the CoS spawn fix, #2243)', () => {// isWin32 is passed explicitly so these tests are deterministic regardless of// the host platform actually running them. A real fakePathDir on PATH letsdiff --git a/server/lib/cliPromptWindowsShim.test.js b/server/lib/cliPromptWindowsShim.test.jsnew file mode 100644index 0000000000..5b72a7495b--- /dev/null+++ b/server/lib/cliPromptWindowsShim.test.js@@ -0,0 +1,45 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import { prepareCliPrompt } from './cliProviderArgs.js';+import { prepareCliSpawn } from './bufferedSpawn.js';++// agy, kimi, openchamber and pi take the prompt on argv. Installed through npm+// on Windows they are .cmd shims, and cmd.exe would parse tracker or model+// text inside that prompt as commands (#12346). Composed exactly as the spawn+// sites compose it: vendor prompt delivery, then shim resolution.+const shimFor = (bin) => [+ '@ECHO off',+ 'SETLOCAL',+ 'SET dp0=%~dp0',+ `"%dp0%\\node.exe" "%dp0%\\node_modules\\${bin}\\cli.js" %*`,+ '',+].join('\r\n');+const HOSTILE_PROMPT = 'Fix the issue titled " & calc & " today';++describe('argv-prompt vendors on a Windows npm shim (#12346)', () => {+ let binDir;++ beforeEach(async () => {+ binDir = await mkdtemp(join(tmpdir(), 'win-prompt-shim-'));+ await writeFile(join(binDir, 'node.exe'), '');+ });++ afterEach(async () => {+ await rm(binDir, { recursive: true, force: true });+ });++ it.each(['agy', 'kimi', 'openchamber', 'pi'])('%s never hands the prompt to cmd.exe', async (bin) => {+ const script = join(binDir, 'node_modules', bin, 'cli.js');+ await mkdir(join(binDir, 'node_modules', bin), { recursive: true });+ await writeFile(script, '');+ await writeFile(join(binDir, `${bin}.cmd`), shimFor(bin));++ const { args } = prepareCliPrompt(bin, [], HOSTILE_PROMPT, { cwd: binDir });+ expect(args.some((arg) => arg.includes(HOSTILE_PROMPT))).toBe(true);+ const spawned = prepareCliSpawn(bin, args, { PATH: binDir }, true);++ expect(spawned).toEqual({ command: join(binDir, 'node.exe'), args: [script, ...args] });+ });+});diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 4b7a7da58d..1318379361 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -905,12 +905,22 @@ describe('codex provider — launch refusal settlement', () => {});describe('codex provider — Windows shim lifecycle', () => {- it.each(['bare', 'explicit'])('prepares the %s shim for both probes and image launches without losing arguments', async kind => {- setPlatform('win32');+ // An npm cmd-shim, so a launch whose argv cmd.exe cannot carry (the image+ // prompt always spans lines) bypasses cmd.exe for the shim's node target.+ const writeCodexShim = async () => {const cliDir = join(TEST_HOME, 'CLI shims');+ const script = join(cliDir, 'node_modules', '@openai', 'codex', 'bin', 'codex.js');+ await mkdir(join(cliDir, 'node_modules', '@openai', 'codex', 'bin'), { recursive: true });+ await writeFile(script, '');+ await writeFile(join(cliDir, 'node.exe'), '');const shim = join(cliDir, 'codex.cmd');- await mkdir(cliDir, { recursive: true });- await writeFile(shim, '@echo off');+ await writeFile(shim, '@ECHO off\r\n"%dp0%\\node.exe" "%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n');+ return { cliDir, shim, script, node: join(cliDir, 'node.exe') };+ };++ it.each(['bare', 'explicit'])('prepares the %s shim for both probes and image launches without losing arguments', async kind => {+ setPlatform('win32');+ const { cliDir, shim, script, node } = await writeCodexShim();vi.stubEnv('PATH', cliDir);const codexPath = kind === 'explicit' ? shim : undefined;@@ -929,11 +939,11 @@ describe('codex provider — Windows shim lifecycle', () => {prompt: 'a fox & tree | sky > clouds', initImagePath: image,});const call = spawnCalls[1];- expect(call.bin).toBe('cmd.exe');+ expect(call.bin).toBe(node);expect(call.options.shell).toBe(false);- expect(call.args.slice(0, 3)).toEqual(['/c', shim, 'exec']);+ expect(call.args.slice(0, 2)).toEqual([script, 'exec']);expect(call.args).toEqual(expect.arrayContaining([- 'model_reasoning_effort=high', '-i', image, '-m', 'gpt-6.1-sol^&example', '--',+ 'model_reasoning_effort=high', '-i', image, '-m', 'gpt-6.1-sol&example', '--',]));expect(call.args.at(-1)).toContain('a fox & tree | sky > clouds');expect(call.args.at(-1)).toMatch(/^\$imagegen /);@@ -945,8 +955,9 @@ describe('codex provider — Windows shim lifecycle', () => {it.each(['win32', 'linux'])('terminates only the selected %s job, then cancel-all terminates the remaining job', async platform => {setPlatform(platform);- const first = await codex.generateImage({ prompt: 'first', codexPath: '/example/codex.cmd' });- const second = await codex.generateImage({ prompt: 'second', codexPath: '/example/codex.cmd' });+ const { shim } = await writeCodexShim();+ const first = await codex.generateImage({ prompt: 'first', codexPath: shim });+ const second = await codex.generateImage({ prompt: 'second', codexPath: shim });const firstChild = spawnCalls[0].child;const secondChild = spawnCalls[1].child;firstChild.pid = 4242;@@ -980,7 +991,8 @@ describe('codex provider — Windows shim lifecycle', () => {it.each(['win32', 'linux'])('uses the same platform termination path for the %s wall-clock limit', async platform => {setPlatform(platform);vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });- const job = await codex.generateImage({ prompt: 'stalled synthetic render', codexPath: '/example/codex.cmd' });+ const { shim } = await writeCodexShim();+ const job = await codex.generateImage({ prompt: 'stalled synthetic render', codexPath: shim });const child = spawnCalls[0].child;child.pid = 4242;await vi.advanceTimersByTimeAsync(20 * 60 * 1000);@@ -990,7 +1002,7 @@ describe('codex provider — Windows shim lifecycle', () => {expect(child.kill).not.toHaveBeenCalled();expect(spawnCalls.filter(call => call.bin === 'taskkill')).toHaveLength(1);} else {- expect(spawnCalls[0].bin).toBe('/example/codex.cmd');+ expect(spawnCalls[0].bin).toBe(shim);expect(child.kill).toHaveBeenCalledWith('SIGTERM');await vi.advanceTimersByTimeAsync(4999);expect(child.kill).toHaveBeenCalledTimes(1);