π€― 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-agent): harden Windows CLI spawning (#18095)
AmAzing-b530ec7346f9
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 8ecf595dc8f..c29f4582a76 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -1084,6 +1084,7 @@ export default class HeterogeneousAgentCtr {let traceSession;let cwd: string;let initialCumulativeUsage: UsageData | undefined;+ let resolvedCliSpawnPlan;let spawnEnv: NodeJS.ProcessEnv;try {const driver = getHeterogeneousAgentDriver(session.agentType);@@ -1112,6 +1113,11 @@ export default class HeterogeneousAgentCtr {resumeSessionId: session.agentSessionId,});+ resolvedCliSpawnPlan = await resolveCliSpawnPlan(+ session.resolvedCommandPath ?? session.command,+ spawnPlan.args,+ );+// Fall back to the user's Desktop so the process never inherits// the Electron parent's cwd (which is `/` when launched from Finder).cwd = session.cwd || electronApp.getPath('desktop');@@ -1153,11 +1159,6 @@ export default class HeterogeneousAgentCtr {throw err;}const useStdin = spawnPlan.stdinPayload !== undefined;- const cliArgs = spawnPlan.args;- const resolvedCliSpawnPlan = await resolveCliSpawnPlan(- session.resolvedCommandPath ?? session.command,- cliArgs,- );logger.info('Spawning agent:',diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex f976f6443f0..7dc64bbd403 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -19,6 +19,8 @@ vi.mock('node:os', async () => {return { ...actual, platform: vi.fn(() => 'linux') };});+const platformMock = vi.mocked(os.platform);+vi.mock('node:fs', async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>();return { ...actual, existsSync: vi.fn(() => true) };@@ -263,6 +265,7 @@ describe('HeterogeneousAgentCtr', () => {codexAppServerConstructMock.mockReset();codexAppServerInterruptMock.mockReset();mockGetAllWindows.mockReset();+ platformMock.mockReturnValue('linux');delete process.env.LOBE_CLAUDE_CODE_SDK;delete process.env.LOBE_CODEX_APP_SERVER;});@@ -644,6 +647,45 @@ describe('HeterogeneousAgentCtr', () => {]);});+ it('cleans up the intervention when Windows command-line validation rejects before spawn', async () => {+ platformMock.mockReturnValue('win32');+ const operationId = 'op-oversized-windows-argv';+ const tmpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);+ await rm(tmpConfigPath, { force: true });++ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ binaryManager: {+ detect: vi.fn().mockResolvedValue({+ available: true,+ path: 'C:\\claude.exe',+ }),+ },+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'claude-code',+ args: ['a'.repeat(32_767)],+ command: 'claude',+ });++ await expect(+ ctr.sendPrompt({+ agentId: 'agent-1',+ operationId,+ prompt: 'hello',+ sessionId,+ topicId: 'topic-1',+ }),+ ).rejects.toThrow(/resolved Windows command line requires/);++ expect(spawnCalls).toHaveLength(0);+ expect((ctr as any).opIdToIntervention.has(operationId)).toBe(false);+ expect((ctr as any).opIdToBrowserBinding.has(operationId)).toBe(false);+ expect((ctr as any).builtinMcpServer.hasOperation(operationId)).toBe(false);+ await expect(access(tmpConfigPath)).rejects.toThrow();+ });+it('uses Claude SDK streaming lab instead of spawning claude -p', async () => {process.env.LOBE_CLAUDE_CODE_SDK = '1';const send = vi.fn();diff --git a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.tsindex 86bf6d09c5a..5ba2b9759c9 100644--- a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts@@ -36,13 +36,6 @@ const callExecFileError = (err: Error) => {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);-};describe('cliAgentBinaries', () => {beforeEach(() => {@@ -59,11 +52,11 @@ describe('cliAgentBinaries', () => {platformMock.mockReturnValue('win32');});- it('resolves `claude` to the .cmd path via `where`, then runs it through the shell', async () => {+ it('resolves `claude` to the .cmd path via `where` without constructing a shell command', async () => {// 1) `where claude` β resolves to the .cmd shim under %APPDATA%\npmcallExecFile('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd\r\n');- // 2) `cmd /c "...\\claude.cmd" --version` β keyword match- callExec('1.2.3 (Claude Code)');+ // 2) validate the resolved command without interpolating it into a shell string+ callExecFile('1.2.3 (Claude Code)');const { claudeCodeBinary } = await import('../cliAgentBinaries');const status = await claudeCodeBinary.detect();@@ -72,11 +65,12 @@ describe('cliAgentBinaries', () => {expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd');expect(status.version).toBe('1.2.3 (Claude Code)');- // The validation call must go via `exec` (shell), NOT `execFile`, so- // cmd.exe can actually interpret the .cmd shim.- expect(execMock).toHaveBeenCalledTimes(1);- const execCall = execMock.mock.calls[0]!;- expect(execCall[0]).toBe('"C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd" --version');+ 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']);});it('returns unavailable when `where` finds nothing', async () => {@@ -101,7 +95,7 @@ describe('cliAgentBinaries', () => {it('fails detection when version output does not match the expected keyword', async () => {callExecFile('C:\\some\\other\\claude.cmd\r\n');- callExec('this is some other binary v1.0');+ callExecFile('this is some other binary v1.0');const { claudeCodeBinary } = await import('../cliAgentBinaries');const status = await claudeCodeBinary.detect();@@ -120,16 +114,18 @@ describe('cliAgentBinaries', () => {'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.ps1',].join('\r\n'),);- callExec('codex 0.130.0');+ callExecFile('codex 0.130.0');const { codexBinary } = await import('../cliAgentBinaries');const status = await codexBinary.detect();expect(status.available).toBe(true);expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd');- expect(execMock.mock.calls[0]![0]).toBe(- '"C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd" --version',+ 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']);});it('prefers .exe over .cmd when both are present', async () => {@@ -154,17 +150,18 @@ describe('cliAgentBinaries', () => {'C:\\Users\\hp\\.vite-plus\\bin\\claude.exe',].join('\r\n'),);- callExec('1.2.3 (Claude Code)');+ callExecFile('1.2.3 (Claude Code)');const { claudeCodeBinary } = await import('../cliAgentBinaries');const status = await claudeCodeBinary.detect();expect(status.available).toBe(true);expect(status.path).toBe('C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd');- expect(execMock).toHaveBeenCalledTimes(1);- expect(execMock.mock.calls[0]![0]).toBe(- '"C:\\Users\\hp\\AppData\\Roaming\\npm\\claude.cmd" --version',+ 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']);});it('reports unavailable when `where` only returns unrunnable matches (.ps1 / extensionless)', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.tsindex 7aba3467098..c0f56bb6bf6 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts@@ -34,8 +34,7 @@ const readFileMock = vi.mocked(fsPromises.readFile);const callExecFile = (stdout: string) => {execFileMock.mockImplementationOnce(((...args: unknown[]) => {const callback = [...args].reverse().find((arg) => typeof arg === 'function') as- | ((error: Error | null, stdout: string) => void)- | undefined;+ ((error: Error | null, stdout: string) => void) | undefined;callback?.(null, stdout);return {} as childProcess.ChildProcess;}) as typeof childProcess.execFile);@@ -226,4 +225,30 @@ describe('cliSpawn', () => {command: shimPath,});});++ it('accepts the exact Windows command-line limit and rejects one UTF-16 unit more', async () => {+ platformMock.mockReturnValue('win32');+ const command = 'C:\\codex.exe';+ const { resolveCliSpawnPlan } = await import('./cliSpawn');+ const exactPrompt = 'a'.repeat(32_767 - command.length - 2);++ await expect(resolveCliSpawnPlan(command, [exactPrompt])).resolves.toEqual({+ args: [exactPrompt],+ command,+ });+ await expect(resolveCliSpawnPlan(command, [`${exactPrompt}a`])).rejects.toThrow(+ /Windows command line requires 32768 UTF-16 code units/,+ );+ });++ it('counts astral characters as two Windows UTF-16 code units', async () => {+ platformMock.mockReturnValue('win32');+ const command = 'C:\\codex.exe';+ const { resolveCliSpawnPlan } = await import('./cliSpawn');+ const promptPrefix = 'a'.repeat(32_767 - command.length - 3);++ await expect(resolveCliSpawnPlan(command, [`${promptPrefix}π`])).rejects.toThrow(+ /Windows command line requires 32768 UTF-16 code units/,+ );+ });});diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.tsindex 7ea64740cc1..bc7f1dc2754 100644--- a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts@@ -4,6 +4,7 @@ import { platform } from 'node:os';import path from 'node:path';const WINDOWS_EXE_EXT_PATTERN = /\.exe$/i;+const WINDOWS_MAX_COMMAND_LINE_LENGTH = 32_767;const WINDOWS_NODE_EXE_PATTERN = /(?:^|[\\/])node(?:\.exe)?$/i;export interface CliSpawnPlan {@@ -18,6 +19,41 @@ interface WindowsShimTarget {const isWindows = () => platform() === 'win32';+const quoteWindowsCommandLineArgument = (argument: string): string => {+ if (argument && !/[\t "]/u.test(argument)) return argument;++ let quoted = '"';+ let backslashCount = 0;++ for (const character of argument) {+ if (character === '\\') {+ backslashCount += 1;+ continue;+ }++ if (character === '"') {+ quoted += `${'\\'.repeat(backslashCount * 2 + 1)}"`;+ } else {+ quoted += `${'\\'.repeat(backslashCount)}${character}`;+ }+ backslashCount = 0;+ }++ return `${quoted}${'\\'.repeat(backslashCount * 2)}"`;+};++const assertWindowsCommandLineFits = ({ args, command }: CliSpawnPlan): void => {+ const commandLineLength = [command, ...args]+ .map(quoteWindowsCommandLineArgument)+ .join(' ').length;+ const requiredLength = commandLineLength + 1;+ if (requiredLength <= WINDOWS_MAX_COMMAND_LINE_LENGTH) return;++ throw new Error(+ `Cannot start CLI because the resolved Windows command line requires ${requiredLength} UTF-16 code units; Windows permits at most ${WINDOWS_MAX_COMMAND_LINE_LENGTH} including the terminator. Shorten the prompt or conversation context and retry.`,+ );+};+const isPathLikeCommand = (command: string) =>path.win32.isAbsolute(command) || path.posix.isAbsolute(command) || /[\\/]/.test(command);@@ -229,7 +265,10 @@ export const resolveCliSpawnPlan = async (? await inferWindowsNpmShimTarget(trimmedCommand): await resolveWindowsBareCommand(trimmedCommand);- if (!target) return { args, command };+ const spawnPlan = target+ ? { args: [...(target.argsPrefix ?? []), ...args], command: target.command }+ : { args, command };- return { args: [...(target.argsPrefix ?? []), ...args], command: target.command };+ assertWindowsCommandLineFits(spawnPlan);+ return spawnPlan;};diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex 5ebfc5e50d4..af6e44ed638 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -36,14 +36,6 @@ const callExecFileError = (err: Error) => {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', () => {@@ -255,18 +247,18 @@ describe('resolveCliCommand', () => {platformMock.mockReturnValue('win32');});- it('resolves `codex` to the .cmd shim via `where`, then runs it through the shell', async () => {+ it('resolves `codex` to the .cmd shim without constructing a shell command', async () => {callExecFile('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd\r\n');- callExec('codex 0.142.5');+ 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(execMock.mock.calls[0]![0]).toBe(- '"C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd" --version',- );+ expect(execFileMock.mock.calls[1]![0]).toBe('C:\\Users\\x\\AppData\\Roaming\\npm\\codex.cmd');+ expect(execFileMock.mock.calls[1]![1]).toEqual(['--version']);+ expect(execMock).not.toHaveBeenCalled();});it('prefers the .cmd shim when `where` returns multiple PATHEXT matches', async () => {@@ -277,7 +269,7 @@ describe('resolveCliCommand', () => {'C:\\Users\\x\\AppData\\Roaming\\npm\\codex.ps1',].join('\r\n'),);- callExec('codex 0.142.5');+ callExecFile('codex 0.142.5');const { detectValidatedCommand } = await importModule();const status = await detectValidatedCommand('codex', { validateKeywords: ['codex'] });@@ -296,7 +288,7 @@ describe('resolveCliCommand', () => {'C:\\Users\\hp\\.vite-plus\\bin\\claude.exe',].join('\r\n'),);- callExec('1.2.3 (Claude Code)');+ callExecFile('1.2.3 (Claude Code)');const { detectValidatedCommand } = await importModule();const status = await detectValidatedCommand('claude', {diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 28b65b73161..7711d88921c 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -1,10 +1,11 @@-import { exec, execFile } from 'node:child_process';+import { execFile } from 'node:child_process';import { homedir, platform } from 'node:os';import path from 'node:path';import { promisify } from 'node:util';import type { LocalHeterogeneousAgentType } from '../config';import { HETEROGENEOUS_AGENT_CONFIGS } from '../config';+import { resolveCliSpawnPlan } from './cliSpawn';/*** Shared resolver for external CLI-agent binaries (Amp / Claude Code / Codex / OpenCode / Pi / Qoder).@@ -21,7 +22,6 @@ import { HETEROGENEOUS_AGENT_CONFIGS } from '../config';*/const execFilePromise = promisify(execFile);-const execPromise = promisify(exec);export type HeterogeneousCliAgentType = LocalHeterogeneousAgentType;@@ -58,13 +58,12 @@ interface ResolvedCommand {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`.+// Reject shell syntax in user-supplied custom commands instead of treating it+// as part of a command name.const WINDOWS_SHELL_METAS = /[&|;<>^`!"]/;-// Extensions we can actually execute on Windows.-// `.exe` runs directly via `execFile`, `.cmd` / `.bat` runs via `cmd.exe`.+// Extensions eligible for execution on Windows. `.exe` runs directly, while+// supported `.cmd` / `.bat` shims are unwrapped by `resolveCliSpawnPlan`.// `.ps1` and extensionless wrappers (npm sometimes drops a Unix shell script// next to the `.cmd` shim) are deliberately excluded β we can't run them.//@@ -185,6 +184,15 @@ const resolveCommandPath = async (command: string): Promise<ResolvedCommand | unreturn { env: lookupEnv, path: lines[0] };};+const execResolvedCommand = async (command: string, args: string[], env?: NodeJS.ProcessEnv) => {+ const spawnPlan = await resolveCliSpawnPlan(command, args);+ return execFilePromise(spawnPlan.command, spawnPlan.args, {+ env,+ timeout: 5000,+ windowsHide: true,+ });+};+/*** Resolve a command via which/where, then confirm it's the binary we expect by* matching `--version` output against a keyword or output pattern (avoids@@ -209,18 +217,7 @@ export const detectValidatedCommand = async (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 { stderr, stdout } = await execResolvedCommand(resolvedPath, [validateFlag], env);const output = `${stdout}\n${stderr}`.trim();const loweredOutput = output.toLowerCase();const matchesKeyword = validateKeywords?.some((keyword) =>