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(desktop): resolve Windows npm CLI shims before spawning agents (#14772)

YuSaZh17506e30eecd
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index b27f8516884..f139b138252 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -24,11 +24,15 @@ import {
buildAgentInput,
materializeImageToPath,
normalizeImage,
+ resolveCliSpawnPlan,
} from '@lobechat/heterogeneous-agents/spawn';
import { app as electronApp, BrowserWindow } from 'electron';
import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
-import type { HeterogeneousAgentImageAttachment } from '@/modules/heterogeneousAgent/types';
+import type {
+ HeterogeneousAgentBuildPlan,
+ HeterogeneousAgentImageAttachment,
+} from '@/modules/heterogeneousAgent/types';
import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
import { detectHeterogeneousCliCommand } from '@/modules/toolDetectors';
import { createLogger } from '@/utils/logger';
@@ -868,169 +872,210 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
}
const useStdin = spawnPlan.stdinPayload !== undefined;
const cliArgs = spawnPlan.args;
+ const resolvedCliSpawnPlan = await resolveCliSpawnPlan(session.command, cliArgs);
- return new Promise<void>((resolve, reject) => {
- logger.info('Spawning agent:', session.command, cliArgs.join(' '), `(cwd: ${cwd})`);
-
- // `detached: true` on Unix puts the child in a new process group so we
- // can SIGINT/SIGKILL the whole tree (claude + any tool subprocesses)
- // via `process.kill(-pid, sig)` on cancel. Without this, SIGINT to just
- // the claude binary can leave bash/grep/etc. tool children running and
- // the CLI hung waiting on them. Windows has different semantics β€” use
- // taskkill /T /F there; no detached flag needed.
- // Forward the user's proxy settings to the CLI. The main-process undici
- // dispatcher doesn't reach child processes β€” they need env vars.
- const proxyEnv = buildProxyEnv(this.app.storeManager.get('networkProxy'));
-
- const proc = spawn(session.command, cliArgs, {
- cwd,
- detached: process.platform !== 'win32',
- env: { ...process.env, ...proxyEnv, ...session.env },
- stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
- });
+ logger.info(
+ 'Spawning agent:',
+ resolvedCliSpawnPlan.command,
+ resolvedCliSpawnPlan.args.join(' '),
+ `(cwd: ${cwd})`,
+ );
- // In stdin mode, write the prepared payload and close stdin.
- if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {
- void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);
- const stdin = proc.stdin as Writable;
- stdin.write(spawnPlan.stdinPayload, () => {
- stdin.end();
- });
- }
+ // `detached: true` on Unix puts the child in a new process group so we
+ // can SIGINT/SIGKILL the whole tree (claude + any tool subprocesses)
+ // via `process.kill(-pid, sig)` on cancel. Without this, SIGINT to just
+ // the claude binary can leave bash/grep/etc. tool children running and
+ // the CLI hung waiting on them. Windows has different semantics β€” use
+ // taskkill /T /F there; no detached flag needed.
+ // Forward the user's proxy settings to the CLI. The main-process undici
+ // dispatcher doesn't reach child processes β€” they need env vars.
+ const proxyEnv = buildProxyEnv(this.app.storeManager.get('networkProxy'));
+
+ const spawnOptions = {
+ cwd,
+ detached: process.platform !== 'win32',
+ env: { ...process.env, ...proxyEnv, ...session.env },
+ stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] as ['pipe' | 'ignore', 'pipe', 'pipe'],
+ };
- session.process = proc;
-
- // Producer-side conversion (V3 contract): JSONL framing + adapter +
- // toStreamEvent all run inside the shared pipeline, so renderer + future
- // server `heteroIngest` see the same `AgentStreamEvent` wire shape with
- // no per-consumer adapter. The pipeline auto-wires the Codex
- // file-change line-stat tracker when `agentType === 'codex'`, so this
- // controller stays agent-agnostic.
- const pipeline = new AgentStreamPipeline({
- agentType: session.agentType,
- operationId: params.operationId,
+ return new Promise<void>((resolve, reject) => {
+ const proc = spawn(resolvedCliSpawnPlan.command, resolvedCliSpawnPlan.args, spawnOptions);
+ this.handleSpawnedAgentProcess({
+ intervention,
+ params,
+ proc,
+ reject,
+ resolve,
+ session,
+ traceSession,
+ useStdin,
+ spawnPlan,
});
- let stdoutBroadcastQueue: Promise<void> = Promise.resolve();
-
- const broadcastPipelineBatch = (produce: () => ReturnType<AgentStreamPipeline['push']>) => {
- stdoutBroadcastQueue = stdoutBroadcastQueue
- .then(async () => {
- const events = await produce();
- // Adapter-extracted CC/Codex session id powers `--resume` on the
- // next prompt; surface it through the existing `getSessionInfo`
- // IPC by mirroring the freshest value onto the session record.
- if (pipeline.sessionId && pipeline.sessionId !== session.agentSessionId) {
- session.agentSessionId = pipeline.sessionId;
- }
- for (const event of events) {
- this.broadcast('heteroAgentEvent', {
- event,
- sessionId: session.sessionId,
- });
- }
- })
- .catch((error) => {
- logger.error('Failed to broadcast agent stream batch:', error);
- });
- };
+ });
+ }
- // Stream stdout events through the producer pipeline.
- const stdout = proc.stdout as Readable;
- stdout.on('data', (chunk: Buffer) => {
- void this.appendCliTraceFile(traceSession, 'stdout.jsonl', chunk);
- broadcastPipelineBatch(() => pipeline.push(chunk));
+ private handleSpawnedAgentProcess({
+ intervention,
+ params,
+ proc,
+ reject,
+ resolve,
+ session,
+ spawnPlan,
+ traceSession,
+ useStdin,
+ }: {
+ intervention?: Awaited<ReturnType<HeterogeneousAgentCtr['setupInterventionForOp']>>;
+ params: SendPromptParams;
+ proc: ChildProcess;
+ reject: (reason?: unknown) => void;
+ resolve: () => void;
+ session: AgentSession;
+ spawnPlan: HeterogeneousAgentBuildPlan;
+ traceSession: CliTraceSession | undefined;
+ useStdin: boolean;
+ }) {
+ proc.on('error', (err) => {
+ logger.error('Agent process error:', err);
+ void this.writeCliTraceJson(traceSession, 'process-error.json', {
+ message: err.message,
+ name: err.name,
});
- stdout.on('end', () => {
- broadcastPipelineBatch(() => pipeline.flush());
+ void this.flushCliTrace(traceSession);
+ const sessionError = this.getSessionErrorPayload(err, session);
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
});
+ reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));
+ });
- // Capture stderr
- const stderrChunks: string[] = [];
- const stderr = proc.stderr as Readable;
- stderr.on('data', (chunk: Buffer) => {
- void this.appendCliTraceFile(traceSession, 'stderr.log', chunk);
- stderrChunks.push(chunk.toString('utf8'));
+ // In stdin mode, write the prepared payload and close stdin.
+ if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {
+ void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);
+ const stdin = proc.stdin as Writable;
+ stdin.write(spawnPlan.stdinPayload, () => {
+ stdin.end();
});
+ }
- proc.on('error', (err) => {
- logger.error('Agent process error:', err);
- void this.writeCliTraceJson(traceSession, 'process-error.json', {
- message: err.message,
- name: err.name,
- });
- void this.flushCliTrace(traceSession);
- const sessionError = this.getSessionErrorPayload(err, session);
- this.broadcast('heteroAgentSessionError', {
- error: sessionError,
- sessionId: session.sessionId,
+ session.process = proc;
+
+ // Producer-side conversion (V3 contract): JSONL framing + adapter +
+ // toStreamEvent all run inside the shared pipeline, so renderer + future
+ // server `heteroIngest` see the same `AgentStreamEvent` wire shape with
+ // no per-consumer adapter. The pipeline auto-wires the Codex
+ // file-change line-stat tracker when `agentType === 'codex'`, so this
+ // controller stays agent-agnostic.
+ const pipeline = new AgentStreamPipeline({
+ agentType: session.agentType,
+ operationId: params.operationId,
+ });
+ let stdoutBroadcastQueue: Promise<void> = Promise.resolve();
+
+ const broadcastPipelineBatch = (produce: () => ReturnType<AgentStreamPipeline['push']>) => {
+ stdoutBroadcastQueue = stdoutBroadcastQueue
+ .then(async () => {
+ const events = await produce();
+ // Adapter-extracted CC/Codex session id powers `--resume` on the
+ // next prompt; surface it through the existing `getSessionInfo`
+ // IPC by mirroring the freshest value onto the session record.
+ if (pipeline.sessionId && pipeline.sessionId !== session.agentSessionId) {
+ session.agentSessionId = pipeline.sessionId;
+ }
+ for (const event of events) {
+ this.broadcast('heteroAgentEvent', {
+ event,
+ sessionId: session.sessionId,
+ });
+ }
+ })
+ .catch((error) => {
+ logger.error('Failed to broadcast agent stream batch:', error);
});
- reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));
- });
+ };
- proc.on('exit', (code, signal) => {
- // Node may emit `'exit'` BEFORE stdio finishes draining (documented:
- // child_process docs note "stdio streams might still be open" at exit
- // time). Wait for stdout to fully end/close so the `stdout.on('end')`
- // handler has scheduled `pipeline.flush()` onto `stdoutBroadcastQueue`,
- // THEN wait for the queue itself to settle. Without this two-step
- // gate, trailing flushed events (final synthesized tool_end /
- // tool_result) would race against β€” and lose to β€” the
- // `heteroAgentSessionComplete` broadcast, leaving renderer-side
- // persistence to finalize on incomplete state.
- const stdoutDrained = streamFinished(stdout, { writable: false }).catch(() => {
- /* end / close / error are all "done"; we still want to settle. */
- });
+ // Stream stdout events through the producer pipeline.
+ const stdout = proc.stdout as Readable;
+ stdout.on('data', (chunk: Buffer) => {
+ void this.appendCliTraceFile(traceSession, 'stdout.jsonl', chunk);
+ broadcastPipelineBatch(() => pipeline.push(chunk));
+ });
+ stdout.on('end', () => {
+ broadcastPipelineBatch(() => pipeline.flush());
+ });
+
+ // Capture stderr
+ const stderrChunks: string[] = [];
+ const stderr = proc.stderr as Readable;
+ stderr.on('data', (chunk: Buffer) => {
+ void this.appendCliTraceFile(traceSession, 'stderr.log', chunk);
+ stderrChunks.push(chunk.toString('utf8'));
+ });
+
+ proc.on('exit', (code, signal) => {
+ // Node may emit `'exit'` BEFORE stdio finishes draining (documented:
+ // child_process docs note "stdio streams might still be open" at exit
+ // time). Wait for stdout to fully end/close so the `stdout.on('end')`
+ // handler has scheduled `pipeline.flush()` onto `stdoutBroadcastQueue`,
+ // THEN wait for the queue itself to settle. Without this two-step
+ // gate, trailing flushed events (final synthesized tool_end /
+ // tool_result) would race against β€” and lose to β€” the
+ // `heteroAgentSessionComplete` broadcast, leaving renderer-side
+ // persistence to finalize on incomplete state.
+ const stdoutDrained = streamFinished(stdout, { writable: false }).catch(() => {
+ /* end / close / error are all "done"; we still want to settle. */
+ });
- void stdoutDrained
- .then(() => stdoutBroadcastQueue)
- .finally(async () => {
- // Tear down the AskUserQuestion bridge / temp `mcp.json` for this
- // op. Pending MCP handlers get a `session_ended` cancellation so
- // they return cleanly even if CC was killed mid-tool-call.
- if (intervention) {
- await intervention.cleanup().catch((err) => {
- logger.warn('AskUserQuestion cleanup error:', err);
- });
- }
-
- void this.writeCliTraceJson(traceSession, 'exit.json', {
- code,
- finishedAt: new Date().toISOString(),
- signal,
+ void stdoutDrained
+ .then(() => stdoutBroadcastQueue)
+ .finally(async () => {
+ // Tear down the AskUserQuestion bridge / temp `mcp.json` for this
+ // op. Pending MCP handlers get a `session_ended` cancellation so
+ // they return cleanly even if CC was killed mid-tool-call.
+ if (intervention) {
+ await intervention.cleanup().catch((err) => {
+ logger.warn('AskUserQuestion cleanup error:', err);
});
- await this.flushCliTrace(traceSession);
-
- logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });
- session.process = undefined;
-
- // If *we* killed it (cancel / stop / before-quit), treat the non-zero
- // exit as a clean shutdown β€” surfacing it as an error would make a
- // user-initiated cancel look like an agent failure, and an Electron
- // shutdown affecting OTHER running CC sessions would pollute their
- // topics with a misleading "Agent exited with code 143" message.
- if (session.cancelledByUs) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- resolve();
- return;
- }
-
- if (code === 0) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- resolve();
- } else {
- const stderrOutput = stderrChunks.join('').trim();
- const errorMsg = this.getExitErrorMessage(code, session, stderrOutput);
- const sessionError = this.getSessionErrorPayload(errorMsg, session);
- this.broadcast('heteroAgentSessionError', {
- error: sessionError,
- sessionId: session.sessionId,
- });
- reject(
- new Error(typeof sessionError === 'string' ? sessionError : sessionError.message),
- );
- }
+ }
+
+ void this.writeCliTraceJson(traceSession, 'exit.json', {
+ code,
+ finishedAt: new Date().toISOString(),
+ signal,
});
- });
+ await this.flushCliTrace(traceSession);
+
+ logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });
+ session.process = undefined;
+
+ // If *we* killed it (cancel / stop / before-quit), treat the non-zero
+ // exit as a clean shutdown β€” surfacing it as an error would make a
+ // user-initiated cancel look like an agent failure, and an Electron
+ // shutdown affecting OTHER running CC sessions would pollute their
+ // topics with a misleading "Agent exited with code 143" message.
+ if (session.cancelledByUs) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ resolve();
+ return;
+ }
+
+ if (code === 0) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ resolve();
+ } else {
+ const stderrOutput = stderrChunks.join('').trim();
+ const errorMsg = this.getExitErrorMessage(code, session, stderrOutput);
+ const sessionError = this.getSessionErrorPayload(errorMsg, session);
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ reject(
+ new Error(typeof sessionError === 'string' ? sessionError : sessionError.message),
+ );
+ }
+ });
});
}
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 330dc3e4830..4e3542da3c5 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -1,6 +1,6 @@
import { EventEmitter } from 'node:events';
import { access, mkdtemp, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
+import * as os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
@@ -9,6 +9,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';
+vi.mock('node:os', async () => {
+ const actual = await vi.importActual<typeof os>('node:os');
+ return { ...actual, platform: vi.fn(() => 'linux') };
+});
+
const FAKE_DESKTOP_PATH = '/Users/fake/Desktop';
const { mockGetAllWindows } = vi.hoisted(() => ({
@@ -111,7 +116,7 @@ describe('HeterogeneousAgentCtr', () => {
let appStoragePath: string;
beforeEach(async () => {
- appStoragePath = await mkdtemp(path.join(tmpdir(), 'lobehub-hetero-'));
+ appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-hetero-'));
});
afterEach(async () => {
@@ -817,7 +822,7 @@ describe('HeterogeneousAgentCtr', () => {
* it like a real pending intervention and tries to unlink it.
*/
const seedPendingIntervention = async (ctr: HeterogeneousAgentCtr, opId: string) => {
- const tmpConfigPath = path.join(tmpdir(), `lobe-cc-mcp-test-${opId}.json`);
+ const tmpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-test-${opId}.json`);
await writeFile(tmpConfigPath, '{"mcpServers":{}}');
const slot = {
bridge: {} as any,
diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts
new file mode 100644
index 00000000000..7aba3467098
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.test.ts
@@ -0,0 +1,229 @@
+import * as childProcess from 'node:child_process';
+import * as fsPromises from 'node:fs/promises';
+import * as os from 'node:os';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('node:os', async () => {
+ const actual = await vi.importActual<typeof os>('node:os');
+ return { ...actual, platform: vi.fn(() => actual.platform()) };
+});
+
+vi.mock('node:fs/promises', async () => {
+ const actual = await vi.importActual<typeof fsPromises>('node:fs/promises');
+ return {
+ ...actual,
+ access: vi.fn(),
+ readFile: vi.fn(),
+ };
+});
+
+vi.mock('node:child_process', async () => {
+ const actual = await vi.importActual<typeof childProcess>('node:child_process');
+ return {
+ ...actual,
+ execFile: vi.fn(),
+ };
+});
+
+const platformMock = vi.mocked(os.platform);
+const execFileMock = vi.mocked(childProcess.execFile);
+const accessMock = vi.mocked(fsPromises.access);
+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;
+ callback?.(null, stdout);
+ return {} as childProcess.ChildProcess;
+ }) as typeof childProcess.execFile);
+};
+
+const existingPaths = (...paths: string[]) => {
+ const normalizedPaths = new Set(paths.map((filePath) => filePath.toLowerCase()));
+ accessMock.mockImplementation(async (filePath) => {
+ if (normalizedPaths.has(String(filePath).toLowerCase())) return;
+ throw new Error(`missing: ${String(filePath)}`);
+ });
+};
+
+describe('cliSpawn', () => {
+ beforeEach(() => {
+ platformMock.mockReturnValue('linux');
+ execFileMock.mockReset();
+ accessMock.mockReset();
+ readFileMock.mockReset();
+ });
+
+ it('keeps non-Windows commands unchanged', async () => {
+ platformMock.mockReturnValue('darwin');
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+
+ await expect(resolveCliSpawnPlan('claude', ['--version'])).resolves.toEqual({
+ args: ['--version'],
+ command: 'claude',
+ });
+ expect(execFileMock).not.toHaveBeenCalled();
+ });
+
+ it('prefers a Windows executable returned by where', async () => {
+ platformMock.mockReturnValue('win32');
+ callExecFile(
+ ['C:\\Users\\Hanam\\AppData\\Roaming\\npm\\gemini.cmd', 'C:\\Tools\\gemini.exe'].join('\r\n'),
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan('gemini', ['--version'])).resolves.toEqual({
+ args: ['--version'],
+ command: 'C:\\Tools\\gemini.exe',
+ });
+ expect(readFileMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves Windows npm shell shim to a package executable', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude';
+ const exePath =
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe';
+ callExecFile([shimPath, `${shimPath}.cmd`].join('\r\n'));
+ existingPaths(shimPath, exePath);
+ readFileMock.mockResolvedValue(
+ 'exec "$basedir/node_modules/@anthropic-ai/claude-code/bin/claude.exe" "$@"\n',
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan('claude', ['--version'])).resolves.toEqual({
+ args: ['--version'],
+ command: exePath,
+ });
+ });
+
+ it('resolves Windows npm .cmd shim to a package executable when configured directly', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd';
+ const exePath =
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe';
+ existingPaths(shimPath, exePath);
+ readFileMock.mockResolvedValue(
+ '@ECHO off\r\n"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe" %*\r\n',
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan(shimPath, ['--version'])).resolves.toEqual({
+ args: ['--version'],
+ command: exePath,
+ });
+ expect(execFileMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves a .cmd npm shim that invokes node.exe plus a JS bin', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\gemini.cmd';
+ const nodePath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node.exe';
+ const scriptPath =
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\@google\\gemini-cli\\dist\\index.js';
+ existingPaths(shimPath, nodePath, scriptPath);
+ readFileMock.mockResolvedValue(
+ '@ECHO off\r\n"%dp0%\\node.exe" "%dp0%\\node_modules\\@google\\gemini-cli\\dist\\index.js" %*\r\n',
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan(shimPath, ['--version'])).resolves.toEqual({
+ args: [scriptPath, '--version'],
+ command: nodePath,
+ });
+ });
+
+ it('resolves an extensionless npm shell shim that invokes node.exe plus a JS bin', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\kimi';
+ const nodePath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node.exe';
+ const scriptPath =
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\kimi-cli\\bin\\kimi.js';
+ callExecFile([shimPath, `${shimPath}.cmd`].join('\r\n'));
+ existingPaths(shimPath, nodePath, scriptPath);
+ readFileMock.mockResolvedValue(
+ 'exec "$basedir/node.exe" "$basedir/node_modules/kimi-cli/bin/kimi.js" "$@"\n',
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan('kimi', ['chat', '--json'])).resolves.toEqual({
+ args: [scriptPath, 'chat', '--json'],
+ command: nodePath,
+ });
+ });
+
+ it('uses the node executable from PATH when a shim invokes bare node plus a JS bin', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\example-cli.cmd';
+ const nodePath = 'C:\\Program Files\\nodejs\\node.exe';
+ const scriptPath =
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\example-cli\\bin\\cli.js';
+ existingPaths(shimPath, scriptPath);
+ callExecFile(`${nodePath}\r\n`);
+ readFileMock.mockResolvedValue('node "%dp0%\\node_modules\\example-cli\\bin\\cli.js" %*\r\n');
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan(shimPath, ['--help'])).resolves.toEqual({
+ args: [scriptPath, '--help'],
+ command: nodePath,
+ });
+ });
+
+ it('resolves the npm generated %_prog% .cmd shim form used by Codex and Gemini', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd';
+ const nodePath = 'C:\\Program Files\\nodejs\\node.exe';
+ const scriptPath =
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node_modules\\@openai\\codex\\bin\\codex.js';
+ existingPaths(shimPath, scriptPath);
+ callExecFile(`${nodePath}\r\n`);
+ readFileMock.mockResolvedValue(
+ [
+ '@ECHO off',
+ 'IF EXIST "%dp0%\\node.exe" (',
+ ' SET "_prog=%dp0%\\node.exe"',
+ ') ELSE (',
+ ' SET "_prog=node"',
+ ')',
+ 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js" %*',
+ ].join('\r\n'),
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan(shimPath, ['--version'])).resolves.toEqual({
+ args: [scriptPath, '--version'],
+ command: nodePath,
+ });
+ });
+
+ it('falls back to the original command and args when a JS bin target is missing', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\gemini.cmd';
+ existingPaths(shimPath, 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\node.exe');
+ readFileMock.mockResolvedValue(
+ '"%dp0%\\node.exe" "%dp0%\\node_modules\\@google\\gemini-cli\\dist\\index.js" %*\r\n',
+ );
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan(shimPath, ['--version'])).resolves.toEqual({
+ args: ['--version'],
+ command: shimPath,
+ });
+ });
+
+ it('falls back to the original command and args when shim content is unsupported', async () => {
+ platformMock.mockReturnValue('win32');
+ const shimPath = 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\unknown.cmd';
+ existingPaths(shimPath);
+ readFileMock.mockResolvedValue('@ECHO off\r\nset SOME_VAR=1\r\n');
+
+ const { resolveCliSpawnPlan } = await import('./cliSpawn');
+ await expect(resolveCliSpawnPlan(shimPath, ['--version'])).resolves.toEqual({
+ args: ['--version'],
+ command: shimPath,
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/cliSpawn.ts b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts
new file mode 100644
index 00000000000..7ea64740cc1
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/cliSpawn.ts
@@ -0,0 +1,235 @@
+import { execFile } from 'node:child_process';
+import { access, readFile } from 'node:fs/promises';
+import { platform } from 'node:os';
+import path from 'node:path';
+
+const WINDOWS_EXE_EXT_PATTERN = /\.exe$/i;
+const WINDOWS_NODE_EXE_PATTERN = /(?:^|[\\/])node(?:\.exe)?$/i;
+
+export interface CliSpawnPlan {
+ args: string[];
+ command: string;
+}
+
+interface WindowsShimTarget {
+ argsPrefix?: string[];
+ command: string;
+}
+
+const isWindows = () => platform() === 'win32';
+
+const isPathLikeCommand = (command: string) =>
+ path.win32.isAbsolute(command) || path.posix.isAbsolute(command) || /[\\/]/.test(command);
+
+const fileExists = async (filePath: string): Promise<boolean> => {
+ try {
+ await access(filePath);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const execFileString = async (command: string, args: string[]): Promise<string> =>
+ new Promise((resolve, reject) => {
+ execFile(
+ command,
+ args,
+ { timeout: 3000, windowsHide: true },
+ (error: Error | null, stdout: string) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve(stdout.toString());
+ },
+ );
+ });
+
+const pickWindowsExecutable = (candidates: string[]): string | undefined =>
+ candidates.find((candidate) => WINDOWS_EXE_EXT_PATTERN.test(candidate));
+
+const pickWindowsNodeExecutable = (candidates: string[]): string | undefined =>
+ candidates.find(
+ (candidate) =>
+ WINDOWS_EXE_EXT_PATTERN.test(candidate) && WINDOWS_NODE_EXE_PATTERN.test(candidate),
+ );
+
+const joinShimRelativePath = (shimPath: string, relativePath: string) =>
+ path.win32.join(
+ path.win32.dirname(shimPath),
+ ...relativePath.replaceAll('\\', '/').split('/').filter(Boolean),
+ );
+
+const resolveShimPathToken = (shimPath: string, token: string): string | undefined => {
+ const trimmedToken = token.trim().replaceAll(/^['"]|['"]$/g, '');
+ const lowerToken = trimmedToken.toLowerCase();
+
+ if (lowerToken.startsWith('$basedir')) {
+ return joinShimRelativePath(
+ shimPath,
+ trimmedToken.slice('$basedir'.length).replace(/^[\\/]/, ''),
+ );
+ }
+
+ if (lowerToken.startsWith('%dp0%')) {
+ return joinShimRelativePath(shimPath, trimmedToken.slice('%dp0%'.length).replace(/^[\\/]/, ''));
+ }
+
+ if (path.win32.isAbsolute(trimmedToken)) return trimmedToken;
+
+ if (/[\\/]/.test(trimmedToken)) return joinShimRelativePath(shimPath, trimmedToken);
+};
+
+const getExistingShimPathToken = async (
+ shimPath: string,
+ token: string,
+): Promise<string | undefined> => {
+ const resolvedPath = resolveShimPathToken(shimPath, token);
+ if (!resolvedPath) return;
+ return (await fileExists(resolvedPath)) ? resolvedPath : undefined;
+};
+
+const resolveWindowsNodeCommand = async (shimPath: string): Promise<string | undefined> => {
+ const localNodePath = path.win32.join(path.win32.dirname(shimPath), 'node.exe');
+ if (await fileExists(localNodePath)) return localNodePath;
+
+ try {
+ const stdout = await execFileString('where', ['node']);
+ const candidates = stdout
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+ return pickWindowsNodeExecutable(candidates);
+ } catch {
+ return;
+ }
+};
+
+const getNodeCommand = async (shimPath: string, token: string): Promise<string | undefined> => {
+ const trimmedToken = token.trim().replaceAll(/^['"]|['"]$/g, '');
+ if (/^node(?:\.exe)?$/i.test(trimmedToken) || /^%_prog%$/i.test(trimmedToken)) {
+ return resolveWindowsNodeCommand(shimPath);
+ }
+
+ const resolvedPath = await getExistingShimPathToken(shimPath, trimmedToken);
+ if (!resolvedPath) return;
+
+ return WINDOWS_NODE_EXE_PATTERN.test(resolvedPath) ? resolvedPath : undefined;
+};
+
+const getNodeScriptTarget = async (
+ shimPath: string,
+ nodeToken: string,
+ scriptToken: string,
+): Promise<WindowsShimTarget | undefined> => {
+ const command = await getNodeCommand(shimPath, nodeToken);
+ if (!command) return;
+
+ const scriptPath = await getExistingShimPathToken(shimPath, scriptToken);
+ if (!scriptPath) return;
+
+ return { argsPrefix: [scriptPath], command };
+};
+
+const inferWindowsNodeScriptFromShim = async (
+ shimPath: string,
+ source: string,
+): Promise<WindowsShimTarget | undefined> => {
+ const patterns: Array<RegExp | [RegExp, string]> = [
+ /exec\s+"(\$basedir[^"]*node(?:\.exe)?)"\s+"([^"]+)"/i,
+ /exec\s+(node(?:\.exe)?)\s+"([^"]+)"/i,
+ /"(%dp0%[^"]*node(?:\.exe)?)"\s+"([^"]+)"/i,
+ /"(%_prog%)"\s+"([^"]+)"/i,
+ [/(?:^|\r?\n)\s*(node(?:\.exe)?)\s+"([^"]+)"/i, 'node'],
+ ];
+
+ for (const pattern of patterns) {
+ const regex = Array.isArray(pattern) ? pattern[0] : pattern;
+ const match = source.match(regex);
+ if (!match) continue;
+
+ const nodeToken = Array.isArray(pattern) ? pattern[1] : match[1];
+ const scriptToken = Array.isArray(pattern) ? match[2] : match[2];
+ if (!nodeToken || !scriptToken) continue;
+
+ const target = await getNodeScriptTarget(shimPath, nodeToken, scriptToken);
+ if (target) return target;
+ }
+};
+
+const inferWindowsExecutableFromShim = async (
+ shimPath: string,
+ source: string,
+): Promise<WindowsShimTarget | undefined> => {
+ const matches = [
+ ...source.matchAll(/\$basedir[\\/]([^"\s]+?\.exe)/gi),
+ ...source.matchAll(/%dp0%\\([^"\r\n]+?\.exe)/gi),
+ ];
+
+ for (const match of matches) {
+ const relativePath = match[1]?.replaceAll('\\', '/');
+ if (!relativePath || WINDOWS_NODE_EXE_PATTERN.test(relativePath)) continue;
+
+ const command = joinShimRelativePath(shimPath, relativePath);
+ if (await fileExists(command)) return { command };
+ }
+};
+
+const inferWindowsNpmShimTarget = async (
+ shimPath: string,
+): Promise<WindowsShimTarget | undefined> => {
+ if (WINDOWS_EXE_EXT_PATTERN.test(shimPath)) return { command: shimPath };
+ if (!(await fileExists(shimPath))) return;
+
+ try {
+ const source = await readFile(shimPath, 'utf8');
+ return (
+ (await inferWindowsNodeScriptFromShim(shimPath, source)) ??
+ (await inferWindowsExecutableFromShim(shimPath, source))
+ );
+ } catch {
+ return;
+ }
+};
+
+const resolveWindowsBareCommand = async (
+ command: string,
+): Promise<WindowsShimTarget | undefined> => {
+ try {
+ const stdout = await execFileString('where', [command]);
+ const candidates = stdout
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean);
+
+ const executable = pickWindowsExecutable(candidates);
+ if (executable) return { command: executable };
+
+ for (const candidate of candidates) {
+ const target = await inferWindowsNpmShimTarget(candidate);
+ if (target) return target;
+ }
+
+ return undefined;
+ } catch {
+ return;
+ }
+};
+
+export const resolveCliSpawnPlan = async (
+ command: string,
+ args: string[],
+): Promise<CliSpawnPlan> => {
+ const trimmedCommand = command.trim();
+ if (!isWindows() || !trimmedCommand) return { args, command };
+
+ const target = isPathLikeCommand(trimmedCommand)
+ ? await inferWindowsNpmShimTarget(trimmedCommand)
+ : await resolveWindowsBareCommand(trimmedCommand);
+
+ if (!target) return { args, command };
+
+ return { args: [...(target.argsPrefix ?? []), ...args], command: target.command };
+};
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 28af4013b54..67dc37d78fd 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -13,6 +13,7 @@
* that producers have no business pulling in).
*/
export { AgentStreamPipeline, type AgentStreamPipelineOptions } from './agentStreamPipeline';
+export { type CliSpawnPlan, resolveCliSpawnPlan } from './cliSpawn';
export { CodexFileChangeTracker } from './codexFileChangeTracker';
export {
type AgentContentBlock,
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
index 41833ed2de2..b39afdad876 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
@@ -1,4 +1,6 @@
+import * as childProcess from 'node:child_process';
import { EventEmitter } from 'node:events';
+import * as os from 'node:os';
import { PassThrough } from 'node:stream';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -6,17 +8,36 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];
let nextFakeProc: any = null;
-vi.mock('node:child_process', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
+const platformMock = vi.mocked(os.platform);
+const execFileMock = vi.mocked(childProcess.execFile);
+
+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;
+ callback?.(null, stdout);
+ return {} as childProcess.ChildProcess;
+ }) as typeof childProcess.execFile);
+};
+
+vi.mock('node:child_process', async () => {
+ const actual = await vi.importActual<typeof childProcess>('node:child_process');
return {
...actual,
- spawn: (command: string, args: string[], options: any) => {
+ execFile: vi.fn(),
+ spawn: vi.fn((command: string, args: string[], options: any) => {
spawnCalls.push({ args, command, options });
return nextFakeProc;
- },
+ }),
};
});
+vi.mock('node:os', async () => {
+ const actual = await vi.importActual<typeof os>('node:os');
+ return { ...actual, platform: vi.fn(() => 'linux') };
+});
+
const createFakeProc = ({
exitCode = 0,
stdoutChunks = [] as string[],
@@ -78,6 +99,8 @@ describe('spawnAgent', () => {
beforeEach(() => {
spawnCalls.length = 0;
nextFakeProc = null;
+ platformMock.mockReturnValue('linux');
+ execFileMock.mockReset();
});
afterEach(() => {
@@ -169,6 +192,19 @@ describe('spawnAgent', () => {
expect(args).toContain('--full-auto');
});
+ it('spawns the Windows executable resolved by the shared CLI spawn plan', async () => {
+ platformMock.mockReturnValue('win32');
+ callExecFile('C:\\Tools\\codex.exe\r\n');
+ nextFakeProc = createFakeProc().proc;
+
+ const { spawnAgent } = await import('./spawnAgent');
+ await spawnAgent({ agentType: 'codex', operationId: 'op-1', prompt: 'hello' });
+
+ const { args, command } = spawnCalls[0];
+ expect(command).toBe('C:\\Tools\\codex.exe');
+ expect(args[0]).toBe('exec');
+ });
+
it('uses codex `exec resume` form with thread id + `-` stdin marker on resume', async () => {
nextFakeProc = createFakeProc().proc;
const { spawnAgent } = await import('./spawnAgent');
@@ -242,7 +278,9 @@ describe('spawnAgent', () => {
const imageIdx = args.indexOf('--image');
expect(imageIdx).toBeGreaterThan(-1);
const materializedPath = args[imageIdx + 1]!;
- expect(materializedPath.startsWith(cacheDir)).toBe(true);
+ const normalizedCacheDir = cacheDir.replaceAll('\\', '/');
+ const normalizedMaterializedPath = materializedPath.replaceAll('\\', '/');
+ expect(normalizedMaterializedPath.startsWith(normalizedCacheDir)).toBe(true);
expect(materializedPath.endsWith('.png')).toBe(true);
// Codex receives the prompt text on stdin.
const stdinPayload = (nextFakeProc as any).stdin.write.mock.calls[0][0] as string;
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index a982fc277b2..6b7beb9671b 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -4,6 +4,7 @@ import { spawn } from 'node:child_process';
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { AgentStreamPipeline } from './agentStreamPipeline';
+import { resolveCliSpawnPlan } from './cliSpawn';
import type { AgentPromptInput, BuildAgentInputOptions } from './input';
import { buildAgentInput } from './input';
@@ -230,13 +231,21 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
});
const cwd = options.cwd || process.cwd();
- const proc = spawn(command, args, {
+ const cliSpawnPlan = await resolveCliSpawnPlan(command, args);
+ const proc = spawn(cliSpawnPlan.command, cliSpawnPlan.args, {
cwd,
detached: process.platform !== 'win32',
env: { ...process.env, ...options.env },
stdio: ['pipe', 'pipe', 'pipe'],
});
+ const exit = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
+ (resolve, reject) => {
+ proc.on('exit', (code, signal) => resolve({ code, signal }));
+ proc.on('error', (err) => reject(err));
+ },
+ );
+
if (proc.stdin) {
proc.stdin.write(inputPlan.stdin, () => {
proc.stdin?.end();
@@ -338,13 +347,6 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
},
};
- const exit = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
- (resolve, reject) => {
- proc.on('exit', (code, signal) => resolve({ code, signal }));
- proc.on('error', (err) => reject(err));
- },
- );
-
return {
events,
exit,