π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): share the CLI agent binary resolver with headless runs (#16811)
Arvin Xu212b7ad40d00
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 76143ce9b67..428bd327a02 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -7,6 +7,7 @@ import path from 'node:path';import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import { AskUserMcpServer } from '@lobechat/heterogeneous-agents/askUser';+import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';import type {AgentContentBlock,AgentImageSource,@@ -813,11 +814,20 @@ const exec = async (options: ExecOptions): Promise<void> => {// Point CC at the lobe_cc AskUserQuestion MCP server we just mounted....(askMcpConfigPath ? ['--mcp-config', askMcpConfigPath] : []),];+ // Resolve the CLI binary once, up front, and reuse it for both the initial+ // run and the resume-retry. For the default bare command (`codex`/`claude`)+ // this finds the validated binary β including the Codex.app bundled CLI when+ // a broken `codex` shim shadows PATH β so sandbox/terminal runs no longer+ // ENOENT on a stale global install. Custom commands are used verbatim.+ const resolvedCommand = await resolveHeteroSpawnCommand(agentType, options.command);+ const commandEnv = resolvedCommand.pathEnv ? { PATH: resolvedCommand.pathEnv } : undefined;+const first = await runOneAgent({agentType: options.type,- command: options.command,+ command: resolvedCommand.command,cwd: options.cwd || process.cwd(),+ env: commandEnv,extraArgs,operationId,prompt: resolved.prompt,@@ -847,8 +857,9 @@ const exec = async (options: ExecOptions): Promise<void> => {result = await runOneAgent({agentType: options.type,- command: options.command,+ command: resolvedCommand.command,cwd: options.cwd || process.cwd(),+ env: commandEnv,extraArgs,operationId,prompt: resolved.prompt,diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex 1b6c122b159..181b6426e4f 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -1,17 +1,21 @@-import { exec, execFile } from 'node:child_process';-import { homedir, platform } from 'node:os';-import path from 'node:path';-import { promisify } from 'node:util';+import {+ detectHeterogeneousCliCommand,+ detectValidatedCommand,+} from '@lobechat/heterogeneous-agents/resolveCliCommand';import type { BinarySpec, BinaryStatus } from '@/core/infrastructure/BinaryManager';import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';-const execFilePromise = promisify(execFile);-const execPromise = promisify(exec);+// The command-resolution + validation logic (which/where lookup, login-shell+// PATH retry, well-known install fallbacks incl. the Codex.app bundled CLI,+// `--version` keyword validation) lives in the shared `@lobechat/heterogeneous-+// agents` package so the desktop manager path and the `lh hetero exec` CLI /+// sandbox path resolve binaries identically. This module only adapts it into+// the desktop `BinarySpec` shape.+export { detectHeterogeneousCliCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';-type HeterogeneousCliAgentType = 'claude-code' | 'codex';--interface ValidatedDetectorOptions {+interface ValidatedBinaryOptions {+ candidates: string[];description: string;name: string;priority: number;@@ -19,275 +23,12 @@ interface ValidatedDetectorOptions {validateKeywords: string[];}-interface ResolvedCommand {- env?: NodeJS.ProcessEnv;- path: string;-}--const isWindows = () => platform() === 'win32';-let shellPathPromise: Promise<string | undefined> | undefined;--// Reject anything that could break out of the `cmd /c "<path>" --version`-// shell line we build for Windows .cmd shims (see `detectValidatedCommand`).-// User-supplied custom commands flow through here via `detectHeterogeneousCliCommand`.-const WINDOWS_SHELL_METAS = /[&|;<>^`!"]/;--// Extensions we can actually execute on Windows, in preference order:-// `.exe` runs directly via `execFile`, `.cmd` / `.bat` runs via `cmd.exe`.-// `.ps1` and extensionless wrappers (npm sometimes drops a Unix shell script-// next to the `.cmd` shim) are deliberately excluded β we can't run them.-const WINDOWS_RUNNABLE_EXTS = ['.exe', '.cmd', '.bat'] as const;--const pickWindowsRunnable = (lines: string[]): string | undefined => {- for (const ext of WINDOWS_RUNNABLE_EXTS) {- const match = lines.find((line) => line.toLowerCase().endsWith(ext));- if (match) return match;- }- return undefined;-};--const getLoginShellPath = async (): Promise<string | undefined> => {- if (isWindows()) return undefined;-- const shell = process.env.SHELL;- if (!shell || !path.isAbsolute(shell)) return undefined;-- try {- const { stdout } = await execFilePromise(shell, ['-ilc', 'printf "%s" "$PATH"'], {- timeout: 3000,- windowsHide: true,- });-- return stdout- .split(/\r?\n/)- .map((line) => line.trim())- .reverse()- .find((line) => line.includes(path.delimiter));- } catch {- return undefined;- }-};--const getCachedLoginShellPath = async (): Promise<string | undefined> => {- shellPathPromise ??= getLoginShellPath();- return shellPathPromise;-};--const mergePathValues = (...values: Array<string | undefined>): string | undefined => {- const seen = new Set<string>();- const segments = values- .flatMap((value) => value?.split(path.delimiter) ?? [])- .map((segment) => segment.trim())- .filter((segment) => {- if (!segment || seen.has(segment)) return false;- seen.add(segment);- return true;- });-- return segments.length > 0 ? segments.join(path.delimiter) : undefined;-};--const getCommandPathLines = async (- whichCommand: 'where' | 'which',- command: string,- env?: NodeJS.ProcessEnv,-): Promise<string[] | undefined> => {- try {- const { stdout } = await execFilePromise(whichCommand, [command], {- env,- timeout: 3000,- windowsHide: true,- });- const lines = stdout- .split(/\r?\n/)- .map((line) => line.trim())- .filter(Boolean);-- return lines.length > 0 ? lines : undefined;- } catch {- return undefined;- }-};--const resolveCommandPath = async (command: string): Promise<ResolvedCommand | undefined> => {- const trimmedCommand = command.trim();- if (!trimmedCommand) return;-- if (path.isAbsolute(trimmedCommand) || trimmedCommand.includes(path.sep)) {- 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 (lookupPath && lookupPath !== process.env.PATH) {- const fallbackEnv = {- ...process.env,- PATH: lookupPath,- };- lines = await getCommandPathLines(whichCommand, trimmedCommand, fallbackEnv);- if (lines) lookupEnv = fallbackEnv;- }- }-- if (!lines) return undefined;-- // 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 prefer a- // runnable extension and bail otherwise.- if (isWindows()) {- const runnablePath = pickWindowsRunnable(lines);- return runnablePath ? { path: runnablePath } : undefined;- }-- return { env: lookupEnv, path: lines[0] };-};--const detectValidatedCommand = async (- command: string,- options: Pick<ValidatedDetectorOptions, 'validateFlag' | 'validateKeywords'>,-): Promise<BinaryStatus> => {- const trimmedCommand = command.trim();- if (!trimmedCommand) return { available: false };- if (isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand)) return { available: false };-- const { validateFlag = '--version', validateKeywords } = options;-- // 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;-- try {- const needsShell = isWindows() && /\.(?:cmd|bat)$/i.test(resolvedPath);- const { stderr, stdout } = needsShell- ? await execPromise(`"${resolvedPath}" ${validateFlag}`, {- env,- timeout: 5000,- windowsHide: true,- })- : await execFilePromise(resolvedPath, [validateFlag], {- env,- timeout: 5000,- windowsHide: true,- });- const output = `${stdout}\n${stderr}`.trim();- const loweredOutput = output.toLowerCase();-- if (!validateKeywords.some((keyword) => loweredOutput.includes(keyword.toLowerCase()))) {- return { available: false };- }-- 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).- resolvedPathEnv: env?.PATH,- version: output.split(/\r?\n/)[0],- };- } catch {- return { available: false };- }-};--const HETEROGENEOUS_CLI_AGENT_OPTIONS = {- 'claude-code': {- validateKeywords: ['claude code'],- },- 'codex': {- validateKeywords: ['codex'],- },-} as const satisfies Record<- HeterogeneousCliAgentType,- Pick<ValidatedDetectorOptions, 'validateKeywords'>->;--// The default (bare) command each agent type is shipped to run. The well-known-// fallback locations below hold *this* binary, so they may only be probed when-// the requested command is the default β never for a custom command.-const DEFAULT_COMMAND: Record<HeterogeneousCliAgentType, string> = {- 'claude-code': 'claude',- 'codex': 'codex',-};--// Well-known absolute install locations probed when a bare command isn't on-// PATH. This covers GUI-launched apps with a lean launchd PATH: Claude's-// official installer can put `claude` under ~/.local/bin, while the Codex-// desktop app bundles a functional CLI inside Codex.app without symlinking it.-const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[] => {- switch (agentType) {- case 'claude-code': {- if (platform() !== 'darwin' && platform() !== 'linux') return [];-- return [- path.join(homedir(), '.local', 'bin', 'claude'),- path.join(homedir(), '.bun', 'bin', 'claude'),- path.join(homedir(), '.npm-global', 'bin', 'claude'),- path.join(homedir(), 'Library', 'pnpm', 'claude'),- ];- }- case 'codex': {- if (platform() !== 'darwin') return [];-- const bundledCli = path.join('Codex.app', 'Contents', 'Resources', 'codex');- return [- path.join('/Applications', bundledCli),- path.join(homedir(), 'Applications', bundledCli),- ];- }- default: {- return [];- }- }-};--export const detectHeterogeneousCliCommand = async (- agentType: HeterogeneousCliAgentType,- command: string,-): Promise<BinaryStatus> => {- const validator = HETEROGENEOUS_CLI_AGENT_OPTIONS[agentType];- if (!validator) return { available: false };-- const status = await detectValidatedCommand(command, validator);- if (status.available) return status;-- // The default command missing from PATH may still live at a well-known install- // location (e.g. the Codex desktop app's bundled CLI). Only probe those for the- // default command: the well-known paths hold the *default* binary, so applying- // them to a custom command (e.g. `claude-beta`) would silently resolve it to- // stock `claude` instead of reporting the configured command as missing.- if (command.trim() === DEFAULT_COMMAND[agentType]) {- for (const candidate of getWellKnownCommandPaths(agentType)) {- const fallbackStatus = await detectValidatedCommand(candidate, validator);- if (fallbackStatus.available) return fallbackStatus;- }- }-- return status;-};-/*** Binary spec that resolves a command path via which/where, then validates* the binary by matching `--version` (or `--help`) output against a keyword* to avoid collisions with unrelated executables of the same name.*/-const defineValidatedBinary = (- options: ValidatedDetectorOptions & {- candidates: string[];- },-): BinarySpec => {+const defineValidatedBinary = (options: ValidatedBinaryOptions): BinarySpec => {const { candidates, description, name, priority, ...validation } = options;return {diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 84d87e2fb1d..a168b7a0bd7 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -8,6 +8,7 @@"./askUser": "./src/askUser/index.ts","./client": "./src/client/index.ts","./protocol": "./src/protocol/index.ts",+ "./resolveCliCommand": "./src/spawn/resolveCliCommand.ts","./spawn": "./src/spawn/index.ts"},"main": "./src/index.ts",diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 74a3b1113c5..50a004a7ee9 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -47,6 +47,12 @@ export {type NormalizeImageOptions,} from './input';export { JsonlStreamProcessor } from './jsonlProcessor';+// NOTE: `resolveCliCommand` is intentionally NOT re-exported here. It runs+// `promisify(execFile)` at module load, which throws under a partial+// `node:child_process` mock β and this barrel is widely imported (e.g. for+// `resolveCliSpawnPlan`), so pulling it in would break unrelated suites at+// import time. Import it from the dedicated `@lobechat/heterogeneous-agents/+// resolveCliCommand` subpath instead.export {CLAUDE_CODE_BASE_ARGS,CODEX_BYPASS_APPROVALS_AND_SANDBOX_ARG,diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsnew file mode 100644index 00000000000..7bbdfc6fbb3--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -0,0 +1,304 @@+import * as childProcess from 'node:child_process';+import * as os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Mocks must be set up before importing the module under test, because it+// captures `promisify(execFile)` / `promisify(exec)` at import time.+vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => actual.platform()) };+});++vi.mock('node:child_process', () => ({+ exec: vi.fn(),+ execFile: vi.fn(),+}));++const platformMock = vi.mocked(os.platform);+const execFileMock = vi.mocked(childProcess.execFile);+const execMock = vi.mocked(childProcess.exec);++const noErr = null;+const callExecFile = (stdout: string, stderr = '') => {+ execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {+ // promisify-wrapped: the callback is always the last positional arg.+ const callback = typeof opts === 'function' ? opts : cb;+ callback(noErr, { stdout, stderr });+ return {} as any;+ }) as any);+};+const callExecFileError = (err: Error) => {+ execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ callback(err, { stdout: '', stderr: '' });+ return {} as any;+ }) as any);+};+const callExec = (stdout: string, stderr = '') => {+ execMock.mockImplementationOnce(((cmd: string, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ callback(noErr, { stdout, stderr });+ return {} as any;+ }) as any);+};++const importModule = () => import('./resolveCliCommand');++describe('resolveCliCommand', () => {+ beforeEach(() => {+ execFileMock.mockReset();+ execMock.mockReset();+ });++ afterEach(() => {+ vi.resetModules();+ });++ describe('detectHeterogeneousCliCommand β macOS / Linux', () => {+ beforeEach(() => {+ platformMock.mockReturnValue('darwin');+ });++ it('resolves `codex` on PATH and validates it via execFile (no shell)', async () => {+ callExecFile('/usr/local/bin/codex\n');+ callExecFile('codex-cli 0.142.5');++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('codex', 'codex');++ expect(status.available).toBe(true);+ expect(status.path).toBe('/usr/local/bin/codex');+ expect(status.version).toBe('codex-cli 0.142.5');+ expect(status.resolvedPathEnv).toBeUndefined();+ expect(execMock).not.toHaveBeenCalled();+ });++ it('falls through a PATH `codex` that fails validation to the Codex.app bundled CLI', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ // Deterministic env: no SHELL β no login-shell lookup.+ process.env.PATH = '/usr/bin:/bin';+ delete process.env.SHELL;++ try {+ // `which codex` finds the (broken) global shim...+ callExecFile('/Users/x/Library/pnpm/codex\n');+ // ...but its `--version` errors (ENOENT-style broken wrapper).+ callExecFileError(new Error('spawn ENOENT'));+ // Fallback: the Codex.app bundled CLI validates.+ callExecFile('codex-cli 0.142.5');++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('codex', 'codex');++ expect(status.available).toBe(true);+ expect(status.path).toBe('/Applications/Codex.app/Contents/Resources/codex');+ expect(execFileMock.mock.calls[2]![0]).toBe(+ '/Applications/Codex.app/Contents/Resources/codex',+ );+ } finally {+ process.env.PATH = originalPath;+ if (originalShell === undefined) delete process.env.SHELL;+ else process.env.SHELL = originalShell;+ }+ });++ it('does NOT probe well-known locations for a custom command', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ delete process.env.SHELL;++ try {+ callExecFileError(new Error('not found')); // which codex-beta++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('codex', 'codex-beta');++ expect(status.available).toBe(false);+ // Only the custom command's own `which` runs β no Codex.app fallback.+ expect(execFileMock).toHaveBeenCalledTimes(1);+ expect(execFileMock.mock.calls[0]![0]).toBe('which');+ } finally {+ process.env.PATH = originalPath;+ if (originalShell === undefined) delete process.env.SHELL;+ else process.env.SHELL = originalShell;+ }+ });++ it('falls back to the login-shell PATH for a shim installed by shell setup', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';++ try {+ callExecFileError(new Error('not found')); // which codex (inherited PATH)+ callExecFile('/opt/homebrew/bin:/Users/x/.local/share/mise/shims:/usr/bin:/bin'); // login shell PATH+ callExecFile('/Users/x/.local/share/mise/shims/codex\n'); // which codex (login PATH)+ callExecFile('codex-cli 0.142.5');++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('codex', 'codex');++ expect(status.available).toBe(true);+ expect(status.path).toBe('/Users/x/.local/share/mise/shims/codex');+ expect(status.resolvedPathEnv).toBe(+ '/opt/homebrew/bin:/Users/x/.local/share/mise/shims:/usr/bin:/bin',+ );+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });+ });++ describe('detectValidatedCommand β Windows npm shims', () => {+ beforeEach(() => {+ platformMock.mockReturnValue('win32');+ });++ it('resolves `codex` to the .cmd shim via `where`, then runs it through the shell', async () => {+ callExecFile('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd\r\n');+ callExec('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(execMock.mock.calls[0]![0]).toBe(+ '"C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd" --version',+ );+ });++ 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'),+ );+ callExec('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');+ });++ it('rejects a command containing shell metacharacters', async () => {+ const { detectValidatedCommand } = await importModule();+ const status = await detectValidatedCommand('codex & calc.exe', {+ validateKeywords: ['codex'],+ });++ expect(status.available).toBe(false);+ expect(execFileMock).not.toHaveBeenCalled();+ expect(execMock).not.toHaveBeenCalled();+ });+ });++ describe('resolveHeteroSpawnCommand', () => {+ beforeEach(() => {+ platformMock.mockReturnValue('darwin');+ });++ it('resolves the default bare command to the validated absolute path', async () => {+ callExecFile('/usr/local/bin/codex\n');+ callExecFile('codex-cli 0.142.5');++ const { resolveHeteroSpawnCommand } = await importModule();+ const resolved = await resolveHeteroSpawnCommand('codex', undefined);++ expect(resolved.command).toBe('/usr/local/bin/codex');+ expect(resolved.pathEnv).toBeUndefined();+ });++ it('surfaces the login-shell PATH as pathEnv when resolution used it', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ process.env.PATH = '/usr/bin:/bin';+ process.env.SHELL = '/bin/zsh';++ try {+ callExecFileError(new Error('not found'));+ callExecFile('/opt/homebrew/bin:/usr/bin:/bin');+ callExecFile('/opt/homebrew/bin/codex\n');+ callExecFile('codex-cli 0.142.5');++ const { resolveHeteroSpawnCommand } = await importModule();+ const resolved = await resolveHeteroSpawnCommand('codex', 'codex');++ expect(resolved.command).toBe('/opt/homebrew/bin/codex');+ expect(resolved.pathEnv).toBe('/opt/homebrew/bin:/usr/bin:/bin');+ } finally {+ process.env.PATH = originalPath;+ process.env.SHELL = originalShell;+ }+ });++ it('falls back to the bare default command when nothing validates', async () => {+ const originalPath = process.env.PATH;+ const originalShell = process.env.SHELL;+ // Clean PATH (no dupes/empties) so the merged login-shell PATH equals it+ // β no second `which` attempt; and no SHELL β no login-shell lookup.+ process.env.PATH = '/usr/bin:/bin';+ delete process.env.SHELL;++ try {+ callExecFileError(new Error('not found')); // which codex+ callExecFileError(new Error('ENOENT')); // /Applications candidate+ callExecFileError(new Error('ENOENT')); // ~/Applications candidate++ const { resolveHeteroSpawnCommand } = await importModule();+ const resolved = await resolveHeteroSpawnCommand('codex', 'codex');++ expect(resolved.command).toBe('codex');+ expect(resolved.pathEnv).toBeUndefined();+ } finally {+ process.env.PATH = originalPath;+ if (originalShell === undefined) delete process.env.SHELL;+ else process.env.SHELL = originalShell;+ }+ });++ it('uses a custom command verbatim without any resolution attempt', async () => {+ const { resolveHeteroSpawnCommand } = await importModule();+ const resolved = await resolveHeteroSpawnCommand(+ 'claude-code',+ '/usr/local/bin/claude-wrapped',+ );++ expect(resolved.command).toBe('/usr/local/bin/claude-wrapped');+ expect(resolved.pathEnv).toBeUndefined();+ // Custom command = no probing at all.+ expect(execFileMock).not.toHaveBeenCalled();+ expect(execMock).not.toHaveBeenCalled();+ });++ it('never throws β a resolver failure degrades to the bare command', async () => {+ // execFile throws synchronously (not just callback error).+ execFileMock.mockImplementation((() => {+ throw new Error('boom');+ }) as any);++ const { resolveHeteroSpawnCommand } = await importModule();+ const resolved = await resolveHeteroSpawnCommand('codex', 'codex');++ expect(resolved.command).toBe('codex');+ });+ });++ it('reports unavailable for an unknown agent type', async () => {+ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('gemini' as any, 'gemini');+ expect(status.available).toBe(false);+ // Sanity: keep `path` unused-import-free.+ expect(path.sep).toBeTruthy();+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsnew file mode 100644index 00000000000..c5a24be8a3b--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -0,0 +1,361 @@+import { exec, execFile } from 'node:child_process';+import { homedir, platform } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++/**+ * Shared resolver for the external CLI-agent binaries (Claude Code / Codex).+ *+ * This is the single source of truth for "given a command name, where is the+ * runnable binary?". It's consumed by BOTH spawn sites:+ * - desktop main (`cliAgentBinaries` β `HeterogeneousAgentCtr`)+ * - the `lh hetero exec` CLI (sandbox + terminal), via `resolveHeteroSpawnCommand`+ *+ * Kept dependency-free (node built-ins only) so it runs unchanged in Electron+ * main, the CLI, the server, and cloud sandboxes. Every external call is+ * wrapped with a timeout + try/catch so a hostile or missing environment+ * degrades to "unavailable" instead of hanging or throwing.+ */++const execFilePromise = promisify(execFile);+const execPromise = promisify(exec);++export type HeterogeneousCliAgentType = 'claude-code' | 'codex';++/**+ * Resolution result. A structural subset of the desktop `BinaryManager`'s+ * `BinaryStatus`, so `cliAgentBinaries` can surface these values as a+ * `BinaryStatus` without adaptation.+ */+export interface CliCommandStatus {+ available: boolean;+ path?: string;+ /**+ * PATH used to resolve/validate the command, surfaced only when it differs+ * from the detector process's `process.env.PATH` (i.e. resolution fell back+ * to the login-shell PATH). A caller that spawns the resolved `path` must+ * carry this into the child's PATH, or a `#!/usr/bin/env node` shim resolved+ * here can't find `node` under the leaner inherited PATH.+ */+ resolvedPathEnv?: string;+ version?: string;+}++interface ValidateOptions {+ validateFlag?: string;+ validateKeywords: string[];+}++interface ResolvedCommand {+ env?: NodeJS.ProcessEnv;+ path: string;+}++const isWindows = () => platform() === 'win32';+let shellPathPromise: Promise<string | undefined> | undefined;++// Reject anything that could break out of the `cmd /c "<path>" --version`+// shell line we build for Windows .cmd shims (see `detectValidatedCommand`).+// User-supplied custom commands flow through here via `detectHeterogeneousCliCommand`.+const WINDOWS_SHELL_METAS = /[&|;<>^`!"]/;++// Extensions we can actually execute on Windows, in preference order:+// `.exe` runs directly via `execFile`, `.cmd` / `.bat` runs via `cmd.exe`.+// `.ps1` and extensionless wrappers (npm sometimes drops a Unix shell script+// next to the `.cmd` shim) are deliberately excluded β we can't run them.+const WINDOWS_RUNNABLE_EXTS = ['.exe', '.cmd', '.bat'] as const;++const pickWindowsRunnable = (lines: string[]): string | undefined => {+ for (const ext of WINDOWS_RUNNABLE_EXTS) {+ const match = lines.find((line) => line.toLowerCase().endsWith(ext));+ if (match) return match;+ }+ return undefined;+};++const getLoginShellPath = async (): Promise<string | undefined> => {+ if (isWindows()) return undefined;++ const shell = process.env.SHELL;+ if (!shell || !path.isAbsolute(shell)) return undefined;++ try {+ const { stdout } = await execFilePromise(shell, ['-ilc', 'printf "%s" "$PATH"'], {+ timeout: 3000,+ windowsHide: true,+ });++ return stdout+ .split(/\r?\n/)+ .map((line) => line.trim())+ .reverse()+ .find((line) => line.includes(path.delimiter));+ } catch {+ return undefined;+ }+};++const getCachedLoginShellPath = async (): Promise<string | undefined> => {+ shellPathPromise ??= getLoginShellPath();+ return shellPathPromise;+};++const mergePathValues = (...values: Array<string | undefined>): string | undefined => {+ const seen = new Set<string>();+ const segments = values+ .flatMap((value) => value?.split(path.delimiter) ?? [])+ .map((segment) => segment.trim())+ .filter((segment) => {+ if (!segment || seen.has(segment)) return false;+ seen.add(segment);+ return true;+ });++ return segments.length > 0 ? segments.join(path.delimiter) : undefined;+};++const getCommandPathLines = async (+ whichCommand: 'where' | 'which',+ command: string,+ env?: NodeJS.ProcessEnv,+): Promise<string[] | undefined> => {+ try {+ const { stdout } = await execFilePromise(whichCommand, [command], {+ env,+ timeout: 3000,+ windowsHide: true,+ });+ const lines = stdout+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);++ return lines.length > 0 ? lines : undefined;+ } catch {+ return undefined;+ }+};++const resolveCommandPath = async (command: string): Promise<ResolvedCommand | undefined> => {+ const trimmedCommand = command.trim();+ if (!trimmedCommand) return;++ if (path.isAbsolute(trimmedCommand) || trimmedCommand.includes(path.sep)) {+ 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 (lookupPath && lookupPath !== process.env.PATH) {+ const fallbackEnv = {+ ...process.env,+ PATH: lookupPath,+ };+ lines = await getCommandPathLines(whichCommand, trimmedCommand, fallbackEnv);+ if (lines) lookupEnv = fallbackEnv;+ }+ }++ if (!lines) return undefined;++ // 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 prefer a+ // runnable extension and bail otherwise.+ if (isWindows()) {+ const runnablePath = pickWindowsRunnable(lines);+ return runnablePath ? { path: runnablePath } : undefined;+ }++ return { env: lookupEnv, path: lines[0] };+};++/**+ * Resolve a command via which/where, then confirm it's the binary we expect by+ * matching `--version` output against a keyword (avoids collisions with an+ * unrelated executable of the same name).+ */+export const detectValidatedCommand = async (+ command: string,+ options: ValidateOptions,+): Promise<CliCommandStatus> => {+ const trimmedCommand = command.trim();+ if (!trimmedCommand) return { available: false };+ if (isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand)) return { available: false };++ const { validateFlag = '--version', validateKeywords } = options;++ // 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;++ try {+ const needsShell = isWindows() && /\.(?:cmd|bat)$/i.test(resolvedPath);+ const { stderr, stdout } = needsShell+ ? await execPromise(`"${resolvedPath}" ${validateFlag}`, {+ env,+ timeout: 5000,+ windowsHide: true,+ })+ : await execFilePromise(resolvedPath, [validateFlag], {+ env,+ timeout: 5000,+ windowsHide: true,+ });+ const output = `${stdout}\n${stderr}`.trim();+ const loweredOutput = output.toLowerCase();++ if (!validateKeywords.some((keyword) => loweredOutput.includes(keyword.toLowerCase()))) {+ return { available: false };+ }++ 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).+ resolvedPathEnv: env?.PATH,+ version: output.split(/\r?\n/)[0],+ };+ } catch {+ return { available: false };+ }+};++const HETEROGENEOUS_CLI_AGENT_OPTIONS = {+ 'claude-code': {+ validateKeywords: ['claude code'],+ },+ 'codex': {+ validateKeywords: ['codex'],+ },+} as const satisfies Record<HeterogeneousCliAgentType, ValidateOptions>;++// The default (bare) command each agent type is shipped to run. The well-known+// fallback locations below hold *this* binary, so they may only be probed when+// the requested command is the default β never for a custom command.+export const DEFAULT_HETERO_COMMAND: Record<HeterogeneousCliAgentType, string> = {+ 'claude-code': 'claude',+ 'codex': 'codex',+};++// Well-known absolute install locations probed when a bare command isn't on+// PATH. This covers GUI-launched apps with a lean launchd PATH: Claude's+// official installer can put `claude` under ~/.local/bin, while the Codex+// desktop app bundles a functional CLI inside Codex.app without symlinking it.+const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[] => {+ switch (agentType) {+ case 'claude-code': {+ if (platform() !== 'darwin' && platform() !== 'linux') return [];++ return [+ path.join(homedir(), '.local', 'bin', 'claude'),+ path.join(homedir(), '.bun', 'bin', 'claude'),+ path.join(homedir(), '.npm-global', 'bin', 'claude'),+ path.join(homedir(), 'Library', 'pnpm', 'claude'),+ ];+ }+ case 'codex': {+ if (platform() !== 'darwin') return [];++ const bundledCli = path.join('Codex.app', 'Contents', 'Resources', 'codex');+ return [+ path.join('/Applications', bundledCli),+ path.join(homedir(), 'Applications', bundledCli),+ ];+ }+ default: {+ return [];+ }+ }+};++export const detectHeterogeneousCliCommand = async (+ agentType: HeterogeneousCliAgentType,+ command: string,+): Promise<CliCommandStatus> => {+ const validator = HETEROGENEOUS_CLI_AGENT_OPTIONS[agentType];+ if (!validator) return { available: false };++ const status = await detectValidatedCommand(command, validator);+ if (status.available) return status;++ // The default command missing from PATH may still live at a well-known install+ // location (e.g. the Codex desktop app's bundled CLI). Only probe those for the+ // default command: the well-known paths hold the *default* binary, so applying+ // them to a custom command (e.g. `claude-beta`) would silently resolve it to+ // stock `claude` instead of reporting the configured command as missing.+ if (command.trim() === DEFAULT_HETERO_COMMAND[agentType]) {+ for (const candidate of getWellKnownCommandPaths(agentType)) {+ const fallbackStatus = await detectValidatedCommand(candidate, validator);+ if (fallbackStatus.available) return fallbackStatus;+ }+ }++ return status;+};++/**+ * Command + env a spawn site should use for an external CLI agent.+ */+export interface ResolvedHeteroCommand {+ /**+ * The command to spawn β an absolute, validated binary path when resolution+ * succeeded; otherwise the requested command left untouched (so the spawn+ * still trusts the ambient PATH, exactly as before).+ */+ command: string;+ /**+ * PATH to inject into the child env when resolution fell back to the+ * login-shell PATH; undefined when nothing extra is needed.+ */+ pathEnv?: string;+}++/**+ * Resolve the binary a spawn site (e.g. `lh hetero exec`) should launch for a+ * heterogeneous CLI agent. Best-effort and non-throwing: any failure degrades+ * to the requested command, preserving the prior PATH-trusting behavior.+ *+ * Resolution only kicks in for the DEFAULT bare command (`codex` / `claude`) β+ * the case that benefits from the well-known-path fallback (e.g. the Codex.app+ * bundled CLI when a broken `codex` shim shadows PATH). A custom command or an+ * explicit path is used verbatim, unchanged from before. This mirrors the+ * desktop controller, which resolves the default via the binary manager and+ * leaves custom commands to the caller.+ */+export const resolveHeteroSpawnCommand = async (+ agentType: HeterogeneousCliAgentType,+ command?: string,+): Promise<ResolvedHeteroCommand> => {+ const requested = command?.trim();+ const defaultCommand = DEFAULT_HETERO_COMMAND[agentType];++ // Non-default / custom / path-like command: use verbatim, no resolution.+ if (requested && requested !== defaultCommand) return { command: requested };++ if (!defaultCommand) return { command: requested ?? command ?? '' };++ try {+ const status = await detectHeterogeneousCliCommand(agentType, defaultCommand);+ if (status.available && status.path) {+ return { command: status.path, pathEnv: status.resolvedPathEnv };+ }+ } catch {+ // best-effort: fall through to the bare command below+ }++ return { command: defaultCommand };+};