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 (codex): honor provider PATH override, escape the resolved command path

[._.]/ Adam Eivy4fcf0a3c603f
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 2789ddaa09..953baadd67 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -34,9 +34,9 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
* 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') {
+function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32', searchEnv = process.env) {
if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
- const pathDirs = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);
for (const dir of pathDirs) {
for (const ext of WIN_EXECUTABLE_EXTS) {
const candidate = join(dir, `${command}${ext}`);
@@ -59,7 +59,10 @@ const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;
*/
function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {
if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {
- return { command: 'cmd.exe', args: ['/c', command, ...args.map(escapeCmdMetacharsIfUnquoted)] };
+ return {
+ command: 'cmd.exe',
+ args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],
+ };
}
return { command, args };
}
@@ -531,10 +534,14 @@ export function createProviderService(config = {}) {
// 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;
+ // (server/lib/bufferedSpawn.js's resolveWindowsExecutable), searched
+ // against the same provider-envVars-merged env the runner actually
+ // spawns under (so a configured PATH override is honored here too),
+ // 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 searchEnv = { ...process.env, ...provider.envVars };
+ const invokePath = (isWin32 && resolveWindowsExecutable(provider.command, isWin32, searchEnv)) || commandPath;
// Track whether the resolved path could actually be spawned. Without
// this, a non-spawnable shim falls through to `version: 'available'`
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index a0a85280aa..ba61f198b6 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -24,12 +24,14 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
* 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 }`.
+ * full root-cause explanation (including why `searchEnv` matters — a
+ * provider-configured PATH override), mirrored here for self-containment.
+ * Pair with `prepareWindowsSafeSpawn` below to get a launchable
+ * `{ command, args }`.
*/
-function resolveWindowsExecutable(command, isWin32 = IS_WIN32) {
+function resolveWindowsExecutable(command, isWin32 = IS_WIN32, searchEnv = process.env) {
if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
- const pathDirs = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);
for (const dir of pathDirs) {
for (const ext of WIN_EXECUTABLE_EXTS) {
const candidate = join(dir, `${command}${ext}`);
@@ -55,7 +57,10 @@ const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;
*/
function prepareWindowsSafeSpawn(command, args, isWin32 = IS_WIN32) {
if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {
- return { command: 'cmd.exe', args: ['/c', command, ...args.map(escapeCmdMetacharsIfUnquoted)] };
+ return {
+ command: 'cmd.exe',
+ args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],
+ };
}
return { command, args };
}
@@ -393,11 +398,14 @@ export function createRunnerService(config = {}) {
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 childEnv = { ...process.env, ...provider.envVars };
+ // Resolved against `childEnv` (not bare process.env) so a
+ // provider-configured PATH override is honored.
+ const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;
const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);
const childProcess = spawn(spawnCommand, spawnArgs, {
cwd: workspacePath,
- env: { ...process.env, ...provider.envVars },
+ env: childEnv,
windowsHide: true
});
if (childProcess.stdin) {
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index 49c44c3157..b9a84ad3a9 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -55,14 +55,20 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
* is synchronous and side-effect-free. Pair with `prepareWindowsSafeSpawn`
* below to get a `{ command, args }` pair that's actually launchable.
*
+ * Searches `searchEnv.PATH`/`.Path`, NOT necessarily `process.env` — pass the
+ * actual env object the child will run under (e.g. after merging a
+ * provider's `envVars`) so a per-provider `PATH` override is honored. The
+ * default is `process.env` for callers that don't customize the child env.
+ *
* @param {string} command - bare command name, or an existing path (returned unchanged)
* @param {boolean} [isWin32] - injectable for tests; defaults to the real platform
+ * @param {NodeJS.ProcessEnv} [searchEnv] - env to read PATH from; defaults to `process.env`
* @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) {
+export function resolveWindowsExecutable(command, isWin32 = IS_WIN32, searchEnv = process.env) {
if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;
- const pathDirs = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);
for (const dir of pathDirs) {
for (const ext of WIN_EXECUTABLE_EXTS) {
const candidate = join(dir, `${command}${ext}`);
@@ -96,12 +102,15 @@ const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;
* A resolved native `.exe`/`.com` target needs no wrapping at all — it's
* directly launchable, so it's returned unchanged.
*
- * Each arg is also passed through `escapeCmdMetacharsIfUnquoted` (see its
- * docstring) — Node's own argv→command-line quoting only wraps an arg in
- * literal double quotes when it contains whitespace/a quote; an arg with
- * none of those reaches cmd.exe's raw command line UNQUOTED, so a bare
- * metacharacter like `&` in it would still be interpreted by cmd.exe as a
- * command separator despite `shell:false`.
+ * The resolved path AND each arg are passed through
+ * `escapeCmdMetacharsIfUnquoted` (see its docstring) — Node's own
+ * argv→command-line quoting only wraps a value in literal double quotes when
+ * it contains whitespace/a quote; a value with none of those reaches
+ * cmd.exe's raw command line UNQUOTED, so a bare metacharacter like `&` in
+ * it would still be interpreted by cmd.exe as a command separator despite
+ * `shell:false` — this covers both a metacharacter in an arg AND one in the
+ * resolved install path itself (e.g. a custom npm prefix directory named
+ * `C:\Tools&CLIs\npm`).
*
* @param {string} command - bare name, or a resolveWindowsExecutable result
* @param {string[]} args
@@ -110,7 +119,10 @@ const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;
*/
export function prepareWindowsSafeSpawn(command, args, isWin32 = IS_WIN32) {
if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {
- return { command: 'cmd.exe', args: ['/c', command, ...args.map(escapeCmdMetacharsIfUnquoted)] };
+ return {
+ command: 'cmd.exe',
+ args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],
+ };
}
return { command, args };
}
diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.js
index 7f58fee8da..3af8e4e01a 100644
--- a/server/lib/bufferedSpawn.test.js
+++ b/server/lib/bufferedSpawn.test.js
@@ -166,6 +166,30 @@ describe('resolveWindowsExecutable', () => {
it('returns null for a relative path containing a separator', () => {
expect(resolveWindowsExecutable('./bin/opencode', true)).toBeNull();
});
+
+ it('searches the given searchEnv.PATH, not bare process.env, honoring a provider-configured PATH override', async () => {
+ // A provider's envVars can override PATH for the child process — the CLI
+ // may live somewhere the PARENT process.env.PATH never points to.
+ const customDir = await mkdtemp(join(tmpdir(), 'resolve-win-exe-custom-'));
+ try {
+ await writeFile(join(customDir, 'opencode.cmd'), '@echo off\n');
+ // process.env.PATH (set in beforeEach) does NOT include customDir.
+ expect(resolveWindowsExecutable('opencode', true)).toBeNull();
+ expect(resolveWindowsExecutable('opencode', true, { PATH: customDir })).toBe(join(customDir, 'opencode.cmd'));
+ } finally {
+ await rm(customDir, { recursive: true, force: true });
+ }
+ });
+
+ it('falls back to searchEnv.Path (capital-P-lowercase, the Windows convention) when PATH is absent', async () => {
+ const customDir = await mkdtemp(join(tmpdir(), 'resolve-win-exe-capital-'));
+ try {
+ await writeFile(join(customDir, 'opencode.cmd'), '@echo off\n');
+ expect(resolveWindowsExecutable('opencode', true, { Path: customDir })).toBe(join(customDir, 'opencode.cmd'));
+ } finally {
+ await rm(customDir, { recursive: true, force: true });
+ }
+ });
});
describe('prepareWindowsSafeSpawn', () => {
@@ -221,6 +245,13 @@ describe('prepareWindowsSafeSpawn', () => {
const result = prepareWindowsSafeSpawn('/usr/local/bin/tool.cmd', ['foo&bar'], false);
expect(result.args).toEqual(['foo&bar']);
});
+
+ it('also caret-escapes a metacharacter in the resolved command path itself (e.g. a custom install dir)', () => {
+ // A custom npm prefix directory containing a metacharacter, with no
+ // whitespace, would reach cmd.exe unquoted just like an unquoted arg.
+ const result = prepareWindowsSafeSpawn('C:\\Tools&CLIs\\npm\\codex.cmd', ['exec'], true);
+ expect(result).toEqual({ command: 'cmd.exe', args: ['/c', 'C:\\Tools^&CLIs\\npm\\codex.cmd', 'exec'] });
+ });
});
describe('bufferedSpawn — structured result', () => {
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 80799883e6..6d8d9c05c3 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -97,18 +97,22 @@ 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 childEnv = { ...process.env, ...provider.envVars };
+ delete childEnv.CLAUDECODE;
+
// 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
+ // space would silently corrupt or be shell-injectable. Resolved against
+ // `childEnv` so a provider-configured PATH override is honored. See
// resolveWindowsExecutable/prepareWindowsSafeSpawn in
// server/lib/bufferedSpawn.js.
- const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;
+ const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;
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; })(),
+ env: childEnv,
windowsHide: true,
});
diff --git a/server/services/runner.js b/server/services/runner.js
index 9f9af921cc..496d1af242 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -202,16 +202,21 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
const args = buildCliArgs(provider);
console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via stdin)`);
+ // Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted
+ // agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.
+ const childEnv = { ...process.env, ...provider.envVars };
+ delete childEnv.CLAUDECODE;
+ Object.assign(childEnv, agentGuardEnv(childEnv));
+
// See the executeCliRun docblock above for why this is a resolve+wrap, not
- // a shell:true.
- const resolvedCommand = resolveWindowsExecutable(provider.command) || provider.command;
+ // a shell:true. Resolved against `childEnv` (not bare process.env) so a
+ // provider-configured PATH override is honored.
+ const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;
const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(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.
- env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })(),
+ env: childEnv,
windowsHide: true
});
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index 896b38c1a2..d90cf1892a 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -115,6 +115,9 @@ export async function describeImageViaCli({
await writeFile(join(dir, IMAGE_BASENAME), bytes);
const { command, args, stdin, cwd } = buildCliVisionInvocation(provider, visionModel, dir, prompt);
+ const childEnv = { ...process.env, ...provider?.envVars };
+ delete childEnv.CLAUDECODE;
+
// 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
@@ -123,16 +126,17 @@ export async function describeImageViaCli({
// 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
+ // which DOES preserve spaces within each arg as a single token. Resolved
+ // against `childEnv` so a provider-configured PATH override is honored.
+ // See resolveWindowsExecutable/prepareWindowsSafeSpawn in
// server/lib/bufferedSpawn.js.
- const resolvedCommand = resolveWindowsExecutable(command) || command;
+ const resolvedCommand = resolveWindowsExecutable(command, undefined, childEnv) || command;
const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);
const text = await new Promise((resolve, reject) => {
const child = spawnImpl(spawnCommand, spawnArgs, {
cwd,
- env: (() => { const e = { ...process.env, ...provider?.envVars }; delete e.CLAUDECODE; return e; })(),
+ env: childEnv,
windowsHide: true,
stdio: ['pipe', 'pipe', 'pipe'],
});