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: spawn npm-installed CLI providers through a shell on Windows
[._.]/ Adam Eivyfa707142db4f
diff --git a/server/lib/aiToolkit/providers.cliPathResolve.test.js b/server/lib/aiToolkit/providers.cliPathResolve.test.jsindex d206b54fc3..aaf105c311 100644--- a/server/lib/aiToolkit/providers.cliPathResolve.test.js+++ b/server/lib/aiToolkit/providers.cliPathResolve.test.js@@ -37,10 +37,17 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>const setPlatform = (value) => Object.defineProperty(process, 'platform', { value, configurable: true });+ // execFile's callback is always its last argument — the version probe now+ // passes an extra `{ shell }` options object (4 args) while the which/where+ // lookup stays at 3, so find the callback positionally instead of assuming+ // a fixed arity.+ const lastCallback = (args) => args[args.length - 1];+// Drive the mocked execFile: `lookup` is the stdout the which/where call emits,// `version` is the stdout the resolved-binary --version probe emits.const stubExec = ({ lookup, version = 'claude 1.0.0\n' }) => {- vi.mocked(execFile).mockImplementation((cmd, argv, cb) => {+ vi.mocked(execFile).mockImplementation((cmd, ...rest) => {+ const cb = lastCallback(rest);if (cmd === 'which' || cmd === 'where') {if (lookup === null) return cb(new Error('not found'));return cb(null, { stdout: lookup, stderr: '' });@@ -80,6 +87,28 @@ 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 () => {+ setPlatform('win32');+ stubExec({ lookup: 'C:\\Users\\Joe\\AppData\\Roaming\\npm\\claude.cmd\r\n' });+ const p = await makeCliProvider();++ 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: true });+ });++ it('does not enable a shell for the version probe on non-win32 platforms', async () => {+ setPlatform('linux');+ stubExec({ lookup: '/usr/local/bin/claude\n' });+ const p = await makeCliProvider();++ 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 });+ });+it('invokes the resolved path for the version probe (so win32 runs the exact .exe)', async () => {setPlatform('win32');stubExec({ lookup: 'C:\\Users\\Joe\\.local\\bin\\claude.exe\r\n' });@@ -119,7 +148,8 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>it('falls back to "available" when the binary spawns but supports no version flag', async () => {setPlatform('linux');- vi.mocked(execFile).mockImplementation((cmd, argv, cb) => {+ vi.mocked(execFile).mockImplementation((cmd, ...rest) => {+ const cb = lastCallback(rest);if (cmd === 'which' || cmd === 'where') return cb(null, { stdout: '/usr/local/bin/claude\n', stderr: '' });// The binary ran (it's spawnable) but exited non-zero on the unknown flag —// a numeric exit code is how Node surfaces a non-zero exit from execFile.@@ -136,10 +166,13 @@ describe('testProvider — cli command resolution (cross-platform PATH)', () =>it('reports failure when the resolved path cannot be spawned (Windows .cmd/.bat shim)', async () => {setPlatform('win32');- vi.mocked(execFile).mockImplementation((cmd, argv, cb) => {+ vi.mocked(execFile).mockImplementation((cmd, ...rest) => {+ const cb = lastCallback(rest);if (cmd === 'which' || cmd === 'where') return cb(null, { stdout: 'C:\\Users\\Joe\\AppData\\npm\\claude.cmd\r\n', stderr: '' });- // execFile (shell:false) cannot launch a .cmd shim — a spawn error carries a- // string code (ENOENT), distinct from a non-zero exit's numeric code.+ // Even with the runner's shell:true workaround, simulate a genuinely+ // unspawnable shim (e.g. corrupted/missing target) — a spawn error+ // carries a string code (ENOENT), distinct from a non-zero exit's+ // numeric code.const e = new Error('spawn claude.cmd ENOENT'); e.code = 'ENOENT';return cb(e);});diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 47e3bd55e4..e0d6e69e7c 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -439,12 +439,16 @@ export function createProviderService(config = {}) {}if (provider.type === 'cli' || provider.type === 'tui') {+ // Read fresh per call (not hoisted to module scope) so tests can drive+ // both branches by stubbing process.platform per test.+ const isWin32 = process.platform === 'win32';+// Resolve the command on PATH. Windows has no `which` — it ships `where`// instead — so a `which` lookup there always fails and falsely reports the// command "not found in PATH" even when it resolves fine from a shell.// Use execFile (no shell) so user-configured `provider.command` cannot// inject extra shell commands via metacharacters.- const lookup = process.platform === 'win32' ? 'where' : 'which';+ const lookup = isWin32 ? 'where' : 'which';const { stdout } = await execFileAsync(lookup, [provider.command]).catch(() => ({ stdout: '', stderr: 'not found' }));@@ -457,17 +461,20 @@ export function createProviderService(config = {}) {}// Track whether the resolved path could actually be spawned. A bare PATH- // lookup (`where`) on Windows happily returns npm `.cmd`/`.bat` shims,- // which execFile (shell:false) — and the agent runner, which also spawns- // shell:false — cannot launch. 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.+ // 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.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.+ // 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.try {- const out = await execFileAsync(commandPath, [flag]);+ const out = await execFileAsync(commandPath, [flag], { shell: isWin32 });everSpawned = true;return out?.stdout?.trim() || null;} catch (err) {diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex f40ffcc0be..9f958c1c21 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -6,6 +6,26 @@ 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).+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.+function killProcessTree(child) {+ if (IS_WIN32 && child.pid) {+ spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true })+ .on('error', () => {})+ .unref();+ } else {+ child.kill('SIGTERM');+ }+}+// Invoke a completion hook / callback so a throw is logged but never// propagates — these run at out-of-request boundaries where an uncaught throw// is an unhandled rejection that crashes the process. Each call is isolated so@@ -293,7 +313,9 @@ export function createRunnerService(config = {}) {const childProcess = spawn(provider.command, args, {cwd: workspacePath,env: { ...process.env, ...provider.envVars },- windowsHide: true+ windowsHide: true,+ // See IS_WIN32 above — .cmd/.bat npm shims need a shell on Windows.+ shell: IS_WIN32});if (childProcess.stdin) {childProcess.stdin.write(prompt);@@ -306,7 +328,7 @@ export function createRunnerService(config = {}) {const timeoutHandle = setTimeout(() => {if (childProcess && !childProcess.killed) {console.log(`⏱️ Run ${runId} timed out after ${timeout}ms`);- childProcess.kill('SIGTERM');+ killProcessTree(childProcess);}}, timeout);@@ -601,7 +623,7 @@ export function createRunnerService(config = {}) {// and drop it so a later isRunActive reports false.const external = externalRuns.get(runId);if (external) {- if (external.kill && !external.killed) external.kill('SIGTERM');+ if (external.kill && !external.killed) killProcessTree(external);else if (external.abort) external.abort();externalRuns.delete(runId);return true;@@ -611,7 +633,7 @@ export function createRunnerService(config = {}) {if (!active) return false;if (active.kill) {- active.kill('SIGTERM');+ killProcessTree(active);} else if (active.abort) {active.abort();}diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 736a4217f3..0b73e6a868 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -2,7 +2,15 @@ import { describe, it, expect, afterEach, vi } from 'vitest';import { mkdtemp, rm, readFile, writeFile } from 'fs/promises';import { join, basename } from 'path';import { tmpdir } from 'os';-import { createRunnerService } from './runner.js';+import EventEmitter from 'events';++vi.mock('child_process', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, spawn: vi.fn() };+});++const { spawn } = await import('child_process');+const { createRunnerService } = await import('./runner.js');describe('AI Toolkit runner service', () => {const tempDirs = [];@@ -258,3 +266,47 @@ describe('AI Toolkit runner — declared extension points', () => {await rm(dataDir, { recursive: true, force: true });});});++describe('AI Toolkit runner — built-in executeCliRun spawn (#1865)', () => {+ // Mirrors server/services/runner.test.js's equivalent assertion — this is+ // the toolkit's OWN spawn path (inert in PortOS, which always registers a+ // host CLI runner via setCliRunner, but must stay behaviorally in sync per+ // the override-consistency contract in ./CLAUDE.md).+ function makeChild() {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = { write: vi.fn(), end: vi.fn() };+ child.kill = vi.fn();+ child.killed = false;+ return child;+ }++ it('passes shell: IS_WIN32 to spawn so npm-installed CLI shims can launch on Windows', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-spawn-'));+ const runner = createRunnerService({ dataDir });+ const child = makeChild();+ spawn.mockReturnValue(child);++ const provider = { id: 'opencode', command: 'opencode', args: [], timeout: 5000, defaultModel: null };+ let resolveComplete;+ const completed = new Promise((resolve) => { resolveComplete = resolve; });++ setImmediate(() => {+ child.stdout.emit('data', Buffer.from('output'));+ child.emit('close', 0);+ });++ await runner.executeCliRun({+ runId: 'builtin-run', provider, prompt: 'test prompt', onComplete: resolveComplete,+ });++ const [, , options] = spawn.mock.calls.at(-1);+ expect(options.shell).toBe(process.platform === 'win32');++ // The 'close' handler's atomicWrite calls run after executeCliRun returns+ // — wait for completion before removing dataDir, or rm races the writes.+ await completed;+ await rm(dataDir, { recursive: true, force: true });+ });+});diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex a4b69597ed..1e63391c02 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -18,6 +18,7 @@import { spawn } from 'child_process';import { buildCliArgs } from './cliProviderArgs.js';+import { IS_WIN32, killProcessTree } from './bufferedSpawn.js';/*** Resolve which CLI provider + model a feature should use from the providers@@ -98,7 +99,9 @@ export function runCliProviderPrompt(args = {}) {// think it's running inside the parent Claude Code session.const child = spawn(provider.command, spawnArgs, {cwd: cwd || process.cwd(),- shell: false,+ // 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,@@ -115,7 +118,7 @@ export function runCliProviderPrompt(args = {}) {};const timer = setTimeout(() => {- if (!child.killed) child.kill('SIGTERM');+ if (!child.killed) killProcessTree(child);done({ error: `Provider call timed out after ${timeoutMs}ms`, text: stdout.trim(), stderr });}, timeoutMs);diff --git a/server/services/runner.js b/server/services/runner.jsindex ee59ddf210..237051460c 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -10,6 +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 {setAIToolkitInstance,getAIToolkitInstance,@@ -158,8 +159,16 @@ export async function patchRunMetadata(runId, patch) {}/**- * Override executeCliRun to fix shell security issue- * This removes 'shell: true' which causes DEP0190 warning and potential security issues+ * 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.*/export async function executeCliRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout }) {const toolkit = requireToolkit();@@ -182,7 +191,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onif (!analysis) return;immediateFallbackAnalysis = analysis;console.log(`⚡ Run ${runId} detected fallback signal (${analysis.category}); stopping ${provider.name || provider.id || provider.command}`);- childProcess.kill('SIGTERM');+ killProcessTree(childProcess);};// Build provider-specific args for stdin-based prompt delivery@@ -194,7 +203,13 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// 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+ 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});// Pass prompt via stdin to avoid OS argv limits@@ -213,7 +228,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onconst timeoutHandle = effectiveTimeout > 0 ? setTimeout(() => {if (childProcess && !childProcess.killed) {console.log(`⏱️ Run ${runId} timed out after ${effectiveTimeout}ms`);- childProcess.kill('SIGTERM');+ killProcessTree(childProcess);}}, effectiveTimeout) : null;diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex b9c24e429a..cab95b3a33 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -1,5 +1,6 @@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();@@ -179,6 +180,30 @@ 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 () => {+ const child = makeChild();+ spawn.mockReturnValue(child);++ const provider = { id: 'opencode', command: 'opencode', args: [], timeout: 5000 };++ setImmediate(() => {+ child.stdout.emit('data', Buffer.from('output'));+ child.emit('close', 0);+ });++ await executeCliRun({ runId: 'run-shell-opt', provider, prompt: 'test prompt', workspacePath: '/workspace' });++ const [, , options] = spawn.mock.calls.at(-1);+ expect(options.shell).toBe(IS_WIN32);+ });+});+describe('executeCliRun — close handler crash guard', () => {// Drive a codex run whose first write (output) succeeds and second write// (metadata) rejects, so the close handler's recovery path runs. Returns thediff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 116dec0fe7..257cf73ac8 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -30,6 +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';const CLI_VISION_TIMEOUT_MS = 120000;const IMAGE_BASENAME = 'vision-input.png';@@ -120,6 +121,9 @@ export async function describeImageViaCli({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 = '';@@ -129,7 +133,7 @@ export async function describeImageViaCli({// the promise would hang forever and the temp dir (cleaned in `finally`)// would leak. Escalate to SIGKILL on a short grace timer.const timer = timeout > 0 ? setTimeout(() => {- if (!child.killed) child.kill('SIGTERM');+ if (!child.killed) killProcessTree(child);killTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000);killTimer?.unref?.();reject(new Error(`${command} vision call timed out after ${timeout}ms`));