Skip to content

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

address review (claude): resolve win32 .cmd/.bat path instead of enabling shell:true

[._.]/ Adam Eivyb306c73463ea
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c063106779..d11fb48411 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, which Node's `spawn()` can't execute directly without a shell; the Test-provider button surfaced this as "Resolved 'opencode' to ... but it could not be executed". The runner's spawn call (`server/services/runner.js`, mirrored in the vendored toolkit's built-in fallback `server/lib/aiToolkit/runner.js`) now passes `shell: true` on `win32`, and the same `.cmd`/`.bat` probe in `testProvider()`'s version check (`server/lib/aiToolkit/providers.js`) does too, so Test Provider and real runs both succeed. Because Windows wraps the child in a `cmd.exe` process when `shell: true`, a plain `SIGTERM` only killed that wrapper and orphaned the real CLI process; run-kill paths (timeout, fallback-signal abort, Stop Run) now use a `taskkill /T /F`-based process-tree kill on Windows (`killProcessTree`, reusing `server/lib/bufferedSpawn.js`'s existing pattern) 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 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)
- **[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 API
diff --git a/server/lib/aiToolkit/providers.cliPathResolve.test.js b/server/lib/aiToolkit/providers.cliPathResolve.test.js
index aaf105c311..4ad59a82d5 100644
--- a/server/lib/aiToolkit/providers.cliPathResolve.test.js
+++ b/server/lib/aiToolkit/providers.cliPathResolve.test.js
@@ -1,7 +1,8 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { mkdir, rm } from 'fs/promises';
+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
+import { tmpdir } from 'os';
// Mock child_process so testProvider's command-resolution branch runs against a
// controllable `which`/`where` + version probe instead of the host's real PATH.
@@ -22,15 +23,28 @@ const TEST_DATA_DIR = join(process.cwd(), 'test-data-cli-resolve');
describe('testProvider — cli command resolution (cross-platform PATH)', () => {
let providerService;
let originalPlatform;
+ let originalPath;
+ let fakePathDir;
beforeEach(async () => {
originalPlatform = process.platform;
if (!existsSync(TEST_DATA_DIR)) await mkdir(TEST_DATA_DIR, { recursive: true });
providerService = createProviderService({ dataDir: TEST_DATA_DIR, providersFile: 'providers.json' });
+ // testProvider's win32 path now ALSO does its own filesystem-based
+ // re-resolution (resolveWindowsExecutable) independent of the mocked
+ // `where`/`which` lookup below — point PATH at a controlled, normally-empty
+ // temp dir so that re-resolution can't accidentally match something on the
+ // real host running this suite, and so tests can opt in to a match by
+ // writing a file into it.
+ originalPath = process.env.PATH;
+ fakePathDir = await mkdtemp(join(tmpdir(), 'provider-test-path-'));
+ process.env.PATH = fakePathDir;
});
afterEach(async () => {
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ process.env.PATH = originalPath;
+ await rm(fakePathDir, { recursive: true, force: true });
vi.mocked(execFile).mockReset();
if (existsSync(TEST_DATA_DIR)) await rm(TEST_DATA_DIR, { recursive: true });
});
@@ -87,26 +101,41 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>
expect(result.path).toBe('C:\\a\\claude.exe');
});
- it('routes the win32 version probe through a shell (so .cmd/.bat shims can execute)', async () => {
+ it('re-resolves to the real .cmd shim when `where`s first match is an unspawnable extension-less stub (#1865 root cause)', async () => {
setPlatform('win32');
- stubExec({ lookup: 'C:\\Users\\Joe\\AppData\\Roaming\\npm\\claude.cmd\r\n' });
- const p = await makeCliProvider();
+ // npm ships a bare POSIX shell-script stub (for Git Bash/WSL) alongside
+ // the real `.cmd` wrapper — `where` can return the stub first, which is
+ // exactly the literal scenario from the issue's reported error text.
+ await writeFile(join(fakePathDir, 'opencode'), '#!/bin/sh\n');
+ await writeFile(join(fakePathDir, 'opencode.cmd'), '@echo off\n');
+ stubExec({ lookup: `${join(fakePathDir, 'opencode')}\r\n`, version: 'opencode 1.0.0\n' });
+ const p = await makeCliProvider('opencode');
- await providerService.testProvider(p.id);
+ const result = await providerService.testProvider(p.id);
+ 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?.[2]).toEqual({ shell: true });
+ 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.
+ expect(versionCall?.length).toBe(3);
+ expect(typeof versionCall?.[2]).toBe('function');
});
- it('does not enable a shell for the version probe on non-win32 platforms', async () => {
- setPlatform('linux');
- stubExec({ lookup: '/usr/local/bin/claude\n' });
+ it('falls back to the where-resolved path when no extension-bearing match exists on PATH', async () => {
+ setPlatform('win32');
+ // fakePathDir intentionally has no claude.* files — resolveWindowsExecutable
+ // finds nothing, so testProvider must fall back to the `where` result.
+ stubExec({ lookup: 'C:\\Users\\Joe\\.local\\bin\\claude.exe\r\n' });
const p = await makeCliProvider();
- await providerService.testProvider(p.id);
+ const result = await providerService.testProvider(p.id);
- const versionCall = vi.mocked(execFile).mock.calls.find((c) => c[0] !== 'where' && c[0] !== 'which');
- expect(versionCall?.[2]).toEqual({ shell: false });
+ expect(result.success).toBe(true);
+ expect(result.path).toBe('C:\\Users\\Joe\\.local\\bin\\claude.exe');
});
it('invokes the resolved path for the version probe (so win32 runs the exact .exe)', async () => {
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index e0d6e69e7c..c17dd9d476 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -1,6 +1,6 @@
import { readFile, rename } from 'fs/promises';
import { existsSync } from 'fs';
-import { join, dirname } from 'path';
+import { join, dirname, delimiter, isAbsolute } from 'path';
import { atomicWrite } from './internal/atomicWrite.js';
import { fileURLToPath } from 'url';
import { execFile } from 'child_process';
@@ -18,6 +18,34 @@ import {
const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_SAMPLE_PATH = join(__dirname, 'defaults/providers.sample.json');
+// Extensions Windows can launch directly, checked in cmd.exe's own resolution
+// preference. Deliberately excludes an extension-less match — npm ships a
+// POSIX shell-script stub alongside a package's `.cmd`/`.bat`/`.ps1` Windows
+// wrappers (for Git Bash/WSL); that stub is not natively launchable here, and
+// is exactly what `where` can return as its first match (see #1865 — the
+// issue's literal error text was produced by this function resolving that
+// stub as `commandPath`, not by a missing shell).
+const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
+
+/**
+ * Resolve a bare command name to its full path WITH extension on Windows —
+ * mirrors `resolveWindowsExecutable` in `server/lib/bufferedSpawn.js`
+ * (duplicated here for this directory's self-containment; see ./CLAUDE.md).
+ * Filesystem-only (no subprocess), so it can't reorder/misselect the way a
+ * raw `where` first-line read can.
+ */
+function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32') {
+ if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
+ const pathDirs = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ for (const dir of pathDirs) {
+ for (const ext of WIN_EXECUTABLE_EXTS) {
+ const candidate = join(dir, `${command}${ext}`);
+ if (existsSync(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
const execFileAsync = promisify(execFile);
// Tool-use (function-calling) capable model families. Inlined here because the
@@ -460,21 +488,30 @@ export function createProviderService(config = {}) {
return { success: false, error: `Command '${provider.command}' not found in PATH` };
}
- // Track whether the resolved path could actually be spawned. A bare PATH
- // lookup (`where`) on Windows happily returns npm `.cmd`/`.bat` shims.
- // Without this, a non-spawnable shim falls through to `version:
- // 'available'` and the Test button reports a provider the runner can
- // never actually invoke as usable.
+ // On Windows, `where` can return the wrong file: npm ships an
+ // extension-less POSIX shell-script stub (for Git Bash/WSL) alongside
+ // the real `.cmd`/`.bat`/`.ps1` wrappers, and `where`'s first-line
+ // match is not guaranteed to be a launchable one (this is exactly
+ // what produced the literal error text in #1865). Re-resolve via the
+ // same extension-aware filesystem search the agent runner uses
+ // (server/lib/bufferedSpawn.js's resolveWindowsExecutable) and prefer
+ // it for both the actual invocation AND what we report back — falling
+ // back to the `where` result only when that search finds nothing.
+ const invokePath = (isWin32 && resolveWindowsExecutable(provider.command)) || commandPath;
+
+ // Track whether the resolved path could actually be spawned. Without
+ // this, a non-spawnable shim falls through to `version: 'available'`
+ // and the Test button reports a provider the runner can never
+ // actually invoke as usable.
let everSpawned = false;
const tryVersion = async (flag) => {
- // Invoke the resolved path so Windows runs the exact `.exe` we found —
- // execFile won't re-apply PATHEXT to a bare command name. `commandPath`
- // is frequently a `.cmd`/`.bat` npm shim on Windows, which execFile
- // can't launch without a shell — route through one there (the agent
- // runner does the same; see server/services/runner.js IS_WIN32) so
- // this probe matches what a real run can actually do.
+ // 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.
try {
- const out = await execFileAsync(commandPath, [flag], { shell: isWin32 });
+ const out = await execFileAsync(invokePath, [flag]);
everSpawned = true;
return out?.stdout?.trim() || null;
} catch (err) {
@@ -490,13 +527,13 @@ export function createProviderService(config = {}) {
if (!everSpawned) {
return {
success: false,
- error: `Resolved '${provider.command}' to ${commandPath} but it could not be executed (a Windows .cmd/.bat npm shim is not directly spawnable by the agent runner)`,
+ error: `Resolved '${provider.command}' to ${invokePath} but it could not be executed (a Windows .cmd/.bat npm shim is not directly spawnable by the agent runner)`,
};
}
return {
success: true,
- path: commandPath,
+ path: invokePath,
version: versionOut || 'available'
};
}
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 9f958c1c21..b987222089 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -1,23 +1,54 @@
import { mkdir, readFile, readdir, rm } from 'fs/promises';
import { atomicWrite } from './internal/atomicWrite.js';
import { existsSync } from 'fs';
-import { join, extname, basename, isAbsolute } from 'path';
+import { join, extname, basename, isAbsolute, delimiter } from 'path';
import { spawn } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';
// npm-installed CLI providers (claude, codex, opencode, …) are .cmd/.bat
// shims on Windows; Node's spawn() can't execute those without going through
-// cmd.exe. Mirrors `server/lib/bufferedSpawn.js`'s IS_WIN32/killProcessTree
-// pattern — duplicated rather than imported, since this directory must stay
-// self-contained (see ./CLAUDE.md).
+// cmd.exe. Mirrors `server/lib/bufferedSpawn.js`'s IS_WIN32/killProcessTree/
+// resolveWindowsExecutable pattern — duplicated rather than imported, since
+// this directory must stay self-contained (see ./CLAUDE.md).
const IS_WIN32 = process.platform === 'win32';
-// On Windows, shell:true wraps the child in a cmd.exe process, so a plain
-// SIGTERM only kills that wrapper and orphans the real child. Use taskkill to
-// take down the whole process tree there; SIGTERM is sufficient elsewhere.
+// Extensions Windows can launch directly, checked in cmd.exe's own resolution
+// preference. Deliberately excludes an extension-less match — npm ships a
+// POSIX shell-script stub alongside a package's `.cmd`/`.bat`/`.ps1` Windows
+// wrappers (for Git Bash/WSL), and that stub is not natively launchable here.
+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).
+ */
+function resolveWindowsExecutable(command, isWin32 = IS_WIN32) {
+ if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
+ const pathDirs = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ for (const dir of pathDirs) {
+ for (const ext of WIN_EXECUTABLE_EXTS) {
+ const candidate = join(dir, `${command}${ext}`);
+ if (existsSync(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
+// 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
+// POSIX branch) so callers elsewhere that gate re-entrant kill handling on
+// `.killed` actually engage on Windows. A plain SIGTERM kills the cmd.exe
+// wrapper but orphans the real child, so the whole process tree is taken
+// down via `taskkill /T /F` there; SIGTERM is sufficient elsewhere.
function killProcessTree(child) {
if (IS_WIN32 && child.pid) {
+ child.killed = true;
spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true })
.on('error', () => {})
.unref();
@@ -306,16 +337,17 @@ export function createRunnerService(config = {}) {
// Pass the prompt via stdin (not argv) and run without a shell so that
// 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.
+ // 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.
const args = [...(provider.args || [])];
console.log(`🚀 Executing CLI: ${provider.command} ${args.join(' ')} (${prompt.length} chars via stdin)`);
- const childProcess = spawn(provider.command, args, {
+ const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;
+ const childProcess = spawn(resolvedCommand, args, {
cwd: workspacePath,
env: { ...process.env, ...provider.envVars },
- windowsHide: true,
- // See IS_WIN32 above — .cmd/.bat npm shims need a shell on Windows.
- shell: IS_WIN32
+ windowsHide: true
});
if (childProcess.stdin) {
childProcess.stdin.write(prompt);
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 0b73e6a868..a1bb47d8dd 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -282,7 +282,16 @@ describe('AI Toolkit runner — built-in executeCliRun spawn (#1865)', () => {
return child;
}
- it('passes shell: IS_WIN32 to spawn so npm-installed CLI shims can launch on Windows', async () => {
+ it('never enables shell:true — resolveWindowsExecutable (not a shell) is the Windows fix', async () => {
+ // resolveWindowsExecutable is module-private here, and its IS_WIN32 default
+ // is bound once at module load like the rest of the codebase's win32-gated
+ // logic (see bufferedSpawn.test.js) — it can't be faked by mutating
+ // process.platform mid-test. The resolution ALGORITHM itself is exhaustively
+ // covered by server/lib/bufferedSpawn.test.js's injectable-isWin32 tests
+ // (this file's copy is a byte-for-byte mirror); this test only pins the
+ // wiring — that the built-in spawn never falls back to shell:true (the
+ // DEP0190-unsafe approach this directory rejected — see resolveWindowsExecutable
+ // docstring above) regardless of platform.
const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-spawn-'));
const runner = createRunnerService({ dataDir });
const child = makeChild();
@@ -301,8 +310,11 @@ describe('AI Toolkit runner — built-in executeCliRun spawn (#1865)', () => {
runId: 'builtin-run', provider, prompt: 'test prompt', onComplete: resolveComplete,
});
- const [, , options] = spawn.mock.calls.at(-1);
- expect(options.shell).toBe(process.platform === 'win32');
+ const [command, , options] = spawn.mock.calls.at(-1);
+ expect(options.shell).toBeFalsy();
+ // Off win32 (the host actually running this suite), resolution is a no-op
+ // and the bare command is spawned unchanged.
+ if (process.platform !== 'win32') expect(command).toBe('opencode');
// The 'close' handler's atomicWrite calls run after executeCliRun returns
// — wait for completion before removing dataDir, or rm races the writes.
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index 0ff3c00393..078c09ab66 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -1,4 +1,6 @@
import { spawn } from 'child_process';
+import { existsSync } from 'fs';
+import { delimiter, isAbsolute, join } from 'path';
/**
* Shared buffered-spawn + Windows kill-tree machinery used by the app build and
@@ -32,6 +34,52 @@ export const WIN_CMD_SHIMS = new Set(['npm', 'npx']);
*/
export const needsShell = (cmd) => IS_WIN32 && WIN_CMD_SHIMS.has(cmd);
+// Extensions Windows can launch directly, checked in cmd.exe's own resolution
+// preference (a real .exe wins over a batch shim when both exist). Deliberately
+// excludes an extension-less match — npm ships a POSIX shell-script stub
+// alongside a package's `.cmd`/`.bat`/`.ps1` Windows wrappers (for Git
+// Bash/WSL), and that stub is not natively launchable on Windows.
+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).
+ *
+ * Deliberately filesystem-only (no `where`/`which` subprocess) so resolution
+ * is synchronous and side-effect-free.
+ *
+ * @param {string} command - bare command name, or an existing path (returned unchanged)
+ * @param {boolean} [isWin32] - injectable for tests; defaults to the real platform
+ * @returns {string|null} the resolved absolute path, or null when not found
+ * (off win32, command is already a path, or no match exists on PATH)
+ */
+export function resolveWindowsExecutable(command, isWin32 = IS_WIN32) {
+ if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
+ const pathDirs = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ for (const dir of pathDirs) {
+ for (const ext of WIN_EXECUTABLE_EXTS) {
+ const candidate = join(dir, `${command}${ext}`);
+ if (existsSync(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
// 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;
@@ -44,10 +92,18 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;
* is fire-and-forget: its own `error` is swallowed and the handle is unref'd so
* it never keeps the event loop alive. Elsewhere, a plain SIGTERM suffices.
*
+ * `child.killed` is set synchronously on the win32 branch (mirroring what
+ * Node's own `child.kill()` does for the POSIX branch) — callers elsewhere
+ * gate re-entrant kill/abort handling on `.killed`, and `taskkill` runs in a
+ * separate detached process that never touches the original ChildProcess
+ * object, so without this the flag would stay `false` for the process's
+ * entire lifetime and those guards would never engage on Windows.
+ *
* @param {import('child_process').ChildProcess} child
*/
export function killProcessTree(child) {
if (IS_WIN32 && child.pid) {
+ child.killed = true;
spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true })
.on('error', () => {})
.unref();
diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.js
index b74d95a537..87935163b7 100644
--- a/server/lib/bufferedSpawn.test.js
+++ b/server/lib/bufferedSpawn.test.js
@@ -1,5 +1,8 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
// Mock child_process.spawn so we can drive the buffered-spawn machinery without
// launching real processes.
@@ -12,6 +15,7 @@ const {
bufferedSpawnOrThrow,
killProcessTree,
needsShell,
+ resolveWindowsExecutable,
IS_WIN32,
WIN_CMD_SHIMS,
MAX_OUTPUT_BYTES,
@@ -66,7 +70,7 @@ describe('killProcessTree', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
- it('on Windows spawns taskkill /T /F against the pid', () => {
+ it('on Windows spawns taskkill /T /F against the pid and marks the child killed', () => {
if (!IS_WIN32) return; // can't simulate platform branch from outside
const child = makeFakeChild({ pid: 999 });
const tk = makeFakeChild();
@@ -77,6 +81,63 @@ describe('killProcessTree', () => {
'taskkill', ['/T', '/F', '/PID', '999'],
expect.objectContaining({ stdio: 'ignore', windowsHide: true })
);
+ // taskkill runs in a detached process that never touches `child` itself —
+ // .killed must be set synchronously here so re-entrant kill/abort guards
+ // elsewhere (gated on `!child.killed`) actually engage on Windows.
+ expect(child.killed).toBe(true);
+ });
+});
+
+describe('resolveWindowsExecutable', () => {
+ // isWin32 is passed explicitly so these tests are deterministic regardless
+ // of the host platform actually running them.
+ let fakePathDir;
+ let originalPath;
+
+ beforeEach(async () => {
+ fakePathDir = await mkdtemp(join(tmpdir(), 'resolve-win-exe-'));
+ originalPath = process.env.PATH;
+ process.env.PATH = fakePathDir;
+ });
+
+ afterEach(async () => {
+ process.env.PATH = originalPath;
+ await rm(fakePathDir, { recursive: true, force: true });
+ });
+
+ it('returns null when isWin32 is false, regardless of what is on PATH', async () => {
+ await writeFile(join(fakePathDir, 'opencode.cmd'), '@echo off\n');
+ expect(resolveWindowsExecutable('opencode', false)).toBeNull();
+ });
+
+ it('resolves a bare command to its .cmd shim on PATH', async () => {
+ await writeFile(join(fakePathDir, 'opencode.cmd'), '@echo off\n');
+ expect(resolveWindowsExecutable('opencode', true)).toBe(join(fakePathDir, 'opencode.cmd'));
+ });
+
+ it('prefers a real .exe over a .cmd shim when both exist', async () => {
+ await writeFile(join(fakePathDir, 'tool.cmd'), '@echo off\n');
+ await writeFile(join(fakePathDir, 'tool.exe'), '');
+ expect(resolveWindowsExecutable('tool', true)).toBe(join(fakePathDir, 'tool.exe'));
+ });
+
+ it('never matches an extension-less POSIX shim stub (the actual #1865 root cause)', async () => {
+ // npm ships a bare POSIX shell-script stub alongside the .cmd/.bat/.ps1
+ // Windows wrappers for Git Bash/WSL — it is not natively launchable.
+ await writeFile(join(fakePathDir, 'opencode'), '#!/bin/sh\n');
+ expect(resolveWindowsExecutable('opencode', true)).toBeNull();
+ });
+
+ it('returns null when nothing matches on PATH', () => {
+ expect(resolveWindowsExecutable('does-not-exist', true)).toBeNull();
+ });
+
+ it('returns null for an already-absolute path (nothing to resolve)', () => {
+ expect(resolveWindowsExecutable('C:\\tools\\opencode.cmd', true)).toBeNull();
+ });
+
+ it('returns null for a relative path containing a separator', () => {
+ expect(resolveWindowsExecutable('./bin/opencode', true)).toBeNull();
});
});
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 1e63391c02..7dcbfaeafa 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 { IS_WIN32, killProcessTree } from './bufferedSpawn.js';
+import { killProcessTree, resolveWindowsExecutable } from './bufferedSpawn.js';
/**
* Resolve which CLI provider + model a feature should use from the providers
@@ -97,11 +97,14 @@ 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.
- const child = spawn(provider.command, spawnArgs, {
+ // 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.
+ const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;
+ const child = spawn(resolvedCommand, spawnArgs, {
cwd: cwd || process.cwd(),
- // npm-installed CLI providers are .cmd/.bat shims on Windows, which
- // need a shell to execute (see server/lib/bufferedSpawn.js IS_WIN32).
- shell: IS_WIN32,
stdio: ['pipe', 'pipe', 'pipe'],
env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
windowsHide: true,
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index f93c026eeb..e1189e9bba 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -1,5 +1,16 @@
-import { describe, it, expect } from 'vitest';
-import { pickCliProvider, runCliProviderPrompt } from './cliProviderRun.js';
+import { describe, it, expect, vi } from 'vitest';
+
+// Wrap the REAL resolveWindowsExecutable in a spy (not a stub) so every
+// existing real-spawn 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 runCliProviderPrompt actually spawns it.
+vi.mock('./bufferedSpawn.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, resolveWindowsExecutable: vi.fn(actual.resolveWindowsExecutable) };
+});
+
+const { pickCliProvider, runCliProviderPrompt } = await import('./cliProviderRun.js');
+const { resolveWindowsExecutable } = await import('./bufferedSpawn.js');
const cli = (id, extra = {}) => ({ id, type: 'cli', command: id, enabled: true, models: [], ...extra });
@@ -107,4 +118,21 @@ describe('runCliProviderPrompt', () => {
expect(result.error).toBeUndefined();
expect(result.exitCode).toBe(0);
});
+
+ it('spawns the resolveWindowsExecutable-resolved path when one is found (#1865)', async () => {
+ // Force resolution to a real binary (resolved via `which`, so this works
+ // regardless of the host's exact PATH layout) so the round-trip still
+ // completes — proves the resolved path, not the bare provider.command,
+ // is what actually gets spawned.
+ const { execFileSync } = await import('child_process');
+ const catPath = execFileSync('which', ['cat']).toString().trim();
+ vi.mocked(resolveWindowsExecutable).mockReturnValueOnce(catPath);
+ const result = await runCliProviderPrompt({
+ provider: { id: 'gemini-cli', type: 'cli', command: 'this-name-is-never-spawned-directly', args: [] },
+ prompt: 'resolved path round-trip',
+ });
+ expect(result.error).toBeUndefined();
+ expect(result.text).toBe('resolved path round-trip');
+ expect(result.exitCode).toBe(0);
+ });
});
diff --git a/server/services/runner.js b/server/services/runner.js
index 237051460c..703d825e85 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 { IS_WIN32, killProcessTree } from '../lib/bufferedSpawn.js';
+import { killProcessTree, resolveWindowsExecutable } from '../lib/bufferedSpawn.js';
import {
setAIToolkitInstance,
getAIToolkitInstance,
@@ -161,14 +161,17 @@ export async function patchRunMetadata(runId, patch) {
/**
* Override executeCliRun.
*
- * Runs without a shell on POSIX (Node 18.20+/20.10+ already auto-escapes args
- * for Windows .bat/.cmd shims per CVE-2024-27980, so `shell:false` there
- * avoided the old DEP0190 warning and metacharacter-injection surface). On
- * win32, `shell: IS_WIN32` is required: npm-installed CLI providers
- * (opencode, codex, claude, …) are .cmd/.bat shims that Node can't execute
- * without going through cmd.exe — see #1865. Prompt content rides stdin, not
- * argv, and `args` is still escaped by Node for the shell, so this doesn't
- * reopen the injection surface DEP0190 warned about.
+ * 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`.
*/
export async function executeCliRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout }) {
const toolkit = requireToolkit();
@@ -198,18 +201,18 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
const args = buildCliArgs(provider);
console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via stdin)`);
- childProcess = spawn(provider.command, args, {
+ // 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.
+ const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;
+
+ childProcess = spawn(resolvedCommand, args, {
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.
env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })(),
- windowsHide: true,
- // npm-installed CLI providers (opencode, codex, claude, …) are .cmd/.bat
- // shims on Windows; Node can't execute those without going through
- // cmd.exe. See server/lib/bufferedSpawn.js for the same IS_WIN32 pattern
- // used elsewhere in PortOS. Array args are still escaped by Node for the
- // shell, so this doesn't reopen metacharacter injection in `args`.
- shell: IS_WIN32
+ windowsHide: true
});
// Pass prompt via stdin to avoid OS argv limits
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index cab95b3a33..be5277e64c 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -1,12 +1,20 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import EventEmitter from 'events';
-import { IS_WIN32 } from '../lib/bufferedSpawn.js';
vi.mock('child_process', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, spawn: vi.fn() };
});
+// 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.
+vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, resolveWindowsExecutable: vi.fn(() => null) };
+});
+
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
@@ -181,12 +189,10 @@ describe('executeCliRun — Codex sentinel suppression', () => {
});
describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {
- // IS_WIN32 (imported from bufferedSpawn.js) is bound once at module load
- // from the real `process.platform`, like the rest of the codebase's
- // win32-gated tests (see bufferedSpawn.test.js) — it can't be faked by
- // mutating process.platform mid-test. Assert the spawn option mirrors the
- // constant so this pins the wiring on every platform CI actually runs on.
- it('passes shell: IS_WIN32 to spawn so npm-installed CLI shims (opencode, codex, claude) can launch on Windows', async () => {
+ 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');
+
const child = makeChild();
spawn.mockReturnValue(child);
@@ -197,10 +203,34 @@ describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {
child.emit('close', 0);
});
- await executeCliRun({ runId: 'run-shell-opt', provider, prompt: 'test prompt', workspacePath: '/workspace' });
+ 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.
+ expect(options.shell).toBeFalsy();
+ });
+
+ it('falls back to the bare command when resolution finds nothing (e.g. off win32, or not on PATH)', async () => {
+ const { resolveWindowsExecutable } = await import('../lib/bufferedSpawn.js');
+ vi.mocked(resolveWindowsExecutable).mockReturnValueOnce(null);
+
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ const provider = { id: 'codex', command: 'codex', args: [], timeout: 5000 };
+
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from('output'));
+ child.emit('close', 0);
+ });
+
+ await executeCliRun({ runId: 'run-unresolved', provider, prompt: 'test prompt', workspacePath: '/workspace' });
- const [, , options] = spawn.mock.calls.at(-1);
- expect(options.shell).toBe(IS_WIN32);
+ const [command, , options] = spawn.mock.calls.at(-1);
+ expect(command).toBe('codex');
+ expect(options.shell).toBeFalsy();
});
});
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index 257cf73ac8..84c67699a3 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 { IS_WIN32, killProcessTree } from '../lib/bufferedSpawn.js';
+import { killProcessTree, resolveWindowsExecutable } from '../lib/bufferedSpawn.js';
const CLI_VISION_TIMEOUT_MS = 120000;
const IMAGE_BASENAME = 'vision-input.png';
@@ -115,15 +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.
+ const resolvedCommand = resolveWindowsExecutable(command) || command;
+
const text = await new Promise((resolve, reject) => {
- const child = spawnImpl(command, args, {
+ const child = spawnImpl(resolvedCommand, args, {
cwd,
env: (() => { const e = { ...process.env, ...provider?.envVars }; delete e.CLAUDECODE; return e; })(),
windowsHide: true,
stdio: ['pipe', 'pipe', 'pipe'],
- // npm-installed CLI providers are .cmd/.bat shims on Windows, which
- // need a shell to execute (see server/lib/bufferedSpawn.js IS_WIN32).
- shell: IS_WIN32,
});
let out = '';
let err = '';
diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.js
index 16846c1ad9..62168f8914 100644
--- a/server/services/visionCli.test.js
+++ b/server/services/visionCli.test.js
@@ -1,10 +1,21 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
-import {
+
+// 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.
+vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, resolveWindowsExecutable: vi.fn(actual.resolveWindowsExecutable) };
+});
+
+const {
decodeImageDataUrl,
buildCliVisionInvocation,
describeImageViaCli,
-} from './visionCli.js';
+} = await import('./visionCli.js');
+const { resolveWindowsExecutable } = await import('../lib/bufferedSpawn.js');
const PNG_DATA_URL = `data:image/png;base64,${Buffer.from('fake-png').toString('base64')}`;
@@ -104,6 +115,27 @@ 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');
+ const child = makeFakeChild();
+ const spawnImpl = spawnEmitting(child, (c) => {
+ c.stdout.emit('data', Buffer.from('caption'));
+ c.emit('close', 0);
+ });
+ const promise = describeImageViaCli({
+ provider: { id: 'codex', command: 'codex', args: [] },
+ dataUrl: PNG_DATA_URL,
+ prompt: 'caption this',
+ 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).
+ expect(options.shell).toBeUndefined();
+ });
+
it('strips the codex session transcript down to the assistant reply', async () => {
const child = makeFakeChild();
// A realistic codex exec transcript: banner … \ncodex\n<reply>\ntokens used …