Skip to content

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

🐛 fix(hetero): launch CLI agents and dsh with the PATH detection validated (#23613)

Arvin Xu7e89e67daa82
diff --git a/apps/cli/src/commands/hetero/index.dsh.test.ts b/apps/cli/src/commands/hetero/index.dsh.test.ts
new file mode 100644
index 00000000000..14d791163f8
--- /dev/null
+++ b/apps/cli/src/commands/hetero/index.dsh.test.ts
@@ -0,0 +1,95 @@
+import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerHeteroCommand } from './index';
+
+const { resolveDsh, spawnDsh } = vi.hoisted(() => ({
+ resolveDsh: vi.fn(),
+ spawnDsh: vi.fn(),
+}));
+
+vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => ({
+ ...(await importOriginal<typeof HeteroSpawn>()),
+ resolveDshSpawnCommand: resolveDsh,
+ spawnDshAcpSession: spawnDsh,
+}));
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn() }));
+
+const runExec = async (argv: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerHeteroCommand(program);
+ await program
+ .parseAsync(['hetero', 'exec', '--type', 'deepseek-harness', ...argv], { from: 'user' })
+ .catch((error: Error) => {
+ if (!error.message.startsWith('__exit__')) throw error;
+ });
+};
+
+describe('hetero exec — DeepSeek Harness launch', () => {
+ let exit: ReturnType<typeof vi.spyOn>;
+ const dispose = vi.fn().mockResolvedValue(undefined);
+ const prompt = vi.fn(async function* () {
+ yield { data: { model: 'deepseek-chat' }, operationId: 'op-dsh', type: 'stream_start' };
+ yield { data: { finishReason: 'stop' }, operationId: 'op-dsh', type: 'agent_runtime_end' };
+ });
+
+ beforeEach(() => {
+ exit = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`__exit__${code}`);
+ }) as never);
+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ spawnDsh.mockReturnValue({ dispose, prompt, sessionId: 'dsh-session-1' });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('runs the harness through its acp-profile session', async () => {
+ resolveDsh.mockResolvedValue({ command: 'dsh' });
+
+ await runExec(['--prompt', 'say hi', '--cwd', '/tmp/work', '--model', 'deepseek-chat']);
+
+ expect(spawnDsh).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cwd: '/tmp/work',
+ model: 'deepseek-chat',
+ resumeSessionId: undefined,
+ }),
+ );
+ expect(prompt).toHaveBeenCalledWith('say hi');
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(exit).toHaveBeenCalledWith(0);
+ });
+
+ it('launches the validated dsh with the PATH that found it', async () => {
+ // e.g. `npm i -g @deepseek-ai/dsh` after the host started: the registry
+ // PATH has the npm dir, the process PATH does not.
+ resolveDsh.mockResolvedValue({
+ command: 'C:\\Users\\x\\AppData\\Roaming\\npm\\dsh.cmd',
+ pathEnv: 'C:\\Users\\x\\AppData\\Roaming\\npm;C:\\Windows',
+ });
+
+ await runExec(['--prompt', 'say hi']);
+
+ expect(resolveDsh).toHaveBeenCalledWith(undefined);
+ expect(spawnDsh).toHaveBeenCalledWith(
+ expect.objectContaining({
+ command: 'C:\\Users\\x\\AppData\\Roaming\\npm\\dsh.cmd',
+ env: expect.objectContaining({ PATH: 'C:\\Users\\x\\AppData\\Roaming\\npm;C:\\Windows' }),
+ }),
+ );
+ });
+
+ it('passes a custom --command through to the resolver', async () => {
+ resolveDsh.mockResolvedValue({ command: '/opt/dsh-wrapped' });
+
+ await runExec(['--prompt', 'say hi', '--command', '/opt/dsh-wrapped']);
+
+ expect(resolveDsh).toHaveBeenCalledWith('/opt/dsh-wrapped');
+ expect(spawnDsh).toHaveBeenCalledWith(expect.objectContaining({ command: '/opt/dsh-wrapped' }));
+ });
+});
diff --git a/apps/cli/src/commands/hetero/index.test.ts b/apps/cli/src/commands/hetero/index.test.ts
index 8e7ed771c61..039a7966abd 100644
--- a/apps/cli/src/commands/hetero/index.test.ts
+++ b/apps/cli/src/commands/hetero/index.test.ts
@@ -39,6 +39,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => ({
...(await importOriginal<typeof HeteroSpawn>()),
spawnAgent: mockSpawnAgent,
spawnDshAcpSession: mockSpawnDshAcpSession,
+ resolveDshSpawnCommand: async (command?: string) => ({ command: command ?? 'dsh' }),
createCodexAgentHandle: mockCreateCodexAgentHandle,
}));
@@ -549,48 +550,6 @@ describe('hetero exec command', () => {
);
});
- it('runs DeepSeek Harness through its dsh CLI acp-profile session', async () => {
- const dispose = vi.fn().mockResolvedValue(undefined);
- const prompt = vi.fn(async function* () {
- yield {
- data: { model: 'deepseek-chat', provider: 'deepseek-harness' },
- operationId: 'op-dsh',
- type: 'stream_start',
- };
- yield {
- data: { finishReason: 'stop' },
- operationId: 'op-dsh',
- type: 'agent_runtime_end',
- };
- });
- mockSpawnDshAcpSession.mockReturnValue({ dispose, prompt, sessionId: 'dsh-session-1' });
-
- await runCmd([
- 'hetero',
- 'exec',
- '--type',
- 'deepseek-harness',
- '--prompt',
- 'say hi',
- '--cwd',
- '/tmp/work',
- '--model',
- 'deepseek-chat',
- ]);
-
- expect(mockSpawnDshAcpSession).toHaveBeenCalledWith(
- expect.objectContaining({
- cwd: '/tmp/work',
- model: 'deepseek-chat',
- resumeSessionId: undefined,
- }),
- );
- expect(prompt).toHaveBeenCalledWith('say hi');
- expect(dispose).toHaveBeenCalledTimes(1);
- expect(mockSpawnAgent).not.toHaveBeenCalled();
- expect(exitSpy).toHaveBeenCalledWith(0);
- });
-
it('resumes the harness session named by --resume and reports it on finish', async () => {
vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue(undefined);
mockSpawnDshAcpSession.mockReturnValue({
diff --git a/apps/cli/src/commands/hetero/index.ts b/apps/cli/src/commands/hetero/index.ts
index 803d41f228f..40f5182e328 100644
--- a/apps/cli/src/commands/hetero/index.ts
+++ b/apps/cli/src/commands/hetero/index.ts
@@ -30,6 +30,7 @@ import {
createCodexAgentHandle,
createFileStoreImageUploader,
isHeteroStatusGuideErrorData,
+ resolveDshSpawnCommand,
spawnAgent,
spawnDshAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
@@ -435,9 +436,8 @@ const exec = async (options: ExecOptions): Promise<void> => {
})
: undefined;
- // DSH is a protocol runtime (its `acp` profile) with no CLI descriptor. Keep
- // it on the same public `hetero exec` surface, but drive its ACP session
- // directly instead of passing it through `spawnAgent`.
+ // DSH (an `acp`-profile runtime, no CLI descriptor) keeps the CLI agents' surface and
+ // identity echo, but drives its ACP session directly on the validated `dsh` + its PATH.
if (agentType === DSH_AGENT_TYPE) {
const hasImages =
typeof resolved.prompt !== 'string' &&
@@ -468,15 +468,15 @@ const exec = async (options: ExecOptions): Promise<void> => {
};
try {
+ const dshCommand = await resolveDshSpawnCommand(options.command);
session = spawnDshAcpSession({
args: options.agentArg,
clientVersion: 'lobehub-cli',
- command: options.command,
+ command: dshCommand.command,
cwd: options.cwd || process.cwd(),
- // Same identity echo as the CLI agents, so `lh` commands the harness
- // runs for this conversation can name its operation and topic.
env: buildAgentProcessEnv({
operationId: serverIngest ? operationId : undefined,
+ pathEnv: dshCommand.pathEnv,
topicId: options.topic,
}),
model: options.model,
diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
index f336d7f48d4..0acaeb6ed10 100644
--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts
@@ -449,7 +449,7 @@ export const listHeterogeneousAgentModels = async (
: params.type === 'pi'
? buildPiCatalogArgs(params.args)
: ['--list-models'];
- const spawnPlan = await resolveCliSpawnPlan(resolved.command, args);
+ const spawnPlan = await resolveCliSpawnPlan(resolved.command, args, env as NodeJS.ProcessEnv);
const { stderr, stdout } = await execFilePromise(spawnPlan.command, spawnPlan.args, {
cwd,
encoding: 'utf8',
diff --git a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
index 6cb48ebdb5e..60582cba2a0 100644
--- a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
+++ b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
@@ -117,7 +117,11 @@ export class RpcStdioClient {
async start(): Promise<void> {
if (this.child || this.closed) return;
- const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, this.options.args);
+ const spawnPlan = await resolveCliSpawnPlan(
+ this.options.commandPath,
+ this.options.args,
+ this.options.env,
+ );
if (this.closed) return;
const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
cwd: this.options.cwd,
diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts
index e3d85180625..7a5a5103231 100644
--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts
+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts
@@ -102,7 +102,11 @@ export class AcpStdioClient {
if (this.child) return;
if (this.closed) throw new Error('ACP stdio client is closed');
- const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, this.options.args);
+ const spawnPlan = await resolveCliSpawnPlan(
+ this.options.commandPath,
+ this.options.args,
+ this.options.env,
+ );
if (this.closed) throw new Error('ACP stdio client is closed');
const detached = process.platform !== 'win32' && (this.options.detached ?? true);
const child = spawnManaged(spawnPlan.command, spawnPlan.args, {
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts
new file mode 100644
index 00000000000..1c13bad45db
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.resolve.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DSH_MIN_VERSION, resolveDshSpawnCommand } from './dshAcpSession';
+
+const { detectValidatedCommand } = vi.hoisted(() => ({ detectValidatedCommand: vi.fn() }));
+
+vi.mock('./resolveCliCommand', () => ({ detectValidatedCommand }));
+
+describe('resolveDshSpawnCommand', () => {
+ beforeEach(() => detectValidatedCommand.mockReset());
+
+ it('launches the validated dsh with the PATH that found it', async () => {
+ // Installed after the host started: only the re-read PATH has it.
+ detectValidatedCommand.mockResolvedValue({
+ available: true,
+ path: 'C:\\Users\\x\\AppData\\Roaming\\npm\\dsh.cmd',
+ resolvedPathEnv: 'C:\\Users\\x\\AppData\\Roaming\\npm;C:\\Windows',
+ version: DSH_MIN_VERSION,
+ });
+ const env = { PATH: 'C:\\Windows' };
+
+ await expect(resolveDshSpawnCommand(undefined, env)).resolves.toEqual({
+ command: 'C:\\Users\\x\\AppData\\Roaming\\npm\\dsh.cmd',
+ pathEnv: 'C:\\Users\\x\\AppData\\Roaming\\npm;C:\\Windows',
+ version: DSH_MIN_VERSION,
+ });
+ expect(detectValidatedCommand).toHaveBeenCalledWith('dsh', expect.any(Object), env);
+ });
+
+ it('falls back to the bare command when detection fails or finds an old CLI', async () => {
+ detectValidatedCommand.mockRejectedValueOnce(new Error('probe crashed'));
+ await expect(resolveDshSpawnCommand('dsh')).resolves.toEqual({ command: 'dsh' });
+
+ detectValidatedCommand.mockResolvedValueOnce({
+ available: true,
+ path: '/old/dsh',
+ version: '0.0.1',
+ });
+ await expect(resolveDshSpawnCommand()).resolves.toEqual({ command: 'dsh' });
+ });
+
+ it('uses a custom command verbatim without probing', async () => {
+ await expect(resolveDshSpawnCommand(' /opt/dsh-wrapped ')).resolves.toEqual({
+ command: '/opt/dsh-wrapped',
+ });
+ expect(detectValidatedCommand).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
index 5e3ef0589e0..7f334f80559 100644
--- a/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/dshAcpSession.ts
@@ -11,7 +11,7 @@ import {
} from './acpAgentSession';
import type { AcpRpcMessage } from './acpStdioClient';
import { AcpServerRequestError } from './acpStdioClient';
-import type { CliCommandStatus } from './resolveCliCommand';
+import type { CliCommandStatus, ResolvedHeteroCommand } from './resolveCliCommand';
import { detectValidatedCommand } from './resolveCliCommand';
/**
@@ -69,6 +69,25 @@ export const detectDshCommand = async (
};
};
+/**
+ * The `dsh` binary a session should spawn, with the PATH that validated it.
+ * A custom command is used verbatim; the default one is re-detected so a CLI
+ * installed after the host started (a fresh registry PATH on Windows, a new
+ * login-shell PATH elsewhere) still launches instead of failing with ENOENT.
+ */
+export const resolveDshSpawnCommand = async (
+ command?: string,
+ env?: NodeJS.ProcessEnv,
+): Promise<ResolvedHeteroCommand> => {
+ const requested = command?.trim();
+ if (requested && requested !== DSH_COMMAND) return { command: requested };
+
+ const detected = await detectDshCommand(DSH_COMMAND, env).catch(() => undefined);
+ return detected?.available && detected.path
+ ? { command: detected.path, pathEnv: detected.resolvedPathEnv, version: detected.version }
+ : { command: DSH_COMMAND };
+};
+
/** Select the CLI's shipped ACP profile, served on stdio until disconnect. */
export const DSH_ACP_PROFILE_ARGS: readonly string[] = ['--profile', 'acp'];
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 58e4531dfe2..3bdf316cc6b 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -151,6 +151,7 @@ export {
DshAcpSession,
type DshAcpSessionHandle,
type DshAcpSessionOptions,
+ resolveDshSpawnCommand,
spawnDshAcpSession,
type SpawnDshAcpSessionOptions,
} from './dshAcpSession';
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index dd7ce6e2bc8..a819e41ca1b 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -28,10 +28,7 @@ import {
} from './acpSpawnAgent';
import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';
import { buildAntigravityArgs } from './antigravity';
-import {
- AntigravityLiveInput,
- resolveAntigravityLiveRuntimeEnd,
-} from './antigravityLiveInput';
+import { AntigravityLiveInput, resolveAntigravityLiveRuntimeEnd } from './antigravityLiveInput';
import {
type ClaudeCodeControlRequest,
type ClaudeCodeControlRequestHandle,
@@ -610,7 +607,7 @@ const spawnCliAgent = async (
})
: undefined;
- const cliSpawnPlan = await resolveCliSpawnPlan(command, args);
+ const cliSpawnPlan = await resolveCliSpawnPlan(command, args, childEnv);
const detached = platform() !== 'win32' && (options.detached ?? true);
const startedAt = Date.now();
const proc = spawnManaged(cliSpawnPlan.command, cliSpawnPlan.args, {
@@ -620,7 +617,8 @@ const spawnCliAgent = async (
stdio: ['pipe', 'pipe', 'pipe'],
});
- const claudeLive = claudeLiveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : undefined;
+ const claudeLive =
+ claudeLiveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : undefined;
const antigravityLive =
antigravityLiveInput && proc.stdin ? new AntigravityLiveInput(proc.stdin) : undefined;
const live = claudeLive ?? antigravityLive;
diff --git a/packages/heterogeneous-agents/src/spawn/stdioClients.spawnEnv.test.ts b/packages/heterogeneous-agents/src/spawn/stdioClients.spawnEnv.test.ts
new file mode 100644
index 00000000000..82570c73ed6
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/stdioClients.spawnEnv.test.ts
@@ -0,0 +1,45 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { RpcStdioClient } from '../rpc/rpcStdioClient';
+import { AcpStdioClient } from './acpStdioClient';
+
+const { resolveCliSpawnPlan, spawnManaged } = vi.hoisted(() => ({
+ resolveCliSpawnPlan: vi.fn(async (command: string, args: string[]) => ({ args, command })),
+ spawnManaged: vi.fn(),
+}));
+
+vi.mock('./cliSpawn', () => ({ resolveCliSpawnPlan }));
+vi.mock('@lobechat/utils/managedProcess', () => ({ spawnManaged }));
+
+const fakeChild = () =>
+ Object.assign(new EventEmitter(), {
+ pid: 1,
+ stderr: new PassThrough(),
+ stdin: new PassThrough(),
+ stdout: new PassThrough(),
+ });
+
+// A Windows npm shim is unwrapped by finding `node` on PATH. The child's PATH
+// (the one detection validated) must be the one searched, not the host's
+// startup PATH, or a CLI installed after launch fails with EINVAL / ENOENT.
+const env = { PATH: 'C:\\Users\\x\\AppData\\Roaming\\npm;C:\\Windows' };
+const common = { args: ['acp'], commandPath: 'codex.cmd', cwd: '/work', env, onStderr: vi.fn() };
+
+describe('stdio clients resolve their spawn plan against the child env', () => {
+ it('ACP', async () => {
+ spawnManaged.mockReturnValue(fakeChild());
+ await new AcpStdioClient({ ...common, onMessage: vi.fn(), onRawMessage: vi.fn() }).start();
+
+ expect(resolveCliSpawnPlan).toHaveBeenLastCalledWith('codex.cmd', ['acp'], env);
+ });
+
+ it('RPC', async () => {
+ spawnManaged.mockReturnValue(fakeChild());
+ await new RpcStdioClient({ ...common, onMessage: vi.fn() }).start();
+
+ expect(resolveCliSpawnPlan).toHaveBeenLastCalledWith('codex.cmd', ['acp'], env);
+ });
+});