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.

✨ feat(cli): add `lh hetero exec` for standalone heterogeneous agent runs (#14431)

Arvin Xu5fb795b0921c
diff --git a/apps/cli/package.json b/apps/cli/package.json
index ec4f7bf94c5..bacf6446f01 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -30,6 +30,7 @@
"devDependencies": {
"@lobechat/agent-gateway-client": "workspace:*",
"@lobechat/device-gateway-client": "workspace:*",
+ "@lobechat/heterogeneous-agents": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
"@trpc/client": "^11.8.1",
"@types/node": "^22.13.5",
diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yaml
index 0ee104d0196..fe07df92c18 100644
--- a/apps/cli/pnpm-workspace.yaml
+++ b/apps/cli/pnpm-workspace.yaml
@@ -1,6 +1,7 @@
packages:
- '../../packages/agent-gateway-client'
- '../../packages/device-gateway-client'
+ - '../../packages/heterogeneous-agents'
- '../../packages/local-file-shell'
- '../../packages/file-loaders'
- '.'
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
new file mode 100644
index 00000000000..19f8d1e15fa
--- /dev/null
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -0,0 +1,217 @@
+import { PassThrough } from 'node:stream';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerHeteroCommand } from './hetero';
+
+const { mockSpawnAgent } = vi.hoisted(() => ({
+ mockSpawnAgent: vi.fn(),
+}));
+
+vi.mock('@lobechat/heterogeneous-agents/spawn', () => ({
+ spawnAgent: mockSpawnAgent,
+}));
+
+vi.mock('../utils/logger', () => ({
+ log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ setVerbose: vi.fn(),
+}));
+
+/**
+ * Build a fake `SpawnAgentHandle`. The async iterable yields `events`
+ * synchronously and ends, so the command's `for await (const event of ...)`
+ * loop terminates without hanging the test.
+ */
+const createFakeHandle = ({
+ events = [] as any[],
+ exitCode = 0,
+ signal = null as NodeJS.Signals | null,
+ stderrChunks = [] as string[],
+}: {
+ events?: any[];
+ exitCode?: number | null;
+ signal?: NodeJS.Signals | null;
+ stderrChunks?: string[];
+} = {}) => {
+ const stderr = new PassThrough();
+ setImmediate(() => {
+ for (const c of stderrChunks) stderr.write(c);
+ stderr.end();
+ });
+
+ const eventsIter: AsyncIterable<any> = {
+ [Symbol.asyncIterator]() {
+ let i = 0;
+ return {
+ async next() {
+ if (i < events.length) return { done: false, value: events[i++] };
+ return { done: true, value: undefined };
+ },
+ };
+ },
+ };
+
+ return {
+ events: eventsIter,
+ exit: Promise.resolve({ code: exitCode, signal }),
+ kill: vi.fn(),
+ pid: 12_345,
+ stderr,
+ };
+};
+
+describe('hetero exec command', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let stdoutSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ // Stub `process.exit` so the test runner doesn't tear down — but THROW a
+ // sentinel rather than return, mirroring `process.exit`'s `never` return
+ // type in production. Without throwing, the command's code after an
+ // `exit(2)` keeps running and crashes on `handle.stderr` (no spawn mock).
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`__exit__${code}`);
+ }) as any);
+ stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ mockSpawnAgent.mockReset();
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ stdoutSpy.mockRestore();
+ vi.restoreAllMocks();
+ });
+
+ /** Build a fresh program with the hetero command registered. */
+ const buildProgram = () => {
+ const program = new Command();
+ program.exitOverride();
+ registerHeteroCommand(program);
+ return program;
+ };
+
+ /**
+ * Run the parsed command. Swallows our `__exit__<code>` sentinel so tests
+ * can inspect `exitSpy.mock.calls` afterwards instead of having to wrap
+ * every `parseAsync` in `expect(...).rejects`. Real production exits stay
+ * `process.exit` so this only affects the test path.
+ */
+ const runCmd = async (argv: string[]) => {
+ try {
+ await buildProgram().parseAsync(argv, { from: 'user' });
+ } catch (err) {
+ if (err instanceof Error && err.message.startsWith('__exit__')) return;
+ throw err;
+ }
+ };
+
+ it('rejects unsupported agent types via process.exit(2)', async () => {
+ await runCmd(['hetero', 'exec', '--type', 'kimi-cli', '--prompt', 'hi']);
+ expect(exitSpy).toHaveBeenCalledWith(2);
+ expect(mockSpawnAgent).not.toHaveBeenCalled();
+ });
+
+ it('rejects empty prompts via process.exit(2)', async () => {
+ await runCmd(['hetero', 'exec', '--type', 'claude-code', '--prompt', ' ']);
+ expect(exitSpy).toHaveBeenCalledWith(2);
+ expect(mockSpawnAgent).not.toHaveBeenCalled();
+ });
+
+ it('passes --type / --prompt / --resume / --cwd / --command through to spawnAgent', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle());
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'codex',
+ '--prompt',
+ 'do thing',
+ '--resume',
+ 'thread_abc',
+ '--cwd',
+ '/tmp/work',
+ '--command',
+ '/usr/local/bin/codex',
+ ]);
+
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);
+ const call = mockSpawnAgent.mock.calls[0][0];
+ expect(call).toMatchObject({
+ agentType: 'codex',
+ command: '/usr/local/bin/codex',
+ cwd: '/tmp/work',
+ prompt: 'do thing',
+ resumeSessionId: 'thread_abc',
+ });
+ // operationId auto-generated when omitted (uuid v4 shape)
+ expect(call.operationId).toMatch(/^[0-9a-f-]{36}$/i);
+ });
+
+ it('uses the provided --operation-id verbatim', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle());
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--operation-id',
+ 'op-server-allocated',
+ ]);
+
+ const call = mockSpawnAgent.mock.calls[0][0];
+ expect(call.operationId).toBe('op-server-allocated');
+ });
+
+ it('streams events to stdout as JSONL, one line per event', async () => {
+ const events = [
+ { data: { foo: 1 }, operationId: 'op-1', stepIndex: 0, timestamp: 1, type: 'stream_start' },
+ {
+ data: { chunkType: 'text', content: 'hi' },
+ operationId: 'op-1',
+ stepIndex: 0,
+ timestamp: 2,
+ type: 'stream_chunk',
+ },
+ ];
+ mockSpawnAgent.mockReturnValue(createFakeHandle({ events }));
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--operation-id',
+ 'op-1',
+ ]);
+
+ // Each event is one JSON line with a trailing \n.
+ const lines = stdoutSpy.mock.calls.map((c) => c[0]).filter((s) => typeof s === 'string');
+ expect(lines).toHaveLength(2);
+ for (const line of lines as string[]) {
+ expect(line.endsWith('\n')).toBe(true);
+ const parsed = JSON.parse(line);
+ expect(parsed.operationId).toBe('op-1');
+ }
+ });
+
+ it('passes the child exit code straight through', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle({ exitCode: 7 }));
+
+ await runCmd(['hetero', 'exec', '--type', 'claude-code', '--prompt', 'hi']);
+ expect(exitSpy).toHaveBeenCalledWith(7);
+ });
+
+ it('maps SIGINT (code === null) to POSIX exit code 130', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle({ exitCode: null, signal: 'SIGINT' }));
+
+ await runCmd(['hetero', 'exec', '--type', 'claude-code', '--prompt', 'hi']);
+ expect(exitSpy).toHaveBeenCalledWith(130);
+ });
+});
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
new file mode 100644
index 00000000000..a613c5dd429
--- /dev/null
+++ b/apps/cli/src/commands/hetero.ts
@@ -0,0 +1,131 @@
+import { randomUUID } from 'node:crypto';
+
+import { spawnAgent } from '@lobechat/heterogeneous-agents/spawn';
+import type { Command } from 'commander';
+
+import { log } from '../utils/logger';
+
+const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);
+
+interface ExecOptions {
+ command?: string;
+ cwd?: string;
+ operationId?: string;
+ prompt?: string;
+ resume?: string;
+ type: string;
+}
+
+/**
+ * Read all of stdin to a string. Used when `--prompt -` (or `--prompt` is
+ * omitted) to pull the user prompt from a pipe / heredoc.
+ */
+const readStdin = async (): Promise<string> => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));
+ }
+ return Buffer.concat(chunks).toString('utf8');
+};
+
+const resolvePrompt = async (raw: string | undefined): Promise<string> => {
+ if (raw === undefined || raw === '-') return readStdin();
+ return raw;
+};
+
+const exec = async (options: ExecOptions): Promise<void> => {
+ if (!SUPPORTED_AGENT_TYPES.has(options.type)) {
+ log.error(
+ `Unsupported --type "${options.type}". Supported: ${[...SUPPORTED_AGENT_TYPES].join(', ')}`,
+ );
+ process.exit(2);
+ }
+
+ const prompt = await resolvePrompt(options.prompt);
+ if (!prompt.trim()) {
+ log.error('Empty prompt. Pass --prompt <text> or pipe content via stdin.');
+ process.exit(2);
+ }
+
+ // Standalone (phase 1a): no server ingest, so the operationId is just an
+ // identity stamp on the JSONL stream. Generate a fresh one if the caller
+ // didn't provide --operation-id; phase 1b will require it as a real
+ // server-allocated id.
+ const operationId = options.operationId || randomUUID();
+
+ const handle = spawnAgent({
+ agentType: options.type,
+ command: options.command,
+ cwd: options.cwd || process.cwd(),
+ operationId,
+ prompt,
+ resumeSessionId: options.resume,
+ });
+
+ // Forward the child's stderr to ours so users see CLI errors / warnings
+ // (auth prompts, missing-binary errors, etc.) in the terminal.
+ handle.stderr.pipe(process.stderr);
+
+ // Ctrl-C → SIGINT to the child's process group so the spawned CLI gets a
+ // chance to clean up. Repeated Ctrl-C escalates to SIGKILL via the
+ // standard "double-tap" pattern most CLIs implement themselves.
+ let interrupted = false;
+ const onSigint = () => {
+ if (interrupted) {
+ handle.kill('SIGKILL');
+ return;
+ }
+ interrupted = true;
+ handle.kill('SIGINT');
+ };
+ process.on('SIGINT', onSigint);
+ process.on('SIGTERM', () => handle.kill('SIGTERM'));
+
+ // Stream events out as JSONL on stdout. Each line is one `AgentStreamEvent`.
+ // Use raw write (not console.log) so we don't pull in console formatting
+ // and JSONL stays parseable downstream.
+ try {
+ for await (const event of handle.events) {
+ process.stdout.write(`${JSON.stringify(event)}\n`);
+ }
+ } catch (err) {
+ log.error('Stream error from agent process:', err instanceof Error ? err.message : String(err));
+ process.exit(1);
+ } finally {
+ process.off('SIGINT', onSigint);
+ }
+
+ // Pass the child's exit code through. Signal-induced exits (SIGINT etc.)
+ // surface as `code === null` — map to 130 (POSIX convention for SIGINT).
+ const { code, signal } = await handle.exit;
+ if (code !== null) process.exit(code);
+ if (signal === 'SIGINT') process.exit(130);
+ if (signal === 'SIGTERM') process.exit(143);
+ if (signal === 'SIGKILL') process.exit(137);
+ process.exit(1);
+};
+
+export function registerHeteroCommand(program: Command) {
+ const hetero = program
+ .command('hetero')
+ .description('Run heterogeneous agent CLIs (Claude Code / Codex) and stream their output');
+
+ hetero
+ .command('exec')
+ .description(
+ 'Spawn a heterogeneous agent CLI and stream its events as JSONL on stdout. Standalone mode (no server ingest).',
+ )
+ .requiredOption('-t, --type <type>', `Agent type: ${[...SUPPORTED_AGENT_TYPES].join(' | ')}`)
+ .option('-p, --prompt [text]', 'Prompt text. Pass `-` (or omit the value) to read from stdin.')
+ .option('-r, --resume <sessionId>', 'Resume an existing agent session by its native id')
+ .option('-d, --cwd <path>', 'Working directory for the spawned agent (default: process.cwd())')
+ .option(
+ '-c, --command <bin>',
+ 'Override the agent CLI binary name (default: `claude` or `codex`)',
+ )
+ .option(
+ '--operation-id <id>',
+ 'Operation id stamped onto every emitted event. Generated as a uuid if omitted (phase 1a).',
+ )
+ .action(exec);
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index bf3d4ddd3af..e26680477f3 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -14,6 +14,7 @@ import { registerDocCommand } from './commands/doc';
import { registerEvalCommand } from './commands/eval';
import { registerFileCommand } from './commands/file';
import { registerGenerateCommand } from './commands/generate';
+import { registerHeteroCommand } from './commands/hetero';
import { registerKbCommand } from './commands/kb';
import { registerLoginCommand } from './commands/login';
import { registerLogoutCommand } from './commands/logout';
@@ -62,6 +63,7 @@ export function createProgram() {
registerCronCommand(program);
registerGenerateCommand(program);
registerFileCommand(program);
+ registerHeteroCommand(program);
registerSkillCommand(program);
registerSessionGroupCommand(program);
registerTaskCommand(program);
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 60a50d7a45b..ed5384fe91c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -515,6 +515,22 @@
"taskDetail.properties": "Properties",
"taskDetail.reassignDisabled": "Cannot reassign agent while task is running",
"taskDetail.rerunTask": "Re-run task",
+ "taskDetail.runAll": "Run all",
+ "taskDetail.runAll.cancel": "Cancel",
+ "taskDetail.runAll.confirm": "Run {{count}} subtask(s)",
+ "taskDetail.runAll.cycleWarning": "Circular dependency detected. Tasks involved in or blocked by the cycle will not run: {{members}}",
+ "taskDetail.runAll.description": "Subtasks will run layer by layer. Each layer waits for the previous one to finish. Tasks with no dependencies run in layer 1.",
+ "taskDetail.runAll.empty": "Nothing to run — every subtask is already completed, in flight, or stuck in a cycle.",
+ "taskDetail.runAll.kickedOff": "Started {{count}} subtask(s); downstream layers will follow.",
+ "taskDetail.runAll.layer": "Layer {{index}}",
+ "taskDetail.runAll.layerHint.first": "Starts immediately",
+ "taskDetail.runAll.layerHint.next": "Waits for layer {{prev}} to finish",
+ "taskDetail.runAll.loading": "Loading subtask plan...",
+ "taskDetail.runAll.partialFailure": "Started {{ok}} of {{total}} subtask(s); {{failed}} failed.",
+ "taskDetail.runAll.skipped.alreadyDone": "{{count}} task(s) already completed or canceled — skipped",
+ "taskDetail.runAll.skipped.blockedExternally": "{{count}} task(s) waiting on a blocker outside this batch — will run automatically when unblocked",
+ "taskDetail.runAll.skipped.ineligible": "{{count}} task(s) running or scheduled — skipped",
+ "taskDetail.runAll.title": "Run subtasks in dependency order",
"taskDetail.runNow": "Run now",
"taskDetail.runTask": "Run",
"taskDetail.saveModelConfig": "Save",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 9c80067fd6c..21d49879b02 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -520,6 +520,22 @@
"taskDetail.properties": "属性",
"taskDetail.reassignDisabled": "任务运行中,无法切换 Agent",
"taskDetail.rerunTask": "重新运行",
+ "taskDetail.runAll": "全部运行",
+ "taskDetail.runAll.cancel": "取消",
+ "taskDetail.runAll.confirm": "运行 {{count}} 个子任务",
+ "taskDetail.runAll.cycleWarning": "检测到循环依赖,涉及循环或被循环阻塞的任务将不会运行:{{members}}",
+ "taskDetail.runAll.description": "子任务将按层级依次运行,每一层都会等待上一层完成。无依赖的任务将在第 1 层运行。",
+ "taskDetail.runAll.empty": "没有可运行的任务 —— 所有子任务均已完成、运行中或处于循环依赖中。",
+ "taskDetail.runAll.kickedOff": "已启动 {{count}} 个子任务,下游层级将自动跟进。",
+ "taskDetail.runAll.layer": "第 {{index}} 层",
+ "taskDetail.runAll.layerHint.first": "立即开始",
+ "taskDetail.runAll.layerHint.next": "等待第 {{prev}} 层完成",
+ "taskDetail.runAll.loading": "正在加载子任务计划…",
+ "taskDetail.runAll.partialFailure": "已启动 {{total}} 个子任务中的 {{ok}} 个,{{failed}} 个启动失败。",
+ "taskDetail.runAll.skipped.alreadyDone": "{{count}} 个任务已完成或取消 —— 已跳过",
+ "taskDetail.runAll.skipped.blockedExternally": "{{count}} 个任务被本批次外的依赖阻塞 —— 解除阻塞后将自动运行",
+ "taskDetail.runAll.skipped.ineligible": "{{count}} 个任务正在运行或已排期 —— 已跳过",
+ "taskDetail.runAll.title": "按依赖顺序运行子任务",
"taskDetail.runNow": "立即运行",
"taskDetail.runTask": "运行",
"taskDetail.saveModelConfig": "保存",
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 21968dd328b..49b40563fee 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -15,5 +15,6 @@
export { AgentStreamPipeline, type AgentStreamPipelineOptions } from './agentStreamPipeline';
export { CodexFileChangeTracker } from './codexFileChangeTracker';
export { JsonlStreamProcessor } from './jsonlProcessor';
+export { spawnAgent, type SpawnAgentHandle, type SpawnAgentOptions } from './spawnAgent';
export { toStreamEvent } from './streamEvent';
export type { AgentStreamEvent, AgentStreamEventType } from '@lobechat/agent-gateway-client';
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
new file mode 100644
index 00000000000..73edbb3fca6
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
@@ -0,0 +1,351 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+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>;
+ return {
+ ...actual,
+ spawn: (command: string, args: string[], options: any) => {
+ spawnCalls.push({ args, command, options });
+ return nextFakeProc;
+ },
+ };
+});
+
+const createFakeProc = ({
+ exitCode = 0,
+ stdoutChunks = [] as string[],
+ stderrChunks = [] as string[],
+}: {
+ exitCode?: number;
+ stderrChunks?: string[];
+ stdoutChunks?: string[];
+} = {}) => {
+ const proc = new EventEmitter() as any;
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ const stdinWrites: string[] = [];
+ proc.stdout = stdout;
+ proc.stderr = stderr;
+ proc.stdin = {
+ end: vi.fn(),
+ write: vi.fn((chunk: string, cb?: () => void) => {
+ stdinWrites.push(chunk);
+ cb?.();
+ return true;
+ }),
+ };
+ proc.kill = vi.fn();
+ proc.killed = false;
+ proc.pid = 12_345;
+
+ const start = () => {
+ setImmediate(() => {
+ for (const c of stdoutChunks) stdout.write(c);
+ for (const c of stderrChunks) stderr.write(c);
+ stdout.end();
+ stderr.end();
+ proc.emit('exit', exitCode, null);
+ });
+ };
+
+ return { proc, start, stdinWrites };
+};
+
+const ccInit = `${JSON.stringify({
+ model: 'claude-sonnet-4-6',
+ session_id: 'cc-1',
+ subtype: 'init',
+ type: 'system',
+})}\n`;
+
+const ccText = `${JSON.stringify({
+ message: {
+ content: [{ text: 'hello', type: 'text' }],
+ id: 'msg_01',
+ model: 'claude-sonnet-4-6',
+ role: 'assistant',
+ },
+ type: 'assistant',
+})}\n`;
+
+describe('spawnAgent', () => {
+ beforeEach(() => {
+ spawnCalls.length = 0;
+ nextFakeProc = null;
+ });
+
+ afterEach(() => {
+ nextFakeProc = null;
+ });
+
+ it('spawns claude with stream-json flags + writes prompt as user message to stdin', async () => {
+ const fake = createFakeProc({ stdoutChunks: [ccInit] });
+ nextFakeProc = fake.proc;
+
+ const { spawnAgent } = await import('./spawnAgent');
+ const handle = spawnAgent({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ prompt: 'do a thing',
+ });
+ fake.start();
+
+ const events: any[] = [];
+ for await (const event of handle.events) events.push(event);
+ await handle.exit;
+
+ expect(spawnCalls).toHaveLength(1);
+ const call = spawnCalls[0];
+ expect(call.command).toBe('claude');
+ expect(call.args).toContain('--input-format');
+ expect(call.args).toContain('--output-format');
+ expect(call.args.filter((a) => a === 'stream-json')).toHaveLength(2);
+ expect(call.args).toContain('-p');
+ expect(call.args).toContain('--include-partial-messages');
+ // Prompt MUST go through stdin as a stream-json user message — never as argv.
+ expect(call.args).not.toContain('do a thing');
+ expect(fake.stdinWrites).toHaveLength(1);
+ const userMsg = JSON.parse(fake.stdinWrites[0].trim());
+ expect(userMsg).toMatchObject({
+ message: { content: [{ text: 'do a thing', type: 'text' }], role: 'user' },
+ type: 'user',
+ });
+ // Events flow through the pipeline (session id extracted by adapter).
+ expect(events.length).toBeGreaterThan(0);
+ for (const event of events) expect(event.operationId).toBe('op-1');
+ });
+
+ it('appends --resume <id> for claude when resuming a session', async () => {
+ nextFakeProc = createFakeProc().proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ spawnAgent({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ prompt: 'continue',
+ resumeSessionId: 'cc-prev-123',
+ });
+
+ const { args } = spawnCalls[0];
+ const resumeIdx = args.indexOf('--resume');
+ expect(resumeIdx).toBeGreaterThan(-1);
+ expect(args[resumeIdx + 1]).toBe('cc-prev-123');
+ });
+
+ it('builds codex args with `exec` + json + skip-git-repo-check + full-auto', async () => {
+ nextFakeProc = createFakeProc().proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ spawnAgent({ agentType: 'codex', operationId: 'op-1', prompt: 'hello' });
+
+ const { args, command } = spawnCalls[0];
+ expect(command).toBe('codex');
+ expect(args[0]).toBe('exec');
+ expect(args).toContain('--json');
+ expect(args).toContain('--skip-git-repo-check');
+ expect(args).toContain('--full-auto');
+ });
+
+ it('uses codex `exec resume` form with thread id + `-` stdin marker on resume', async () => {
+ nextFakeProc = createFakeProc().proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ spawnAgent({
+ agentType: 'codex',
+ operationId: 'op-1',
+ prompt: 'continue',
+ resumeSessionId: 'thread_abc',
+ });
+
+ const { args } = spawnCalls[0];
+ expect(args.slice(0, 2)).toEqual(['exec', 'resume']);
+ expect(args).toContain('thread_abc');
+ expect(args.at(-1)).toBe('-');
+ });
+
+ it('honors a custom --command override + extraArgs', async () => {
+ nextFakeProc = createFakeProc().proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ spawnAgent({
+ agentType: 'claude-code',
+ command: '/usr/local/bin/claude-wrapped',
+ extraArgs: ['--my-flag', 'x'],
+ operationId: 'op-1',
+ prompt: 'hi',
+ });
+
+ const { args, command } = spawnCalls[0];
+ expect(command).toBe('/usr/local/bin/claude-wrapped');
+ expect(args).toContain('--my-flag');
+ expect(args).toContain('x');
+ });
+
+ it('throws on unknown agent type', async () => {
+ nextFakeProc = createFakeProc().proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ expect(() =>
+ spawnAgent({ agentType: 'kimi-cli', operationId: 'op-1', prompt: 'hi' }),
+ ).toThrowError(/unsupported agent type/);
+ });
+
+ it('events iterator drains all pipeline events including the trailing flush', async () => {
+ const fake = createFakeProc({ stdoutChunks: [ccInit, ccText] });
+ nextFakeProc = fake.proc;
+
+ const { spawnAgent } = await import('./spawnAgent');
+ const handle = spawnAgent({
+ agentType: 'claude-code',
+ operationId: 'op-7',
+ prompt: 'go',
+ });
+ fake.start();
+
+ const events: any[] = [];
+ for await (const event of handle.events) events.push(event);
+
+ // At minimum we expect a stream_start (from CC init) and a stream_chunk
+ // (from the assistant text). The exact event count depends on adapter
+ // partials; we just assert non-empty + every event carries our op id.
+ expect(events.length).toBeGreaterThan(0);
+ for (const event of events) expect(event.operationId).toBe('op-7');
+
+ // Verify the iterator actually completed (no hang).
+ const exit = await handle.exit;
+ expect(exit.code).toBe(0);
+ });
+
+ /**
+ * Regression for the "out-of-order events when push() is async" bug.
+ * `AgentStreamPipeline.push` is async (Codex tracker awaits FS), so
+ * back-to-back stdout chunks would otherwise have their `then` handlers
+ * race. Spy on `push` to make chunk #1 resolve AFTER chunk #2 — the spawn
+ * helper must serialize the work so events still come out in source order.
+ */
+ it('preserves event ordering across async pipeline.push() calls (Codex tracker race)', async () => {
+ vi.resetModules();
+
+ const { AgentStreamPipeline: RealPipeline } = await import('./agentStreamPipeline');
+ const pipelineSpy = vi.spyOn(RealPipeline.prototype, 'push').mockImplementation(function (
+ this: any,
+ chunk: Buffer | string,
+ ) {
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
+ const tag = text.trim();
+ // Earlier-arriving chunk gets a longer delay than later-arriving one,
+ // so without the queue chain the later chunk's `then` handler fires
+ // first and the events come out reversed.
+ const delay = tag === 'A' ? 30 : 0;
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ resolve([
+ {
+ data: { tag },
+ operationId: this.operationId,
+ stepIndex: 0,
+ timestamp: 0,
+ type: 'stream_chunk' as const,
+ },
+ ]);
+ }, delay);
+ });
+ });
+ vi.spyOn(RealPipeline.prototype, 'flush').mockResolvedValue([]);
+
+ const fake = createFakeProc();
+ nextFakeProc = fake.proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ const handle = spawnAgent({ agentType: 'claude-code', operationId: 'op-1', prompt: 'go' });
+
+ // Fire two chunks back-to-back BEFORE 'end'. Both `pipeline.push()` calls
+ // are now in flight; without serialization, B's events would queue first.
+ setImmediate(() => {
+ (fake.proc.stdout as PassThrough).write('A');
+ (fake.proc.stdout as PassThrough).write('B');
+ // Give the queue chain time to drain before ending.
+ setTimeout(() => {
+ (fake.proc.stdout as PassThrough).end();
+ fake.proc.emit('exit', 0, null);
+ }, 60);
+ });
+
+ const collected: any[] = [];
+ for await (const event of handle.events) collected.push(event.data.tag);
+
+ expect(collected).toEqual(['A', 'B']);
+ pipelineSpy.mockRestore();
+ });
+
+ /**
+ * Regression for the "iterator returns done before late push events queue"
+ * bug. Force `push()` to be slow + `end` to fire while it's still pending.
+ * Without the queue chain, `flush()` would set `streamEnded = true` before
+ * the slow push's events landed in the queue.
+ */
+ it('iterator drains slow in-flight pushes before flushing the stream', async () => {
+ vi.resetModules();
+
+ const { AgentStreamPipeline: RealPipeline } = await import('./agentStreamPipeline');
+ vi.spyOn(RealPipeline.prototype, 'push').mockImplementation(function (this: any) {
+ // 40ms delay simulates the codex tracker's FS reads.
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ resolve([
+ {
+ data: {},
+ operationId: this.operationId,
+ stepIndex: 0,
+ timestamp: 0,
+ type: 'stream_chunk' as const,
+ },
+ ]);
+ }, 40);
+ });
+ });
+ vi.spyOn(RealPipeline.prototype, 'flush').mockResolvedValue([]);
+
+ const fake = createFakeProc();
+ nextFakeProc = fake.proc;
+ const { spawnAgent } = await import('./spawnAgent');
+ const handle = spawnAgent({ agentType: 'claude-code', operationId: 'op-1', prompt: 'go' });
+
+ // 'end' fires immediately after the chunk write — pipeline.push() is still
+ // pending. The fix must keep the iterator open until that push resolves.
+ setImmediate(() => {
+ (fake.proc.stdout as PassThrough).write('chunk');
+ (fake.proc.stdout as PassThrough).end();
+ fake.proc.emit('exit', 0, null);
+ });
+
+ const collected: any[] = [];
+ for await (const event of handle.events) collected.push(event);
+
+ expect(collected).toHaveLength(1);
+ });
+
+ it('events iterator surfaces a stream error instead of hanging', async () => {
+ const fake = createFakeProc();
+ nextFakeProc = fake.proc;
+
+ const { spawnAgent } = await import('./spawnAgent');
+ const handle = spawnAgent({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ prompt: 'go',
+ });
+
+ // Fire an error on stdout instead of letting it end naturally.
+ setImmediate(() => {
+ (fake.proc.stdout as PassThrough).destroy(new Error('boom'));
+ fake.proc.emit('exit', 1, null);
+ });
+
+ await expect(async () => {
+ for await (const _e of handle.events) {
+ // drain
+ }
+ }).rejects.toThrow(/boom/);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
new file mode 100644
index 00000000000..8ad029a370d
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -0,0 +1,290 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn } from 'node:child_process';
+
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import { AgentStreamPipeline } from './agentStreamPipeline';
+
+export interface SpawnAgentOptions {
+ /** Agent type key (`'claude-code'` | `'codex'`). */
+ agentType: string;
+ /**
+ * Override the CLI binary name. Defaults to `'claude'` for `claude-code`,
+ * `'codex'` for `codex`. Use this when the binary lives at a non-default
+ * path or is wrapped by a launcher.
+ */
+ command?: string;
+ /** Working directory for the spawned child. Defaults to `process.cwd()`. */
+ cwd?: string;
+ /** Extra environment variables merged on top of `process.env`. */
+ env?: Record<string, string>;
+ /** Extra CLI arguments appended after the agent's preset flags. */
+ extraArgs?: string[];
+ /**
+ * Operation id stamped onto every emitted `AgentStreamEvent`. For ingest-
+ * connected runs this is the server-allocated op id; for standalone runs
+ * (no `--topic` / `--operation-id`) the CLI generates a fresh uuid so
+ * events still carry the conventional shape.
+ */
+ operationId: string;
+ /** User prompt text. Always passed via stdin (CC: stream-json; Codex: raw). */
+ prompt: string;
+ /** Resume an existing agent session by its native session id (CC) / thread id (Codex). */
+ resumeSessionId?: string;
+}
+
+export interface SpawnAgentHandle {
+ /**
+ * Async iterable of `AgentStreamEvent`s parsed + adapted from the child's
+ * stdout. Yields events as they arrive; iteration ends after `stdout`
+ * fully drains AND the adapter's `flush()` events have been delivered.
+ */
+ events: AsyncIterable<AgentStreamEvent>;
+ /**
+ * Resolves once the child process exits. Note: this resolves on the
+ * underlying `'exit'` event, which Node may fire before stdio is fully
+ * closed — `events` already gates on `stdout` end internally, so consumers
+ * should iterate `events` to completion BEFORE awaiting `exit` if they
+ * care about ordering.
+ */
+ exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
+ /**
+ * Send a signal to the child. On Unix, the child is spawned with
+ * `detached: true` so the whole process group can be signaled via
+ * `process.kill(-pid, signal)`; this helper does that automatically.
+ */
+ kill: (signal?: NodeJS.Signals) => void;
+ /** Spawned child PID, undefined if spawn failed pre-PID. */
+ pid: number | undefined;
+ /**
+ * The child's stderr stream — caller can pipe to its own stderr or
+ * collect for error reporting. The pipeline does not consume stderr.
+ */
+ stderr: NodeJS.ReadableStream;
+}
+
+const CLAUDE_CODE_BASE_ARGS = [
+ '-p',
+ '--input-format',
+ 'stream-json',
+ '--output-format',
+ 'stream-json',
+ '--verbose',
+ '--include-partial-messages',
+ '--permission-mode',
+ 'bypassPermissions',
+] as const;
+
+const CODEX_REQUIRED_ARGS = ['--json', '--skip-git-repo-check', '--full-auto'] as const;
+
+const buildClaudeCodeArgs = (resumeSessionId: string | undefined, extraArgs: string[]) => [
+ ...CLAUDE_CODE_BASE_ARGS,
+ ...(resumeSessionId ? ['--resume', resumeSessionId] : []),
+ ...extraArgs,
+];
+
+const buildCodexArgs = (resumeSessionId: string | undefined, extraArgs: string[]) =>
+ resumeSessionId
+ ? ['exec', 'resume', ...CODEX_REQUIRED_ARGS, ...extraArgs, resumeSessionId, '-']
+ : ['exec', ...CODEX_REQUIRED_ARGS, ...extraArgs];
+
+const buildSpawnArgs = (
+ agentType: string,
+ resumeSessionId: string | undefined,
+ extraArgs: string[],
+): string[] => {
+ switch (agentType) {
+ case 'claude-code': {
+ return buildClaudeCodeArgs(resumeSessionId, extraArgs);
+ }
+ case 'codex': {
+ return buildCodexArgs(resumeSessionId, extraArgs);
+ }
+ default: {
+ throw new Error(`spawnAgent: unsupported agent type "${agentType}"`);
+ }
+ }
+};
+
+const buildStdinPayload = (agentType: string, prompt: string): string => {
+ if (agentType === 'claude-code') {
+ return `${JSON.stringify({
+ message: { content: [{ text: prompt, type: 'text' }], role: 'user' },
+ type: 'user',
+ })}\n`;
+ }
+ // Codex reads the prompt as plain text from stdin (the `-` positional in
+ // resume mode also reads from stdin).
+ return prompt;
+};
+
+const defaultCommand = (agentType: string): string => (agentType === 'codex' ? 'codex' : 'claude');
+
+const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {
+ if (!proc.pid || proc.killed) return;
+
+ // On Windows the spawn `detached` flag has different semantics; fall back
+ // to a direct signal. Tree-kill via `taskkill` is what the desktop
+ // controller does for end-user CC, but the CLI's primary use case is
+ // sandbox + Unix dev terminals, so keep this minimal.
+ if (process.platform === 'win32') {
+ try {
+ proc.kill(signal);
+ } catch {
+ // already gone
+ }
+ return;
+ }
+
+ try {
+ process.kill(-proc.pid, signal);
+ } catch {
+ try {
+ proc.kill(signal);
+ } catch {
+ // already gone
+ }
+ }
+};
+
+/**
+ * Spawn an external agent CLI (Claude Code or Codex) and yield its stream as
+ * unified `AgentStreamEvent`s. Used by `lh hetero exec` for both standalone
+ * terminal runs and (later) sandbox-driven runs that ingest into the server.
+ *
+ * Stays minimal on purpose — no image attachment, no on-disk tracing, no
+ * proxy env composition, no CLI-not-found classification. Those host
+ * concerns live in the desktop main controller, which does NOT use this
+ * function (it instantiates `AgentStreamPipeline` directly with its own
+ * spawn logic). The CLI sandbox is a smaller environment where the minimal
+ * surface is correct.
+ */
+export const spawnAgent = (options: SpawnAgentOptions): SpawnAgentHandle => {
+ const command = options.command || defaultCommand(options.agentType);
+ const args = buildSpawnArgs(options.agentType, options.resumeSessionId, options.extraArgs ?? []);
+ const stdinPayload = buildStdinPayload(options.agentType, options.prompt);
+ const cwd = options.cwd || process.cwd();
+
+ const proc = spawn(command, args, {
+ cwd,
+ detached: process.platform !== 'win32',
+ env: { ...process.env, ...options.env },
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+
+ if (proc.stdin) {
+ proc.stdin.write(stdinPayload, () => {
+ proc.stdin?.end();
+ });
+ }
+
+ const pipeline = new AgentStreamPipeline({
+ agentType: options.agentType,
+ operationId: options.operationId,
+ });
+ const stdout = proc.stdout!;
+ const stderr = proc.stderr!;
+
+ // Buffer of events ready to be consumed by the AsyncIterable below. The
+ // generator and the stdout listeners coordinate through this single queue +
+ // wakeup promise — keeps backpressure simple and avoids a third-party
+ // dependency.
+ const queue: AgentStreamEvent[] = [];
+ let streamEnded = false;
+ let streamError: Error | undefined;
+ let wakeup: (() => void) | undefined;
+
+ const wake = () => {
+ if (wakeup) {
+ const w = wakeup;
+ wakeup = undefined;
+ w();
+ }
+ };
+
+ // ALL pipeline work — push / flush — runs through this single chain so:
+ // 1. multiple `'data'` chunks process in arrival order, even when an
+ // earlier `pipeline.push()` is still awaiting the Codex tracker's FS
+ // reads (without the chain, push #2 can resolve before push #1 and
+ // events come out of order)
+ // 2. `'end'`'s flush always runs AFTER every queued push has drained, so
+ // `streamEnded` is never flipped while earlier chunks still have events
+ // to deliver — otherwise the async iterator could return `done: true`
+ // before late events were queued (event loss).
+ let pipelineQueue: Promise<void> = Promise.resolve();
+
+ const enqueuePush = (chunk: Buffer) => {
+ pipelineQueue = pipelineQueue.then(async () => {
+ try {
+ const events = await pipeline.push(chunk);
+ for (const event of events) queue.push(event);
+ wake();
+ } catch (err) {
+ streamError = err instanceof Error ? err : new Error(String(err));
+ streamEnded = true;
+ wake();
+ }
+ });
+ };
+
+ const enqueueFlush = () => {
+ pipelineQueue = pipelineQueue.then(async () => {
+ try {
+ const events = await pipeline.flush();
+ for (const event of events) queue.push(event);
+ } catch (err) {
+ streamError = err instanceof Error ? err : new Error(String(err));
+ } finally {
+ streamEnded = true;
+ wake();
+ }
+ });
+ };
+
+ stdout.on('data', enqueuePush);
+ stdout.on('end', enqueueFlush);
+ stdout.on('error', (err) => {
+ // Append onto the same chain so the error is surfaced strictly after any
+ // in-flight push finishes — late events still get a chance to land before
+ // the iterator throws.
+ pipelineQueue = pipelineQueue.then(() => {
+ streamError = err;
+ streamEnded = true;
+ wake();
+ });
+ });
+
+ const events: AsyncIterable<AgentStreamEvent> = {
+ [Symbol.asyncIterator]() {
+ return {
+ async next(): Promise<IteratorResult<AgentStreamEvent>> {
+ while (true) {
+ if (queue.length > 0) {
+ return { done: false, value: queue.shift()! };
+ }
+ if (streamError) throw streamError;
+ if (streamEnded) return { done: true, value: undefined };
+ await new Promise<void>((res) => {
+ wakeup = res;
+ });
+ }
+ },
+ };
+ },
+ };
+
+ 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,
+ kill: (signal: NodeJS.Signals = 'SIGINT') => killProcessTree(proc, signal),
+ pid: proc.pid,
+ stderr,
+ };
+};