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
address review (codex): .cmd/.bat targets still need cmd.exe, not just an extension
[._.]/ Adam Eivy0f81909cdb46
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d11fb48411..98bf985764 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,6 @@## AI Providers-- **[issue-1865] CLI provider runs now work on Windows** — npm-installed CLI providers (OpenCode, Codex, Claude Code) ship as `.cmd`/`.bat` shims on Windows; a bare command name like `opencode` never resolves there because Node's batch-file safe-execution path only triggers on an explicit `.cmd`/`.bat` suffix in the spawned path, not a libuv-internal PATHEXT search. The Test-provider button surfaced this as "Resolved 'opencode' to ... but it could not be executed" — and that diagnostic was itself hitting a second bug: `where`'s first PATH match can be the extension-less POSIX shell-script stub npm ships alongside the real Windows wrapper (for Git Bash/WSL), which is never launchable natively. A new `resolveWindowsExecutable` (`server/lib/bufferedSpawn.js`) resolves a bare command to its actual `.exe`/`.cmd`/`.bat` path via a deliberately extension-aware filesystem search (skipping that stub), so the runner's spawn call, the vendored toolkit's built-in fallback, the autofixer/calendar-sync CLI runner, and the vision-captioning CLI runner can target it directly under `shell:false` — letting Node's own already-tested, already-safely-escaping `.bat`/`.cmd` handling (the CVE-2024-27980 fix) take over, rather than hand-rolling cmd.exe argument escaping (`shell:true` with an args array does **not** escape arguments — it just space-joins them per the literal DEP0190 warning, so any prompt or path containing a space would have silently corrupted or been shell-injectable). `testProvider()`'s version probe now re-resolves the same way before invoking, fixing the Test button's literal reported scenario. Because a `.cmd`/`.bat` target still routes through an intermediate `cmd.exe` process, a plain `SIGTERM` only kills that wrapper and orphans the real CLI process; every kill path for these processes (timeout, fallback-signal abort, Stop Run) now uses a `taskkill /T /F`-based process-tree kill on Windows (`killProcessTree`, extended to also mark `.killed` synchronously) and a plain `SIGTERM` elsewhere, unchanged. (#1865)+- **[issue-1865] CLI provider runs now work on Windows** — npm-installed CLI providers (OpenCode, Codex, Claude Code) ship as `.cmd`/`.bat` shims on Windows; a bare command name like `opencode` never resolves there because `spawn()`'s default `shell:false` doesn't apply Windows' PATHEXT search at all. The Test-provider button surfaced this as "Resolved 'opencode' to ... but it could not be executed" — and that diagnostic was itself hitting a second bug: `where`'s first PATH match can be the extension-less POSIX shell-script stub npm ships alongside the real Windows wrapper (for Git Bash/WSL), which is never launchable natively. A new `resolveWindowsExecutable` (`server/lib/bufferedSpawn.js`) resolves a bare command to its actual `.exe`/`.cmd`/`.bat` path via a deliberately extension-aware filesystem search (skipping that stub). Critically, a resolved `.cmd`/`.bat` target still cannot be launched directly under `shell:false` even with the explicit extension — Node's CVE-2024-27980 patch makes `spawn()`/`execFile()` refuse batch files outright rather than safely auto-wrapping them — so a new `prepareWindowsSafeSpawn` wraps a batch target through Node's own documented-safe pattern, `cmd.exe /c <path> <args>` (a native `.exe` target is launched directly, unwrapped). Because `cmd.exe` is itself a normal native executable, Node's existing, already-tested non-shell argv escaping governs the result — correctly preserving spaces in each argument (including a multi-word vision-captioning prompt) — with none of `shell:true`'s DEP0190 hazard (`shell:true` with an args array does **not** escape arguments, it just space-joins them, so it was rejected as the fix here). This applies to the runner's spawn call, the vendored toolkit's built-in fallback, the autofixer/calendar-sync CLI runner, the vision-captioning CLI runner, and `testProvider()`'s version probe (fixing the Test button's literal reported scenario). Because a `.cmd`/`.bat` target routes through an intermediate `cmd.exe` process, a plain `SIGTERM` only kills that wrapper and orphans the real CLI process; every kill path for these processes (timeout, fallback-signal abort, Stop Run) now uses a `taskkill /T /F`-based process-tree kill on Windows (`killProcessTree`, extended to mark `.killed` synchronously and to skip non-`ChildProcess` killables like a node-pty TUI session, which has its own native teardown) and a plain `SIGTERM` elsewhere, unchanged. (#1865)- **[claude-default-sonnet-5] Default Claude CLI/TUI providers now use `claude-sonnet-5` for the medium tier.** The seeded `claude-code`, `claude-code-tui`, and both `*-bedrock` providers ship the new sonnet tier (`claude-sonnet-5`, Bedrock `us.anthropic.claude-sonnet-5`) in place of `claude-sonnet-4-6`, and the Anthropic model-refresh dropdown lists it first. Migration 153 bumps existing installs' sonnet tier from `claude-sonnet-4-6` → `claude-sonnet-5` — rewriting the models list and swapping any tier pointer still on `claude-sonnet-4-6`, while leaving customized model lists and still-current pins (opus-4-8, haiku-4-5) untouched. The `claude-sonnet-5` context window (1M) is registered in both the server (`stageRunner.js`) and client (`utils/providers.js`) model maps. (`data.reference/providers.json`, `server/lib/aiToolkit/defaults/providers.sample.json`, `server/routes/scaffoldPortOS.js`)## Brain & CoS APIdiff --git a/server/lib/aiToolkit/providers.cliPathResolve.test.js b/server/lib/aiToolkit/providers.cliPathResolve.test.jsindex f16623a535..7f31998d26 100644--- a/server/lib/aiToolkit/providers.cliPathResolve.test.js+++ b/server/lib/aiToolkit/providers.cliPathResolve.test.js@@ -116,11 +116,12 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>expect(result.success).toBe(true);expect(result.path).toBe(join(fakePathDir, 'opencode.cmd'));const versionCall = vi.mocked(execFile).mock.calls.find((c) => c[0] !== 'where' && c[0] !== 'which');- expect(versionCall?.[0]).toBe(join(fakePathDir, 'opencode.cmd'));- // No options object (and so no shell) — the call is (path, args, callback)- // with nothing in between. The re-resolved path carries the explicit- // extension, so Node's own safely-escaping .bat/.cmd handling applies- // under shell:false.+ // The re-resolved .cmd target can't be launched directly under+ // shell:false even with the explicit extension (Node refuses it+ // outright post-CVE-2024-27980) — it's wrapped through cmd.exe /c,+ // Node's documented safe pattern (no shell:true, no DEP0190 hazard).+ expect(versionCall?.[0]).toBe('cmd.exe');+ expect(versionCall?.[1]).toEqual(['/c', join(fakePathDir, 'opencode.cmd'), '--version']);expect(versionCall?.length).toBe(3);expect(typeof versionCall?.[2]).toBe('function');});diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex c17dd9d476..6819002c5b 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -46,6 +46,24 @@ function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32return null;}+const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;++/**+ * Return the `{ command, args }` pair that's actually safe to hand to+ * `execFile()` under `shell:false` — mirrors `prepareWindowsSafeSpawn` in+ * `server/lib/bufferedSpawn.js` (duplicated here for self-containment).+ * `.bat`/`.cmd` files cannot be launched directly under `shell:false` even+ * with the explicit extension (Node's CVE-2024-27980 patch makes+ * spawn/execFile refuse them outright); the documented safe alternative is+ * to invoke `cmd.exe /c <path> <args>` directly.+ */+function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {+ if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {+ return { command: 'cmd.exe', args: ['/c', command, ...args] };+ }+ return { command, args };+}+const execFileAsync = promisify(execFile);// Tool-use (function-calling) capable model families. Inlined here because the@@ -507,11 +525,13 @@ export function createProviderService(config = {}) {const tryVersion = async (flag) => {// Invoke the resolved path so Windows runs the exact `.exe`/`.cmd`// we found — execFile won't re-apply PATHEXT to a bare command- // name, and (now that `invokePath` carries the correct explicit- // extension) no shell is needed: Node's own already-safely-escaping- // internal `.bat`/`.cmd` handling takes over under shell:false.+ // name. A `.cmd`/`.bat` target still can't be launched directly+ // under shell:false (Node refuses it outright, even with the+ // explicit extension — see prepareWindowsSafeSpawn above), so wrap+ // it through cmd.exe /c exactly like the runner does.try {- const out = await execFileAsync(invokePath, [flag]);+ const { command: execCommand, args: execArgs } = prepareWindowsSafeSpawn(invokePath, [flag]);+ const out = await execFileAsync(execCommand, execArgs);everSpawned = true;return out?.stdout?.trim() || null;} catch (err) {diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 8978b1961b..91ec881401 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -21,11 +21,11 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];/*** Resolve a bare command name to its full path WITH extension on Windows, so- * spawn() can target it directly under shell:false — the actual fix for- * #1865 (a bare command never resolves on Windows even though typing it at a- * real cmd.exe prompt works fine; see server/lib/bufferedSpawn.js's- * `resolveWindowsExecutable` docstring for the full root-cause explanation,- * mirrored here for self-containment). Filesystem-only (no subprocess).+ * the caller knows exactly which file (and which kind — `.exe` vs+ * `.cmd`/`.bat`) it's about to launch. Filesystem-only (no subprocess). See+ * server/lib/bufferedSpawn.js's `resolveWindowsExecutable` docstring for the+ * full root-cause explanation, mirrored here for self-containment. Pair with+ * `prepareWindowsSafeSpawn` below to get a launchable `{ command, args }`.*/function resolveWindowsExecutable(command, isWin32 = IS_WIN32) {if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;@@ -39,6 +39,27 @@ function resolveWindowsExecutable(command, isWin32 = IS_WIN32) {return null;}+const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;++/**+ * Return the `{ command, args }` pair that's actually safe to hand to+ * `spawn()` under `shell:false` — THE ACTUAL FIX FOR #1865. `.bat`/`.cmd`+ * files cannot be launched directly under `shell:false` even with the+ * explicit extension (Node's CVE-2024-27980 patch makes `spawn()` refuse+ * them outright, full stop — it does NOT safely auto-wrap them). Node's+ * documented safe alternative is to spawn `cmd.exe /c <path> <args>`+ * directly: `cmd.exe` is a normal `.exe`, so Node's existing, already-tested+ * non-shell argv→command-line escaping governs the result, with none of+ * `shell:true`'s DEP0190 unescaped-join hazard. Mirrors+ * server/lib/bufferedSpawn.js's `prepareWindowsSafeSpawn` for self-containment.+ */+function prepareWindowsSafeSpawn(command, args, isWin32 = IS_WIN32) {+ if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {+ return { command: 'cmd.exe', args: ['/c', command, ...args] };+ }+ return { command, args };+}+// On Windows, taskkill (used below) runs in a separate detached process that// never touches the original ChildProcess object — `.killed` is set// synchronously here (mirroring what Node's own `child.kill()` does on the@@ -346,13 +367,14 @@ export function createRunnerService(config = {}) {// user-configurable `provider.command` cannot inject extra commands via// shell metacharacters, and so the full prompt isn't visible in// process listings as a single command-line argument. On Windows,- // resolve to the explicit .cmd/.bat path instead of enabling a shell —- // see resolveWindowsExecutable above for why shell:true is unsafe here.+ // resolve+wrap a .cmd/.bat target instead of enabling a shell — see+ // prepareWindowsSafeSpawn above for why shell:true is unsafe here.const args = [...(provider.args || [])];console.log(`🚀 Executing CLI: ${provider.command} ${args.join(' ')} (${prompt.length} chars via stdin)`);const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;- const childProcess = spawn(resolvedCommand, args, {+ const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);+ const childProcess = spawn(spawnCommand, spawnArgs, {cwd: workspacePath,env: { ...process.env, ...provider.envVars },windowsHide: truediff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex 3fb7061d73..0681a9bfec 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -43,25 +43,17 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];/*** Resolve a bare command name (e.g. "opencode") to its full path WITH- * extension on Windows, so `spawn()` can target it directly under the- * default `shell: false`.- *- * This is the actual fix for #1865 (CLI providers like opencode/codex/claude- * failing to spawn on Windows) — NOT a missing `shell: true`. A bare command- * with no extension never resolves on Windows even though typing it at a- * real cmd.exe prompt works fine: libuv's internal PATHEXT search finds e.g.- * "opencode.cmd", but Node's JS-layer `.bat`/`.cmd` safe-auto-escape- * detection (the CVE-2024-27980 fix) only fires on a LITERAL `.bat`/`.cmd`- * suffix in the string passed to `spawn()` — it never sees what libuv found.- * Resolving to the explicit extension up front lets that already-tested,- * already-safely-escaping Node code path take over automatically, instead of- * hand-rolling cmd.exe argument quoting ourselves (the exact class of bug the- * CVE was about — `shell: true` + an args array does NOT escape arguments,- * it just space-joins them, so any arg containing a space or a cmd.exe- * metacharacter would silently corrupt or be shell-injectable).+ * extension on Windows, so the caller knows exactly which file (and which+ * kind — `.exe` vs `.cmd`/`.bat`) it's about to launch.+ *+ * A bare command with no extension never resolves on Windows even though+ * typing it at a real cmd.exe prompt works fine: libuv's internal PATHEXT+ * search finds e.g. "opencode.cmd", but `spawn()`'s default `shell: false`+ * doesn't apply that search at all (it targets the literal string given).** Deliberately filesystem-only (no `where`/`which` subprocess) so resolution- * is synchronous and side-effect-free.+ * is synchronous and side-effect-free. Pair with `prepareWindowsSafeSpawn`+ * below to get a `{ command, args }` pair that's actually launchable.** @param {string} command - bare command name, or an existing path (returned unchanged)* @param {boolean} [isWin32] - injectable for tests; defaults to the real platform@@ -80,6 +72,42 @@ export function resolveWindowsExecutable(command, isWin32 = IS_WIN32) {return null;}+const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;++/**+ * Return the `{ command, args }` pair that's actually safe to hand to+ * `spawn()`/`execFile()` under the default `shell: false`, given a (possibly+ * `resolveWindowsExecutable`-resolved) command.+ *+ * THE ACTUAL FIX FOR #1865. An earlier version of this fix assumed Node's+ * CVE-2024-27980 patch safely auto-escapes a `.bat`/`.cmd` target under+ * `shell: false` once it carries the explicit extension — that's wrong. The+ * shipped patch instead makes `spawn()`/`spawnSync()` **refuse** (an+ * `'error'`/EINVAL-class failure) any `.bat`/`.cmd` target under+ * `shell: false`, full stop; per Node's own docs, `.bat`/`.cmd` files+ * "are not executable on their own... and cannot be launched" that way.+ * Node's documented safe alternative is to spawn `cmd.exe /c <path> <args>`+ * directly: `cmd.exe` is a normal `.exe`, so Node's existing, already-tested+ * non-shell argv→command-line escaping governs the result — correctly+ * preserving spaces/quotes in each arg — with none of `shell: true`'s+ * DEP0190 unescaped-join hazard (a literal `shell: true` + args array does+ * NOT escape arguments, it just space-joins them).+ *+ * A resolved native `.exe`/`.com` target needs no wrapping at all — it's+ * directly launchable, so it's returned unchanged.+ *+ * @param {string} command - bare name, or a resolveWindowsExecutable result+ * @param {string[]} args+ * @param {boolean} [isWin32] - injectable for tests; defaults to the real platform+ * @returns {{ command: string, args: string[] }}+ */+export function prepareWindowsSafeSpawn(command, args, isWin32 = IS_WIN32) {+ if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {+ return { command: 'cmd.exe', args: ['/c', command, ...args] };+ }+ return { command, args };+}+// Cap buffered stdout/stderr so a runaway child can't exhaust memory; we only// ever surface a tail of the output anyway.export const MAX_OUTPUT_BYTES = 64 * 1024;diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 9b8585bd5f..0b301b56b7 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -23,6 +23,7 @@ const {killProcessTree,needsShell,resolveWindowsExecutable,+ prepareWindowsSafeSpawn,IS_WIN32,WIN_CMD_SHIMS,MAX_OUTPUT_BYTES,@@ -167,6 +168,35 @@ describe('resolveWindowsExecutable', () => {});});+describe('prepareWindowsSafeSpawn', () => {+ // isWin32 is passed explicitly so these tests are deterministic regardless+ // of the host platform actually running them.+ it('wraps a .cmd target in cmd.exe /c on Windows (the actual #1865 fix)', () => {+ const result = prepareWindowsSafeSpawn('C:\\npm\\opencode.cmd', ['exec', '-'], true);+ expect(result).toEqual({ command: 'cmd.exe', args: ['/c', 'C:\\npm\\opencode.cmd', 'exec', '-'] });+ });++ it('wraps a .bat target in cmd.exe /c on Windows, case-insensitively', () => {+ const result = prepareWindowsSafeSpawn('C:\\tools\\thing.BAT', ['x'], true);+ expect(result).toEqual({ command: 'cmd.exe', args: ['/c', 'C:\\tools\\thing.BAT', 'x'] });+ });++ it('leaves a resolved .exe target unwrapped on Windows — directly launchable, no batch interpreter needed', () => {+ const result = prepareWindowsSafeSpawn('C:\\tools\\claude.exe', ['-p', '-'], true);+ expect(result).toEqual({ command: 'C:\\tools\\claude.exe', args: ['-p', '-'] });+ });++ it('never wraps off Windows, even for a .cmd-looking path', () => {+ const result = prepareWindowsSafeSpawn('/usr/local/bin/opencode.cmd', ['exec', '-'], false);+ expect(result).toEqual({ command: '/usr/local/bin/opencode.cmd', args: ['exec', '-'] });+ });++ it('passes through a bare unresolved command unchanged (resolution-failure fallback)', () => {+ const result = prepareWindowsSafeSpawn('opencode', ['exec', '-'], true);+ expect(result).toEqual({ command: 'opencode', args: ['exec', '-'] });+ });+});+describe('bufferedSpawn — structured result', () => {it('resolves success on a clean (code 0) exit and captures stdout/stderr', async () => {const child = makeFakeChild();diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex 7dcbfaeafa..80799883e6 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -18,7 +18,7 @@import { spawn } from 'child_process';import { buildCliArgs } from './cliProviderArgs.js';-import { killProcessTree, resolveWindowsExecutable } from './bufferedSpawn.js';+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';/*** Resolve which CLI provider + model a feature should use from the providers@@ -97,13 +97,15 @@ export function runCliProviderPrompt(args = {}) {// CLAUDECODE is deleted from the child env so a nested invocation doesn't// think it's running inside the parent Claude Code session.- // npm-installed CLI providers are .cmd/.bat shims on Windows; resolve to- // the explicit-extension path instead of enabling a shell — shell:true +- // an args array does NOT escape arguments (DEP0190), so a prompt/path- // containing a space would silently corrupt or be shell-injectable. See- // resolveWindowsExecutable in server/lib/bufferedSpawn.js.+ // npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap+ // (cmd.exe /c) instead of enabling a shell — shell:true + an args array+ // does NOT escape arguments (DEP0190), so a prompt/path containing a+ // space would silently corrupt or be shell-injectable. See+ // resolveWindowsExecutable/prepareWindowsSafeSpawn in+ // server/lib/bufferedSpawn.js.const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;- const child = spawn(resolvedCommand, spawnArgs, {+ const { command: spawnCommand, args: wrappedArgs } = prepareWindowsSafeSpawn(resolvedCommand, spawnArgs);+ const child = spawn(spawnCommand, wrappedArgs, {cwd: cwd || process.cwd(),stdio: ['pipe', 'pipe', 'pipe'],env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),diff --git a/server/services/runner.js b/server/services/runner.jsindex 703d825e85..9f9af921cc 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -10,7 +10,7 @@ import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';import { buildCliArgs } from '../lib/cliProviderArgs.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';-import { killProcessTree, resolveWindowsExecutable } from '../lib/bufferedSpawn.js';+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';import {setAIToolkitInstance,getAIToolkitInstance,@@ -161,17 +161,18 @@ export async function patchRunMetadata(runId, patch) {/*** Override executeCliRun.*- * Runs without a shell (`shell:false`, the default — never set `shell:true`- * here): npm-installed CLI providers (opencode, codex, claude, …) are- * .cmd/.bat shims on Windows, but the fix for that (#1865) is resolving the- * bare command to its explicit-extension path via `resolveWindowsExecutable`- * before spawning, NOT enabling a shell. `shell:true` + an args array does- * NOT escape arguments — it just space-joins them (the literal DEP0190- * warning) — so any arg or prompt content containing a space or a cmd.exe- * metacharacter would silently corrupt or be shell-injectable. Resolving the- * `.cmd`/`.bat` extension up front instead lets Node's own already-tested,- * already-safely-escaping internal batch-file handling (the CVE-2024-27980- * fix) take over automatically under `shell:false`.+ * Runs without `shell:true` (never set it here): npm-installed CLI providers+ * (opencode, codex, claude, …) are .cmd/.bat shims on Windows, but+ * `shell:true` + an args array does NOT escape arguments — it just+ * space-joins them (the literal DEP0190 warning) — so any arg or prompt+ * content containing a space or a cmd.exe metacharacter would silently+ * corrupt or be shell-injectable. The fix for #1865 instead resolves the+ * bare command to its explicit-extension path (`resolveWindowsExecutable`)+ * and, when that's a `.cmd`/`.bat` shim, spawns it via Node's own documented+ * safe pattern — `cmd.exe /c <path> <args>` — instead of targeting it+ * directly (`prepareWindowsSafeSpawn`; see its docstring for why a direct+ * `.cmd`/`.bat` spawn under `shell:false` fails outright post-CVE-2024-27980,+ * and why the `cmd.exe` wrapper avoids DEP0190's unescaped-join hazard).*/export async function executeCliRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout }) {const toolkit = requireToolkit();@@ -201,13 +202,12 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onconst args = buildCliArgs(provider);console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via stdin)`);- // See the executeCliRun docblock above — resolve to the explicit-extension- // path on Windows (e.g. opencode.cmd) instead of enabling a shell, so a- // bare command name actually launches there without reopening the- // unescaped-argument injection surface DEP0190 warns about.+ // See the executeCliRun docblock above for why this is a resolve+wrap, not+ // a shell:true.const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;+ const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);- childProcess = spawn(resolvedCommand, args, {+ childProcess = spawn(spawnCommand, spawnArgs, {cwd: workspacePath,// Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted// agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex be5277e64c..09ecc3312c 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -7,12 +7,18 @@ vi.mock('child_process', async (importOriginal) => {});// Keep the real killProcessTree (existing tests below rely on its real-// non-Windows SIGTERM branch) but stub resolveWindowsExecutable so the-// Windows command-resolution path can be driven deterministically regardless-// of the host platform actually running the suite.+// non-Windows SIGTERM branch) but stub resolveWindowsExecutable AND+// prepareWindowsSafeSpawn so the Windows command-resolution/wrap path can be+// driven deterministically regardless of the host platform actually running+// the suite (prepareWindowsSafeSpawn's own win32 check is bound to the real+// platform by default, which is never win32 in CI).vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, resolveWindowsExecutable: vi.fn(() => null) };+ return {+ ...actual,+ resolveWindowsExecutable: vi.fn(() => null),+ prepareWindowsSafeSpawn: vi.fn((command, args) => ({ command, args })),+ };});vi.mock('../lib/fileUtils.js', () => ({@@ -189,14 +195,20 @@ describe('executeCliRun — Codex sentinel suppression', () => {});describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {- it('spawns the resolveWindowsExecutable-resolved path (e.g. opencode.cmd) when one is found', async () => {- const { resolveWindowsExecutable } = await import('../lib/bufferedSpawn.js');- vi.mocked(resolveWindowsExecutable).mockReturnValueOnce('C:\\Users\\Joe\\AppData\\Roaming\\npm\\opencode.cmd');+ it('wraps a resolved .cmd shim via cmd.exe /c — the actual #1865 fix (never shell:true)', async () => {+ const { resolveWindowsExecutable, prepareWindowsSafeSpawn } = await import('../lib/bufferedSpawn.js');+ const resolvedPath = 'C:\\Users\\Joe\\AppData\\Roaming\\npm\\opencode.cmd';+ vi.mocked(resolveWindowsExecutable).mockReturnValueOnce(resolvedPath);+ // Exercise the REAL wrap logic (not the describe-level identity stub) so+ // this test pins the actual cmd.exe /c contract, with isWin32 forced true+ // since the host running this suite is never win32.+ const { prepareWindowsSafeSpawn: realPrepare } = await vi.importActual('../lib/bufferedSpawn.js');+ vi.mocked(prepareWindowsSafeSpawn).mockImplementationOnce((cmd, args) => realPrepare(cmd, args, true));const child = makeChild();spawn.mockReturnValue(child);- const provider = { id: 'opencode', command: 'opencode', args: [], timeout: 5000 };+ const provider = { id: 'codex', command: 'codex', args: ['exec', '-'], timeout: 5000 };setImmediate(() => {child.stdout.emit('data', Buffer.from('output'));@@ -205,10 +217,15 @@ describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {await executeCliRun({ runId: 'run-resolved', provider, prompt: 'test prompt', workspacePath: '/workspace' });- const [command, , options] = spawn.mock.calls.at(-1);- expect(command).toBe('C:\\Users\\Joe\\AppData\\Roaming\\npm\\opencode.cmd');- // Never set shell:true — resolving the explicit extension lets Node's own- // safely-escaping .bat/.cmd handling take over under shell:false instead.+ const [command, args, options] = spawn.mock.calls.at(-1);+ expect(command).toBe('cmd.exe');+ // buildCliArgs injects/transforms provider.args per-provider convention —+ // assert the WRAPPING contract (/c + resolved path prepended), not the+ // exact downstream arg list.+ expect(args[0]).toBe('/c');+ expect(args[1]).toBe(resolvedPath);+ // Never set shell:true — DEP0190's unescaped-join hazard. The cmd.exe+ // wrapper relies on Node's own correct non-shell argv escaping instead.expect(options.shell).toBeFalsy();});diff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 84c67699a3..896b38c1a2 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -30,7 +30,7 @@ import { join } from 'path';import { buildCliArgs } from '../lib/cliProviderArgs.js';import { resolveCliModel } from '../lib/providerModels.js';import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';-import { killProcessTree, resolveWindowsExecutable } from '../lib/bufferedSpawn.js';+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';const CLI_VISION_TIMEOUT_MS = 120000;const IMAGE_BASENAME = 'vision-input.png';@@ -115,18 +115,22 @@ export async function describeImageViaCli({await writeFile(join(dir, IMAGE_BASENAME), bytes);const { command, args, stdin, cwd } = buildCliVisionInvocation(provider, visionModel, dir, prompt);- // npm-installed CLI providers are .cmd/.bat shims on Windows; resolve to- // the explicit-extension path instead of enabling a shell. This matters- // even more here than at other call sites: the codex branch of- // buildCliVisionInvocation puts the free-text `prompt` directly into- // `args` (see above), and shell:true + an args array does NOT escape- // arguments (DEP0190) — any prompt containing a space would silently- // mis-split into extra shell tokens, corrupting or shell-injecting the- // invocation. See resolveWindowsExecutable in server/lib/bufferedSpawn.js.+ // npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap+ // (cmd.exe /c) instead of enabling a shell. This matters even more here+ // than at other call sites: the codex branch of buildCliVisionInvocation+ // puts the free-text `prompt` directly into `args` (see above), and+ // shell:true + an args array does NOT escape arguments (DEP0190) — any+ // prompt containing a space would silently mis-split into extra shell+ // tokens, corrupting or shell-injecting the invocation. The cmd.exe+ // wrapper instead relies on Node's own correct non-shell argv escaping,+ // which DOES preserve spaces within each arg as a single token. See+ // resolveWindowsExecutable/prepareWindowsSafeSpawn in+ // server/lib/bufferedSpawn.js.const resolvedCommand = resolveWindowsExecutable(command) || command;+ const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);const text = await new Promise((resolve, reject) => {- const child = spawnImpl(resolvedCommand, args, {+ const child = spawnImpl(spawnCommand, spawnArgs, {cwd,env: (() => { const e = { ...process.env, ...provider?.envVars }; delete e.CLAUDECODE; return e; })(),windowsHide: true,diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.jsindex 62168f8914..6d0c6ff0d4 100644--- a/server/services/visionCli.test.js+++ b/server/services/visionCli.test.js@@ -1,13 +1,18 @@import { describe, it, expect, vi } from 'vitest';import { EventEmitter } from 'events';-// Wrap the REAL resolveWindowsExecutable in a spy (not a stub) so every-// existing test below is unaffected (a no-op pass-through on the non-win32-// host running this suite) while one test can force a specific resolved-// path to prove describeImageViaCli actually spawns it.+// Wrap the REAL resolveWindowsExecutable/prepareWindowsSafeSpawn in spies+// (not stubs) so every existing test below is unaffected (both are no-op+// pass-throughs on the non-win32 host running this suite) while one test+// can force a specific resolved path, or force isWin32 on the wrap, to+// prove describeImageViaCli actually spawns the result.vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, resolveWindowsExecutable: vi.fn(actual.resolveWindowsExecutable) };+ return {+ ...actual,+ resolveWindowsExecutable: vi.fn(actual.resolveWindowsExecutable),+ prepareWindowsSafeSpawn: vi.fn(actual.prepareWindowsSafeSpawn),+ };});const {@@ -15,7 +20,7 @@ const {buildCliVisionInvocation,describeImageViaCli,} = await import('./visionCli.js');-const { resolveWindowsExecutable } = await import('../lib/bufferedSpawn.js');+const { resolveWindowsExecutable, prepareWindowsSafeSpawn } = await import('../lib/bufferedSpawn.js');const PNG_DATA_URL = `data:image/png;base64,${Buffer.from('fake-png').toString('base64')}`;@@ -115,8 +120,14 @@ describe('describeImageViaCli', () => {expect(spawnImpl).toHaveBeenCalledOnce();});- it('spawns the resolveWindowsExecutable-resolved path when one is found (#1865)', async () => {- vi.mocked(resolveWindowsExecutable).mockReturnValueOnce('C:\\Users\\Joe\\AppData\\Roaming\\npm\\codex.cmd');+ it('wraps a resolved .cmd shim via cmd.exe /c, preserving the multi-word prompt as one arg (#1865)', async () => {+ const resolvedPath = 'C:\\Users\\Joe\\AppData\\Roaming\\npm\\codex.cmd';+ vi.mocked(resolveWindowsExecutable).mockReturnValueOnce(resolvedPath);+ // Force the wrap's win32 branch (host running this suite is never win32)+ // to exercise the real cmd.exe /c contract, not the identity pass-through.+ const { prepareWindowsSafeSpawn: realPrepare } = await vi.importActual('../lib/bufferedSpawn.js');+ vi.mocked(prepareWindowsSafeSpawn).mockImplementationOnce((cmd, args) => realPrepare(cmd, args, true));+const child = makeFakeChild();const spawnImpl = spawnEmitting(child, (c) => {c.stdout.emit('data', Buffer.from('caption'));@@ -125,14 +136,22 @@ describe('describeImageViaCli', () => {const promise = describeImageViaCli({provider: { id: 'codex', command: 'codex', args: [] },dataUrl: PNG_DATA_URL,- prompt: 'caption this',+ // Free-text prompt with spaces — the exact scenario that broke under+ // the prior (rejected) shell:true approach: shell:true + an args array+ // doesn't escape arguments, so this would have silently mis-split into+ // extra shell tokens. The cmd.exe wrapper relies on Node's own correct+ // non-shell argv escaping instead, which keeps it as one token.+ prompt: 'describe this photo in detail',spawnImpl,});await promise;- const [spawnedCommand, , options] = spawnImpl.mock.calls[0];- expect(spawnedCommand).toBe('C:\\Users\\Joe\\AppData\\Roaming\\npm\\codex.cmd');- // Never falls back to shell:true — the resolved path carries the explicit- // extension, so no shell option is needed (see resolveWindowsExecutable).+ const [spawnedCommand, spawnedArgs, options] = spawnImpl.mock.calls[0];+ expect(spawnedCommand).toBe('cmd.exe');+ expect(spawnedArgs[0]).toBe('/c');+ expect(spawnedArgs[1]).toBe(resolvedPath);+ expect(spawnedArgs[spawnedArgs.length - 1]).toBe('describe this photo in detail');+ // Never falls back to shell:true (DEP0190) — the cmd.exe wrapper relies+ // on Node's own correct non-shell argv escaping instead.expect(options.shell).toBeUndefined();});