Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(hetero): detect Windows CLI agents behind unknown shims and stale PATH (#18220)

LiJian61e44df5265b
diff --git a/apps/desktop/src/main/core/infrastructure/BinaryManager.ts b/apps/desktop/src/main/core/infrastructure/BinaryManager.ts
index b377ef872cf..6a70e1a02d7 100644
--- a/apps/desktop/src/main/core/infrastructure/BinaryManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/BinaryManager.ts
@@ -15,6 +15,9 @@ const execPromise = promisify(exec);
const execFilePromise = promisify(execFile);
const logger = createLogger('core:BinaryManager');
+/** How long an "unavailable" verdict is trusted before it is probed again. */
+const UNAVAILABLE_STATUS_TTL = 60_000;
+
/**
* Where on the host a binary resolution came from. Lets the UI tell the user
* that the system-wide install is in use, vs the version this app downloaded
@@ -219,6 +222,22 @@ export class BinaryManager {
return true;
}
+ /**
+ * Whether a cached status must be re-detected.
+ *
+ * Only negatives expire. A binary that resolved once stays cached for the
+ * session, but "not available" is frequently a transient verdict β€” the CLI
+ * printed an upgrade banner that failed validation, or it was installed
+ * after this scan β€” and caching it forever pins the UI to "not installed"
+ * until the user finds the rescan button.
+ */
+ private isStaleStatus(status: BinaryStatus): boolean {
+ if (status.available) return false;
+
+ const checkedAt = status.lastChecked?.getTime();
+ return checkedAt === undefined || Date.now() - checkedAt >= UNAVAILABLE_STATUS_TTL;
+ }
+
/**
* Detect a single binary. Checks the manager's own cache first so a
* previously-installed managed copy wins over a stale `which` result.
@@ -234,8 +253,9 @@ export class BinaryManager {
};
}
- if (!force && this.statusCache.has(name)) {
- return this.statusCache.get(name)!;
+ const cached = this.statusCache.get(name);
+ if (!force && cached && !this.isStaleStatus(cached)) {
+ return cached;
}
const manageable = Boolean(spec.manage);
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts
index 6609207aa29..527cda89b8b 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts
@@ -141,6 +141,40 @@ describe('BinaryManager', () => {
expect(detect).not.toHaveBeenCalled();
});
+ it('re-probes an unavailable binary once the cached verdict ages out', async () => {
+ // A negative is often transient β€” the CLI printed an upgrade banner that
+ // failed validation, or it simply wasn't installed yet. Caching it for
+ // the whole session pins the UI to "not installed" with no way back.
+ vi.useFakeTimers();
+
+ try {
+ const mgr = new BinaryManager(stubApp);
+ const detect = vi
+ .fn<() => Promise<BinaryStatus>>()
+ .mockResolvedValueOnce({ available: false })
+ .mockResolvedValue({ available: true, path: '/usr/local/bin/foo', version: '1.0' });
+ mgr.register({ detect, name: 'foo' }, 'content-search');
+
+ expect((await mgr.detect('foo')).available).toBe(false);
+ // Repeated scans within the window reuse the verdict.
+ expect((await mgr.detect('foo')).available).toBe(false);
+ expect(detect).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(60_001);
+ const recovered = await mgr.detect('foo');
+
+ expect(recovered.available).toBe(true);
+ expect(detect).toHaveBeenCalledTimes(2);
+
+ // A positive verdict stays cached for the session.
+ vi.advanceTimersByTime(60_001);
+ await mgr.detect('foo');
+ expect(detect).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('marks unavailable + manageable when neither managed cache nor PATH has the binary', async () => {
const mgr = new BinaryManager(stubApp);
mgr.register(
diff --git a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
index 5ba2b9759c9..99d390075c7 100644
--- a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts
@@ -1,4 +1,5 @@
import * as childProcess from 'node:child_process';
+import * as fsPromises from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
@@ -16,9 +17,37 @@ vi.mock('node:child_process', () => ({
execFile: vi.fn(),
}));
+// Resolving a Windows `.cmd` shim to its real target reads the shim off disk.
+vi.mock('node:fs/promises', async () => {
+ const actual = await vi.importActual<typeof fsPromises>('node:fs/promises');
+ return { ...actual, access: vi.fn(), readFile: vi.fn() };
+});
+
const platformMock = vi.mocked(os.platform);
const execFileMock = vi.mocked(childProcess.execFile);
const execMock = vi.mocked(childProcess.exec);
+const accessMock = vi.mocked(fsPromises.access);
+const readFileMock = vi.mocked(fsPromises.readFile);
+
+/** Files present on the fake host: contents for shims, `true` for binaries. */
+const existingFiles = (files: Record<string, string | true>) => {
+ const entries = new Map(
+ Object.entries(files).map(([filePath, content]) => [filePath.toLowerCase(), content]),
+ );
+
+ accessMock.mockImplementation(async (filePath) => {
+ if (!entries.has(String(filePath).toLowerCase())) throw new Error(`missing: ${filePath}`);
+ });
+ readFileMock.mockImplementation((async (filePath: string) => {
+ const content = entries.get(String(filePath).toLowerCase());
+ if (typeof content !== 'string') throw new Error(`unreadable: ${filePath}`);
+ return content;
+ }) as never);
+};
+
+/** A stock npm shim β€” the shape the resolver knows how to unwrap. */
+const npmShim = (packagePath: string) =>
+ `@ECHO off\r\n"%dp0%\\node.exe" "%dp0%\\${packagePath}" %*\r\n`;
const noErr = null;
const callExecFile = (stdout: string, stderr = '') => {
@@ -37,10 +66,30 @@ const callExecFileError = (err: Error) => {
}) as any);
};
+/**
+ * Fail any call a test did not queue. Without this the promisified `execFile`
+ * never settles and the test dies on a 5s timeout that says nothing about
+ * which extra process was spawned.
+ */
+const rejectUnqueuedExecFile = () => {
+ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {
+ const callback = typeof opts === 'function' ? opts : cb;
+ callback(new Error(`unexpected execFile: ${file} ${JSON.stringify(args)}`), {
+ stderr: '',
+ stdout: '',
+ });
+ return {} as any;
+ }) as any);
+};
+
describe('cliAgentBinaries', () => {
beforeEach(() => {
execFileMock.mockReset();
execMock.mockReset();
+ accessMock.mockReset();
+ readFileMock.mockReset();
+ rejectUnqueuedExecFile();
+ existingFiles({});
});
afterEach(() => {
@@ -53,8 +102,15 @@ describe('cliAgentBinaries', () => {
});
it('resolves `claude` to the .cmd path via `where` without constructing a shell command', async () => {
+ const npmDir = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm';
+ const scriptPath = `${npmDir}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`;
+ existingFiles({
+ [`${npmDir}\\claude.cmd`]: npmShim('node_modules\\@anthropic-ai\\claude-code\\cli.js'),
+ [`${npmDir}\\node.exe`]: true,
+ [scriptPath]: true,
+ });
// 1) `where claude` β†’ resolves to the .cmd shim under %APPDATA%\npm
- callExecFile('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd\r\n');
+ callExecFile(`${npmDir}\\claude.cmd\r\n`);
// 2) validate the resolved command without interpolating it into a shell string
callExecFile('1.2.3 (Claude Code)');
@@ -62,26 +118,39 @@ describe('cliAgentBinaries', () => {
const status = await claudeCodeBinary.detect();
expect(status.available).toBe(true);
- expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd');
+ expect(status.path).toBe(`${npmDir}\\claude.cmd`);
expect(status.version).toBe('1.2.3 (Claude Code)');
expect(execMock).not.toHaveBeenCalled();
expect(execFileMock).toHaveBeenCalledTimes(2);
- expect(execFileMock.mock.calls[1]![0]).toBe(
- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd',
- );
- expect(execFileMock.mock.calls[1]![1]).toEqual(['--version']);
+ // The shim is unwrapped into node + script rather than handed to a shell.
+ expect(execFileMock.mock.calls[1]![0]).toBe(`${npmDir}\\node.exe`);
+ expect(execFileMock.mock.calls[1]![1]).toEqual([scriptPath, '--version']);
});
it('returns unavailable when `where` finds nothing', async () => {
- callExecFileError(new Error('not found'));
+ const originalPath = process.env.PATH;
+ // Single clean segment: the recovered PATH then equals it exactly, so no
+ // second `where` attempt runs.
+ process.env.PATH = 'C:\\Windows';
- const { claudeCodeBinary } = await import('../cliAgentBinaries');
- const status = await claudeCodeBinary.detect();
+ try {
+ callExecFileError(new Error('not found')); // where claude
+ // A failed `where` falls back to the registry PATH, in case this
+ // process is holding an environment snapshot older than the install.
+ callExecFileError(new Error('access denied')); // reg query HKLM
+ callExecFileError(new Error('access denied')); // reg query HKCU
- expect(status.available).toBe(false);
- // We should NOT proceed to invoke anything after a failed resolve.
- expect(execMock).not.toHaveBeenCalled();
+ const { claudeCodeBinary } = await import('../cliAgentBinaries');
+ const status = await claudeCodeBinary.detect();
+
+ expect(status.available).toBe(false);
+ // We should NOT proceed to invoke anything after a failed resolve.
+ expect(execMock).not.toHaveBeenCalled();
+ expect(execFileMock).toHaveBeenCalledTimes(3);
+ } finally {
+ process.env.PATH = originalPath;
+ }
});
it('rejects custom commands containing shell metacharacters', async () => {
@@ -107,12 +176,15 @@ describe('cliAgentBinaries', () => {
// npm drops a Unix shell-script wrapper (extensionless) alongside the
// Windows `.cmd` / `.ps1` shims. `where` lists every PATHEXT match;
// taking the first line would land us on the unrunnable wrapper.
+ const npmDir = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm';
+ const scriptPath = `${npmDir}\\node_modules\\@openai\\codex\\bin\\codex.js`;
+ existingFiles({
+ [`${npmDir}\\codex.cmd`]: npmShim('node_modules\\@openai\\codex\\bin\\codex.js'),
+ [`${npmDir}\\node.exe`]: true,
+ [scriptPath]: true,
+ });
callExecFile(
- [
- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex',
- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd',
- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.ps1',
- ].join('\r\n'),
+ [`${npmDir}\\codex`, `${npmDir}\\codex.cmd`, `${npmDir}\\codex.ps1`].join('\r\n'),
);
callExecFile('codex 0.130.0');
@@ -120,12 +192,10 @@ describe('cliAgentBinaries', () => {
const status = await codexBinary.detect();
expect(status.available).toBe(true);
- expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd');
+ expect(status.path).toBe(`${npmDir}\\codex.cmd`);
expect(execMock).not.toHaveBeenCalled();
- expect(execFileMock.mock.calls[1]![0]).toBe(
- 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd',
- );
- expect(execFileMock.mock.calls[1]![1]).toEqual(['--version']);
+ expect(execFileMock.mock.calls[1]![0]).toBe(`${npmDir}\\node.exe`);
+ expect(execFileMock.mock.calls[1]![1]).toEqual([scriptPath, '--version']);
});
it('prefers .exe over .cmd when both are present', async () => {
@@ -144,11 +214,15 @@ describe('cliAgentBinaries', () => {
});
it('preserves PATH order when npm .cmd precedes a later .exe (Vite+ case)', async () => {
+ const npmDir = 'C:\\Users\\hp\\AppData\\Roaming\\npm';
+ const scriptPath = `${npmDir}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`;
+ existingFiles({
+ [`${npmDir}\\claude.cmd`]: npmShim('node_modules\\@anthropic-ai\\claude-code\\cli.js'),
+ [`${npmDir}\\node.exe`]: true,
+ [scriptPath]: true,
+ });
callExecFile(
- [
- 'C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd',
- 'C:\\Users\\hp\\.vite-plus\\bin\\claude.exe',
- ].join('\r\n'),
+ [`${npmDir}\\claude.cmd`, 'C:\\Users\\hp\\.vite-plus\\bin\\claude.exe'].join('\r\n'),
);
callExecFile('1.2.3 (Claude Code)');
@@ -156,12 +230,33 @@ describe('cliAgentBinaries', () => {
const status = await claudeCodeBinary.detect();
expect(status.available).toBe(true);
- expect(status.path).toBe('C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd');
+ expect(status.path).toBe(`${npmDir}\\claude.cmd`);
expect(execMock).not.toHaveBeenCalled();
- expect(execFileMock.mock.calls[1]![0]).toBe(
- 'C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd',
- );
- expect(execFileMock.mock.calls[1]![1]).toEqual(['--version']);
+ expect(execFileMock.mock.calls[1]![0]).toBe(`${npmDir}\\node.exe`);
+ expect(execFileMock.mock.calls[1]![1]).toEqual([scriptPath, '--version']);
+ });
+
+ it('skips a shim it cannot unwrap and validates the next candidate instead', async () => {
+ // A third-party wrapper that replaced the npm shim forwards through its
+ // own variable, so no shim pattern matches. `execFile` cannot spawn a
+ // .cmd directly (EINVAL since the CVE-2024-27980 fix), so the only way
+ // to stay useful is to move on to the next entry `where` reported.
+ const hijackedShim = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd';
+ const nativeExe = 'C:\\Program Files\\WindowsApps\\OpenAI.Codex\\codex.exe';
+ existingFiles({
+ [hijackedShim]: '@echo off\r\n"%OCX_REAL_CODEX%" %*\r\n',
+ [nativeExe]: true,
+ });
+ callExecFile([hijackedShim, nativeExe].join('\r\n'));
+ callExecFile('codex-cli 0.146.0');
+
+ const { codexBinary } = await import('../cliAgentBinaries');
+ const status = await codexBinary.detect();
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe(nativeExe);
+ expect(execFileMock).toHaveBeenCalledTimes(2);
+ expect(execFileMock.mock.calls[1]![0]).toBe(nativeExe);
});
it('reports unavailable when `where` only returns unrunnable matches (.ps1 / extensionless)', async () => {
diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts
index bc7f1dc2754..cf3e3854910 100644
--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts
+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts
@@ -4,6 +4,13 @@ import { platform } from 'node:os';
import path from 'node:path';
const WINDOWS_EXE_EXT_PATTERN = /\.exe$/i;
+// `CreateProcess` limit, which is what this plan is spawned through: the plan
+// always names a real executable (an `.exe`, or `node.exe` plus the script a
+// shim pointed at), never a shell. Routing it through cmd.exe instead would
+// drop the ceiling to 8191 β€” and hand the prompt and conversation context to
+// cmd.exe for a second round of parsing (CVE-2024-27980). Detection probes a
+// `.cmd` we can't unwrap through `%ComSpec%` under its own 8191 check; the
+// launch path deliberately does not.
const WINDOWS_MAX_COMMAND_LINE_LENGTH = 32_767;
const WINDOWS_NODE_EXE_PATTERN = /(?:^|[\\/])node(?:\.exe)?$/i;
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
index af6e44ed638..7a8e9313582 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts
@@ -1,4 +1,5 @@
import * as childProcess from 'node:child_process';
+import * as fsPromises from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
@@ -16,9 +17,37 @@ vi.mock('node:child_process', () => ({
execFile: vi.fn(),
}));
+// `resolveCliSpawnPlan` reads Windows shims off disk to find their real target,
+// so shim scenarios need a fake filesystem.
+vi.mock('node:fs/promises', async () => {
+ const actual = await vi.importActual<typeof fsPromises>('node:fs/promises');
+ return { ...actual, access: vi.fn(), readFile: vi.fn() };
+});
+
const platformMock = vi.mocked(os.platform);
const execFileMock = vi.mocked(childProcess.execFile);
const execMock = vi.mocked(childProcess.exec);
+const accessMock = vi.mocked(fsPromises.access);
+const readFileMock = vi.mocked(fsPromises.readFile);
+
+/**
+ * Declare the files that exist on the fake host. Map a path to its contents to
+ * make it readable (shims), or to `true` for an opaque binary.
+ */
+const existingFiles = (files: Record<string, string | true>) => {
+ const entries = new Map(
+ Object.entries(files).map(([filePath, content]) => [filePath.toLowerCase(), content]),
+ );
+
+ accessMock.mockImplementation(async (filePath) => {
+ if (!entries.has(String(filePath).toLowerCase())) throw new Error(`missing: ${filePath}`);
+ });
+ readFileMock.mockImplementation((async (filePath: string) => {
+ const content = entries.get(String(filePath).toLowerCase());
+ if (typeof content !== 'string') throw new Error(`unreadable: ${filePath}`);
+ return content;
+ }) as never);
+};
const noErr = null;
const callExecFile = (stdout: string, stderr = '') => {
@@ -36,12 +65,32 @@ const callExecFileError = (err: Error) => {
return {} as any;
}) as any);
};
+/**
+ * Fail any call a test did not queue. Without this the promisified `execFile`
+ * never settles and the test dies on a 5s timeout that says nothing about
+ * which extra process was spawned.
+ */
+const rejectUnqueuedExecFile = () => {
+ execFileMock.mockImplementation(((file: string, args: any, opts: any, cb: any) => {
+ const callback = typeof opts === 'function' ? opts : cb;
+ callback(new Error(`unexpected execFile: ${file} ${JSON.stringify(args)}`), {
+ stderr: '',
+ stdout: '',
+ });
+ return {} as any;
+ }) as any);
+};
const importModule = () => import('./resolveCliCommand');
describe('resolveCliCommand', () => {
beforeEach(() => {
execFileMock.mockReset();
execMock.mockReset();
+ accessMock.mockReset();
+ readFileMock.mockReset();
+ rejectUnqueuedExecFile();
+ // Empty host by default β€” individual tests opt into the files they need.
+ existingFiles({});
});
afterEach(() => {
@@ -243,51 +292,66 @@ describe('resolveCliCommand', () => {
});
describe('detectValidatedCommand β€” Windows npm shims', () => {
+ const NPM_DIR = 'C:\\Users\\x\\AppData\\Roaming\\npm';
+ // A stock npm shim, the shape `resolveCliSpawnPlan` knows how to unwrap.
+ const npmShim = (packagePath: string) =>
+ `@ECHO off\r\n"%dp0%\\node.exe" "%dp0%\\${packagePath}" %*\r\n`;
+
beforeEach(() => {
platformMock.mockReturnValue('win32');
});
it('resolves `codex` to the .cmd shim without constructing a shell command', async () => {
- callExecFile('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd\r\n');
+ const shimPath = `${NPM_DIR}\\codex.cmd`;
+ const scriptPath = `${NPM_DIR}\\node_modules\\@openai\\codex\\bin\\codex.js`;
+ existingFiles({
+ [`${NPM_DIR}\\node.exe`]: true,
+ [scriptPath]: true,
+ [shimPath]: npmShim('node_modules\\@openai\\codex\\bin\\codex.js'),
+ });
+ callExecFile(`${shimPath}\r\n`);
callExecFile('codex 0.142.5');
const { detectValidatedCommand } = await importModule();
const status = await detectValidatedCommand('codex', { validateKeywords: ['codex'] });
expect(status.available).toBe(true);
- expect(status.path).toBe('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd');
- expect(execFileMock.mock.calls[1]![0]).toBe('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd');
- expect(execFileMock.mock.calls[1]![1]).toEqual(['--version']);
+ expect(status.path).toBe(shimPath);
+ // The shim is unwrapped to node + script, never handed to a shell.
+ expect(execFileMock.mock.calls[1]![0]).toBe(`${NPM_DIR}\\node.exe`);
+ expect(execFileMock.mock.calls[1]![1]).toEqual([scriptPath, '--version']);
expect(execMock).not.toHaveBeenCalled();
});
it('prefers the .cmd shim when `where` returns multiple PATHEXT matches', async () => {
- callExecFile(
- [
- 'C:\\Users\\x\\AppData\\Roaming\\npm\\codex',
- 'C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd',
- 'C:\\Users\\x\\AppData\\Roaming\\npm\\codex.ps1',
- ].join('\r\n'),
- );
+ const shimPath = `${NPM_DIR}\\codex.cmd`;
+ existingFiles({
+ [`${NPM_DIR}\\node.exe`]: true,
+ [`${NPM_DIR}\\node_modules\\@openai\\codex\\bin\\codex.js`]: true,
+ [shimPath]: npmShim('node_modules\\@openai\\codex\\bin\\codex.js'),
+ });
+ callExecFile([`${NPM_DIR}\\codex`, shimPath, `${NPM_DIR}\\codex.ps1`].join('\r\n'));
callExecFile('codex 0.142.5');
const { detectValidatedCommand } = await importModule();
const status = await detectValidatedCommand('codex', { validateKeywords: ['codex'] });
expect(status.available).toBe(true);
- expect(status.path).toBe('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd');
+ expect(status.path).toBe(shimPath);
});
- it('preserves PATH order: earlier .cmd beats later .exe (Vite+ claude.exe case)', async () => {
+ it('preserves PATH order: a runnable earlier .cmd beats a later .exe (Vite+ claude.exe case)', async () => {
// `where claude` lists every match in PATH order. npm's .cmd shim is
// earlier; Vite+ ships a later standalone claude.exe. Preferring every
// .exe over every .cmd would pick Vite+ and break the real install.
- callExecFile(
- [
- 'C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd',
- 'C:\\Users\\hp\\.vite-plus\\bin\\claude.exe',
- ].join('\r\n'),
- );
+ const shimDir = 'C:\\Users\\hp\\AppData\\Roaming\\npm';
+ const shimPath = `${shimDir}\\claude.cmd`;
+ existingFiles({
+ [`${shimDir}\\node.exe`]: true,
+ [`${shimDir}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`]: true,
+ [shimPath]: npmShim('node_modules\\@anthropic-ai\\claude-code\\cli.js'),
+ });
+ callExecFile([shimPath, 'C:\\Users\\hp\\.vite-plus\\bin\\claude.exe'].join('\r\n'));
callExecFile('1.2.3 (Claude Code)');
const { detectValidatedCommand } = await importModule();
@@ -296,7 +360,175 @@ describe('resolveCliCommand', () => {
});
expect(status.available).toBe(true);
- expect(status.path).toBe('C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd');
+ expect(status.path).toBe(shimPath);
+ });
+
+ it('walks past a third-party shim it cannot unwrap to a later native .exe', async () => {
+ // OpenCodex hijacks %APPDATA%\npm\codex.cmd and forwards through a custom
+ // variable, so none of the shim patterns match. The WindowsApps codex.exe
+ // further down PATH runs fine β€” it just has to get a turn.
+ const hijackedShim = `${NPM_DIR}\\codex.cmd`;
+ const nativeExe =
+ 'C:\\Program Files\\WindowsApps\\OpenAI.Codex_1.0.0_x64\\app\\resources\\codex.exe';
+ existingFiles({
+ [hijackedShim]: [
+ '@echo off',
+ 'set "OCX_REAL_CODEX=%APPDATA%\\npm\\codex.opencodex-real.cmd"',
+ ':run_codex',
+ '"%OCX_REAL_CODEX%" %*',
+ ].join('\r\n'),
+ [nativeExe]: true,
+ });
+ callExecFile([`${NPM_DIR}\\codex`, hijackedShim, nativeExe].join('\r\n'));
+ callExecFile('codex-cli 0.146.0');
+
+ const { detectValidatedCommand } = await importModule();
+ const status = await detectValidatedCommand('codex', { validateKeywords: ['codex'] });
+
+ expect(status).toMatchObject({
+ available: true,
+ path: nativeExe,
+ version: 'codex-cli 0.146.0',
+ });
+ // The unrunnable shim is never spawned: `execFile` on a .cmd throws
+ // EINVAL since the CVE-2024-27980 fix, so trying it would only waste a
+ // process launch.
+ expect(execFileMock.mock.calls[1]![0]).toBe(nativeExe);
+ expect(execFileMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('probes an unwrappable shim through %ComSpec% when it is the only candidate', async () => {
+ const originalComSpec = process.env.ComSpec;
+ process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe';
+ const hijackedShim = `${NPM_DIR}\\qodercli.cmd`;
+ existingFiles({ [hijackedShim]: '@echo off\r\n"%OCX_REAL%" %*\r\n' });
+
+ try {
+ callExecFile(`${hijackedShim}\r\n`);
+ callExecFile('1.0.39');
+
+ const { detectValidatedCommand } = await importModule();
+ const status = await detectValidatedCommand('qodercli', {
+ validatePattern: /^v?\d+\.\d+\.\d+$/,
+ });
+
+ expect(status).toMatchObject({ available: true, path: hijackedShim, version: '1.0.39' });
+ expect(execFileMock.mock.calls[1]![0]).toBe('C:\\Windows\\System32\\cmd.exe');
+ expect(execFileMock.mock.calls[1]![1]).toEqual([
+ '/d',
+ '/s',
+ '/c',
+ `""${hijackedShim}" --version"`,
+ ]);
+ } finally {
+ if (originalComSpec === undefined) delete process.env.ComSpec;
+ else process.env.ComSpec = originalComSpec;
+ }
+ });
+
+ it('retries `where` against the registry PATH when the inherited snapshot is stale', async () => {
+ // A process started before the CLI installer ran keeps the PATH it
+ // inherited at creation time and never sees the new directory.
+ const originalPath = process.env.PATH;
+ const originalSystemRoot = process.env.SystemRoot;
+ const codexBin = 'C:\\Users\\x\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin';
+ process.env.PATH = 'C:\\Windows';
+ process.env.SystemRoot = 'C:\\Windows';
+
+ try {
+ existingFiles({ [`${codexBin}\\codex.exe`]: true });
+ callExecFileError(new Error('INFO: Could not find files')); // where codex
+ callExecFileError(new Error('ERROR: access denied')); // reg query HKLM
+ callExecFile(
+ `\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ ${codexBin};%SystemRoot%\\system32\r\n\r\n`,
+ );
+ callExecFile(`${codexBin}\\codex.exe\r\n`); // where codex (recovered PATH)
+ callExecFile('codex-cli 0.147.0');
+
+ const { detectValidatedCommand } = await importModule();
+ const status = await detectValidatedCommand('codex', { validateKeywords: ['codex'] });
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe(`${codexBin}\\codex.exe`);
+
+ const regArgs = execFileMock.mock.calls[1]![1] as string[];
+ expect(regArgs[1]).toContain('Session Manager\\Environment');
+ const retryEnv = (execFileMock.mock.calls[3]![2] as { env: NodeJS.ProcessEnv }).env;
+ expect(retryEnv.PATH).toContain(codexBin);
+ // REG_EXPAND_SZ values keep %VAR% references verbatim β€” `where` needs
+ // them expanded.
+ expect(retryEnv.PATH).toContain('C:\\Windows\\system32');
+ expect(retryEnv.PATH).not.toContain('%SystemRoot%');
+ // The recovered PATH is surfaced so spawn sites inherit it too.
+ expect(status.resolvedPathEnv).toBe(retryEnv.PATH);
+ } finally {
+ process.env.PATH = originalPath;
+ if (originalSystemRoot === undefined) delete process.env.SystemRoot;
+ else process.env.SystemRoot = originalSystemRoot;
+ }
+ });
+
+ it('re-reads the registry on a later scan instead of reusing the first answer', async () => {
+ // The user installs the CLI while the app is already open: the first
+ // scan sees neither the process PATH nor the registry, the rescan must
+ // see the registry entry the installer just wrote.
+ const originalPath = process.env.PATH;
+ const qoderBin = 'C:\\Users\\x\\AppData\\Local\\Programs\\Qoder\\bin';
+ process.env.PATH = 'C:\\Windows';
+
+ try {
+ existingFiles({ [`${qoderBin}\\qodercli.exe`]: true });
+ const { detectValidatedCommand } = await importModule();
+ const options = { validatePattern: /^v?\d+\.\d+\.\d+$/ };
+
+ callExecFileError(new Error('not found')); // where qodercli
+ callExecFileError(new Error('no value')); // reg query HKLM
+ callExecFileError(new Error('no value')); // reg query HKCU
+ expect((await detectValidatedCommand('qodercli', options)).available).toBe(false);
+
+ callExecFileError(new Error('not found')); // where qodercli
+ callExecFileError(new Error('no value')); // reg query HKLM
+ callExecFile(
+ `\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ ${qoderBin}\r\n`,
+ );
+ callExecFile(`${qoderBin}\\qodercli.exe\r\n`); // where qodercli (recovered PATH)
+ callExecFile('1.0.39');
+
+ const status = await detectValidatedCommand('qodercli', options);
+
+ expect(status).toMatchObject({ available: true, path: `${qoderBin}\\qodercli.exe` });
+ } finally {
+ process.env.PATH = originalPath;
+ }
+ });
+
+ it('falls back to the Windows Codex app bundled CLI when nothing is on PATH', async () => {
+ const originalLocalAppData = process.env.LOCALAPPDATA;
+ const originalPath = process.env.PATH;
+ const localAppData = 'C:\\Users\\x\\AppData\\Local';
+ process.env.LOCALAPPDATA = localAppData;
+ // Single-segment PATH: the recovered PATH then matches it exactly, so no
+ // extra `where` retry runs.
+ process.env.PATH = 'C:\\Windows';
+ const bundledCli = `${localAppData}\\Programs\\OpenAI\\Codex\\bin\\codex.exe`;
+
+ try {
+ existingFiles({ [bundledCli]: true });
+ callExecFileError(new Error('not found')); // where codex
+ callExecFileError(new Error('no registry')); // reg query HKLM
+ callExecFileError(new Error('no registry')); // reg query HKCU
+ callExecFile('codex-cli 0.147.0'); // the bundled CLI
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+ const status = await detectHeterogeneousCliCommand('codex', 'codex');
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe(bundledCli);
+ } finally {
+ process.env.PATH = originalPath;
+ if (originalLocalAppData === undefined) delete process.env.LOCALAPPDATA;
+ else process.env.LOCALAPPDATA = originalLocalAppData;
+ }
});
it('rejects a command containing shell metacharacters', async () => {
@@ -311,6 +543,44 @@ describe('resolveCliCommand', () => {
});
});
+ describe('detectValidatedCommand β€” noisy --version output', () => {
+ beforeEach(() => {
+ platformMock.mockReturnValue('darwin');
+ });
+
+ it('validates the version line even when the CLI appends an upgrade notice', async () => {
+ callExecFile('/Users/x/.local/bin/qodercli\n');
+ callExecFile('1.0.39\nA new version (1.0.42) is available. Run `qodercli upgrade`.');
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+ const status = await detectHeterogeneousCliCommand('qoder', 'qodercli');
+
+ expect(status).toMatchObject({ available: true, version: '1.0.39' });
+ });
+
+ it('validates the version line even when Node writes a warning to stderr', async () => {
+ callExecFile('/Users/x/.local/bin/opencode\n');
+ callExecFile('1.18.3\n', '(node:14512) ExperimentalWarning: WASI is an experimental feature');
+
+ const { detectHeterogeneousCliCommand } = await importModule();
+ const status = await detectHeterogeneousCliCommand('opencode', 'opencode');
+
+ expect(status).toMatchObject({ available: true, version: '1.18.3' });
+ });
+
+ it('still rejects output whose first line is not a version', async () => {
+ callExecFile('/Users/x/.local/bin/qodercli\n');
+ callExecFile('Usage: qodercli [command]\n1.0.39');
+
+ const { detectValidatedCommand } = await importModule();
+ const status = await detectValidatedCommand('qodercli', {
+ validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,
+ });
+
+ expect(status.available).toBe(false);
+ });
+ });
+
describe('resolveHeteroSpawnCommand', () => {
beforeEach(() => {
platformMock.mockReturnValue('darwin');
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
index 7711d88921c..37bbc705691 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
@@ -57,6 +57,7 @@ interface ResolvedCommand {
const isWindows = () => platform() === 'win32';
let shellPathPromise: Promise<string | undefined> | undefined;
+let registryPathPromise: Promise<string | undefined> | undefined;
// Reject shell syntax in user-supplied custom commands instead of treating it
// as part of a command name.
@@ -67,20 +68,43 @@ const WINDOWS_SHELL_METAS = /[&|;<>^`!"]/;
// `.ps1` and extensionless wrappers (npm sometimes drops a Unix shell script
// next to the `.cmd` shim) are deliberately excluded β€” we can't run them.
//
-// IMPORTANT: pick by PATH order (the order `where` returns), not by extension
-// rank. Preferring every `.exe` over every `.cmd` would skip an earlier npm
-// `claude.cmd` in favour of a later `claude.exe` from Vite+ (see #17376).
+// IMPORTANT: keep PATH order (the order `where` returns), don't rank by
+// extension. Preferring every `.exe` over every `.cmd` would skip an earlier
+// npm `claude.cmd` in favour of a later `claude.exe` from Vite+ (see #17376).
const WINDOWS_RUNNABLE_EXTS = ['.exe', '.cmd', '.bat'] as const;
+// Batch shims: runnable only after `resolveCliSpawnPlan` unwraps them into the
+// real target, or through `%ComSpec%`.
+const WINDOWS_SHIM_EXTS = ['.cmd', '.bat'] as const;
+
+// cmd.exe truncates command lines beyond this, well below the 32767 that
+// `CreateProcess` (and therefore the direct spawn path) allows.
+const WINDOWS_SHELL_MAX_COMMAND_LINE_LENGTH = 8191;
+
const isWindowsRunnablePath = (line: string): boolean => {
const lower = line.toLowerCase();
return WINDOWS_RUNNABLE_EXTS.some((ext) => lower.endsWith(ext));
};
-const pickWindowsRunnable = (lines: string[]): string | undefined => {
- return lines.find(isWindowsRunnablePath);
+const isWindowsShimPath = (line: string): boolean => {
+ const lower = line.toLowerCase();
+ return WINDOWS_SHIM_EXTS.some((ext) => lower.endsWith(ext));
};
+const pickWindowsRunnables = (lines: string[]): string[] => lines.filter(isWindowsRunnablePath);
+
+/**
+ * Whether the command already names a location instead of something to look up
+ * on PATH. Windows is judged by Windows rules β€” `path.isAbsolute` follows the
+ * host, so `C:\…` reads as a bare command name anywhere but Windows, which
+ * matters for the `lh hetero exec` CLI resolving a Windows path off-host and
+ * keeps this in step with `resolveCliSpawnPlan`.
+ */
+const isPathLikeCommand = (command: string): boolean =>
+ isWindows()
+ ? path.win32.isAbsolute(command) || /[\\/]/.test(command)
+ : path.isAbsolute(command) || command.includes(path.sep);
+
const getLoginShellPath = async (): Promise<string | undefined> => {
if (isWindows()) return undefined;
@@ -108,6 +132,70 @@ const getCachedLoginShellPath = async (): Promise<string | undefined> => {
return shellPathPromise;
};
+// Machine-wide then per-user PATH, the two halves Windows concatenates into a
+// process environment block.
+const WINDOWS_REGISTRY_PATH_KEYS = [
+ String.raw`HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment`,
+ String.raw`HKCU\Environment`,
+] as const;
+
+// `reg query <key> /v Path` prints the key, then `<name> <type> <value>`.
+const WINDOWS_REGISTRY_PATH_VALUE = /^[^\S\n]*Path[^\S\n]+REG_(?:EXPAND_)?SZ[^\S\n]+(\S.*)$/im;
+
+// Both PATH values are REG_EXPAND_SZ, so they store `%SystemRoot%`-style
+// references verbatim; `where` needs them expanded.
+const expandWindowsEnvRefs = (value: string): string =>
+ value.replaceAll(/%([^%]+)%/g, (reference, name: string) => {
+ const match = Object.entries(process.env).find(
+ ([key]) => key.toLowerCase() === name.toLowerCase(),
+ );
+ return match?.[1] ?? reference;
+ });
+
+const readWindowsRegistryPathValue = async (key: string): Promise<string | undefined> => {
+ try {
+ const { stdout } = await execFilePromise('reg', ['query', key, '/v', 'Path'], {
+ timeout: 3000,
+ windowsHide: true,
+ });
+ const value = stdout.match(WINDOWS_REGISTRY_PATH_VALUE)?.[1]?.trim();
+ return value ? expandWindowsEnvRefs(value) : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const readMergedWindowsRegistryPath = async (): Promise<string | undefined> => {
+ if (!isWindows()) return undefined;
+
+ const values = await Promise.all(WINDOWS_REGISTRY_PATH_KEYS.map(readWindowsRegistryPathValue));
+ return mergePathValues(...values);
+};
+
+/**
+ * PATH as the registry currently records it.
+ *
+ * A Windows process gets its environment block copied from its parent at
+ * creation time and never sees later edits, so a desktop app launched from an
+ * Explorer session that predates a CLI install can't find that CLI on PATH
+ * even though every new shell can. This is the Windows counterpart to the
+ * login-shell PATH re-read used on macOS/Linux.
+ *
+ * Concurrent callers share one lookup β€” a scan probes every agent at once β€”
+ * but the result is deliberately NOT kept afterwards. Reading the registry
+ * exists precisely to observe PATH edits this process missed, so holding the
+ * answer for the process lifetime would re-create the staleness it fixes: a
+ * CLI installed after the first failed scan would stay "not installed" until
+ * the app restarted. `reg query` is a couple of short-lived processes, and it
+ * only runs when `where` already came up empty.
+ */
+const getWindowsRegistryPath = async (): Promise<string | undefined> => {
+ registryPathPromise ??= readMergedWindowsRegistryPath().finally(() => {
+ registryPathPromise = undefined;
+ });
+ return registryPathPromise;
+};
+
const mergePathValues = (...values: Array<string | undefined>): string | undefined => {
const seen = new Set<string>();
const segments = values
@@ -144,21 +232,35 @@ const getCommandPathLines = async (
}
};
-const resolveCommandPath = async (command: string): Promise<ResolvedCommand | undefined> => {
+/**
+ * Every runnable location `which`/`where` reports for a command, in PATH order.
+ *
+ * Returning the whole list (rather than the first hit) matters on Windows: the
+ * first `.cmd` on PATH may be a third-party wrapper we can't unwrap, while a
+ * later entry is a native `.exe` that runs fine. Validating candidates in order
+ * makes detection immune to unknown shim shapes instead of chasing them with
+ * more regexes.
+ */
+const resolveCommandCandidates = async (command: string): Promise<ResolvedCommand[]> => {
const trimmedCommand = command.trim();
- if (!trimmedCommand) return;
+ if (!trimmedCommand) return [];
- if (path.isAbsolute(trimmedCommand) || trimmedCommand.includes(path.sep)) {
- return { path: trimmedCommand };
+ if (isPathLikeCommand(trimmedCommand)) {
+ return [{ path: trimmedCommand }];
}
const whichCommand = isWindows() ? 'where' : 'which';
let lines = await getCommandPathLines(whichCommand, trimmedCommand);
let lookupEnv: NodeJS.ProcessEnv | undefined;
- if (!lines && !isWindows()) {
- const shellPath = await getCachedLoginShellPath();
- const lookupPath = mergePathValues(shellPath, process.env.PATH);
+ if (!lines) {
+ // PATH recovery, per platform: macOS/Linux re-read the login shell's PATH,
+ // Windows re-reads the registry environment (the inherited block is a
+ // creation-time snapshot that never picks up a later install).
+ const recoveredPath = isWindows()
+ ? await getWindowsRegistryPath()
+ : await getCachedLoginShellPath();
+ const lookupPath = mergePathValues(recoveredPath, process.env.PATH);
if (lookupPath && lookupPath !== process.env.PATH) {
const fallbackEnv = {
@@ -170,22 +272,89 @@ const resolveCommandPath = async (command: string): Promise<ResolvedCommand | un
}
}
- if (!lines) return undefined;
+ if (!lines) return [];
- // Windows `where` lists every PATHEXT match (e.g. for `codex` npm ships
- // a Unix shell wrapper alongside `codex.cmd` and `codex.ps1`). Picking
- // the first line can land us on something we can't execute, so walk the
- // PATH-ordered list and take the first runnable extension.
+ // Windows `where` lists every PATHEXT match (e.g. for `codex` npm ships a
+ // Unix shell wrapper alongside `codex.cmd` and `codex.ps1`). Keep only the
+ // ones we can execute, still in PATH order.
if (isWindows()) {
- const runnablePath = pickWindowsRunnable(lines);
- return runnablePath ? { path: runnablePath } : undefined;
+ return pickWindowsRunnables(lines).map((runnablePath) => ({
+ env: lookupEnv,
+ path: runnablePath,
+ }));
}
- return { env: lookupEnv, path: lines[0] };
+ return [{ env: lookupEnv, path: lines[0] }];
+};
+
+const quoteWindowsShellToken = (token: string): string =>
+ /[\t ]/.test(token) ? `"${token}"` : token;
+
+/**
+ * `execFile` arguments that run `<executable> <args>` through `%ComSpec%`.
+ *
+ * DETECTION ONLY. The probe's arguments are the literal `--version` /`--help`
+ * flag, so nothing user-controlled reaches cmd.exe; routing the real agent
+ * launch through a shell would hand cmd.exe the prompt and conversation
+ * context and re-open CVE-2024-27980. Returns undefined when the command line
+ * can't be built safely.
+ */
+const buildWindowsShellProbe = (
+ executable: string,
+ args: string[],
+): { args: string[]; command: string } | undefined => {
+ const comSpec =
+ process.env.ComSpec ||
+ (process.env.SystemRoot
+ ? path.win32.join(process.env.SystemRoot, 'System32', 'cmd.exe')
+ : undefined);
+ if (!comSpec) return undefined;
+
+ const tokens = [executable, ...args];
+ if (tokens.some((token) => WINDOWS_SHELL_METAS.test(token))) return undefined;
+
+ // `cmd /s /c` strips one leading and one trailing quote from its argument,
+ // so wrap the already-quoted command line in an extra pair. The executable
+ // is always quoted β€” it's a `where` result and can hold spaces β€” while the
+ // flag is left bare.
+ const commandLine = `"${[`"${executable}"`, ...args.map(quoteWindowsShellToken)].join(' ')}"`;
+ const requiredLength = `${quoteWindowsShellToken(comSpec)} /d /s /c ${commandLine}`.length + 1;
+ if (requiredLength > WINDOWS_SHELL_MAX_COMMAND_LINE_LENGTH) return undefined;
+
+ return { args: ['/d', '/s', '/c', commandLine], command: comSpec };
};
-const execResolvedCommand = async (command: string, args: string[], env?: NodeJS.ProcessEnv) => {
+/**
+ * A `.cmd`/`.bat` candidate that `resolveCliSpawnPlan` couldn't unwrap into a
+ * real executable. Since the CVE-2024-27980 fix (Node 18.20.2 / 20.12.2)
+ * `execFile` refuses to spawn those without a shell, so running one directly is
+ * a guaranteed `EINVAL` β€” the caller retries it through `%ComSpec%` once every
+ * directly-runnable candidate has had its turn.
+ */
+const UNRESOLVED_SHIM = Symbol('unresolved-shim');
+
+const execProbe = async (
+ command: string,
+ args: string[],
+ env: NodeJS.ProcessEnv | undefined,
+ viaShell: boolean,
+) => {
+ if (viaShell) {
+ const shellProbe = buildWindowsShellProbe(command, args);
+ if (!shellProbe) return UNRESOLVED_SHIM;
+
+ return execFilePromise(shellProbe.command, shellProbe.args, {
+ env,
+ timeout: 5000,
+ windowsHide: true,
+ });
+ }
+
const spawnPlan = await resolveCliSpawnPlan(command, args);
+ if (isWindows() && spawnPlan.command === command && isWindowsShimPath(command)) {
+ return UNRESOLVED_SHIM;
+ }
+
return execFilePromise(spawnPlan.command, spawnPlan.args, {
env,
timeout: 5000,
@@ -211,19 +380,34 @@ export const detectValidatedCommand = async (
// Resolve via where/which BEFORE invoking. On Windows this is what discovers
// npm-installed shims like `claude.cmd` under %APPDATA%\npm β€” `execFile`
// alone won't apply PATHEXT and can't run .cmd files directly.
- const resolvedCommand = await resolveCommandPath(trimmedCommand);
- if (!resolvedCommand) return { available: false };
-
- const { env, path: resolvedPath } = resolvedCommand;
+ const candidates = await resolveCommandCandidates(trimmedCommand);
+ if (candidates.length === 0) return { available: false };
+
+ const validateCandidate = async (
+ { env, path: resolvedPath }: ResolvedCommand,
+ viaShell: boolean,
+ ): Promise<CliCommandStatus | typeof UNRESOLVED_SHIM> => {
+ let result;
+ try {
+ result = await execProbe(resolvedPath, [validateFlag], env, viaShell);
+ } catch {
+ return { available: false };
+ }
+ if (result === UNRESOLVED_SHIM) return UNRESOLVED_SHIM;
- try {
- const { stderr, stdout } = await execResolvedCommand(resolvedPath, [validateFlag], env);
- const output = `${stdout}\n${stderr}`.trim();
+ const output = `${result.stdout}\n${result.stderr}`.trim();
+ const firstLine = output.split(/\r?\n/)[0]!.trim();
const loweredOutput = output.toLowerCase();
const matchesKeyword = validateKeywords?.some((keyword) =>
loweredOutput.includes(keyword.toLowerCase()),
);
- const matchesPattern = validatePattern?.test(output);
+ // Anchored patterns describe a one-line version banner, so test the first
+ // line β€” the same line reported as `version` below. `output` also carries
+ // stderr plus whatever the CLI decided to print today (upgrade notices,
+ // auth warnings, Node's own `ExperimentalWarning`), and a `^…$` test
+ // against all of it flips a working CLI to "not installed" the moment any
+ // of that appears.
+ const matchesPattern = validatePattern?.test(firstLine);
if (!matchesKeyword && !matchesPattern) {
return { available: false };
@@ -232,16 +416,37 @@ export const detectValidatedCommand = async (
return {
available: true,
path: resolvedPath,
- // `env` is set only when resolution fell back to the login-shell PATH.
- // Surface that PATH so the spawn site can carry it into the child env β€”
- // otherwise a `#!/usr/bin/env node` shim resolved here can't find `node`
- // under the leaner inherited PATH (Finder-launched Electron).
+ // `env` is set only when resolution fell back to a recovered PATH (login
+ // shell on macOS/Linux, registry on Windows). Surface that PATH so the
+ // spawn site can carry it into the child env β€” otherwise a
+ // `#!/usr/bin/env node` shim resolved here can't find `node` under the
+ // leaner inherited PATH (Finder-launched Electron).
resolvedPathEnv: env?.PATH,
- version: output.split(/\r?\n/)[0],
+ version: firstLine,
};
- } catch {
- return { available: false };
+ };
+
+ // Pass 1: every candidate in PATH order, spawned directly. Stop at the first
+ // one whose `--version` output identifies it as the binary we're after.
+ const unresolvedShims: ResolvedCommand[] = [];
+ for (const candidate of candidates) {
+ const status = await validateCandidate(candidate, false);
+ if (status === UNRESOLVED_SHIM) {
+ unresolvedShims.push(candidate);
+ continue;
+ }
+ if (status.available) return status;
}
+
+ // Pass 2: shims no candidate ahead of them could replace. cmd.exe runs them
+ // whatever their shape, which is the only thing that reaches a CLI installed
+ // solely behind a wrapper we can't parse.
+ for (const candidate of unresolvedShims) {
+ const status = await validateCandidate(candidate, true);
+ if (status !== UNRESOLVED_SHIM && status.available) return status;
+ }
+
+ return { available: false };
};
const HETEROGENEOUS_CLI_AGENT_OPTIONS = {
@@ -305,6 +510,22 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[
];
}
case 'codex': {
+ // The Windows Codex desktop app (MSIX package `OpenAI.Codex`) drops its
+ // bundled CLI here and adds the directory to the registry User PATH β€”
+ // which an already-running process never sees. Same scenario the
+ // macOS app-bundle probe below covers: "installed the app, never
+ // installed the CLI".
+ if (platform() === 'win32') {
+ const localAppData = process.env.LOCALAPPDATA;
+ if (!localAppData) return [];
+
+ return [
+ path.win32.join(localAppData, 'Programs', 'OpenAI', 'Codex', 'bin', 'codex.exe'),
+ // winget installs expose a stable `Links` shim alongside the package.
+ path.win32.join(localAppData, 'Microsoft', 'WinGet', 'Links', 'codex.exe'),
+ ];
+ }
+
if (platform() !== 'darwin') return [];
// Codex.app was renamed to ChatGPT.app. Prefer the current bundle name,