π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): keep Claude Code stdin open so background tasks survive print mode (#21140)
Arvin Xu38f7b5ad48a6
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 28072ee9a22..166468a2117 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -859,7 +859,7 @@ describe('hetero exec command', () => {const call = mockSpawnAgent.mock.calls[0][0];expect(call.operationId).toBe('op-server-allocated');- expect(call.includePartialMessages).toBe(true);+ expect(call).toMatchObject({ includePartialMessages: true, liveInput: true });});it("echoes the run's operation and conversation into a server-ingest agent's env", async () => {diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex fcf57a7367e..ec225be15df 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -1257,30 +1257,33 @@ const exec = async (options: ExecOptions): Promise<void> => {// response must not overwrite the model selected by `initialModel`.const permissionMode = options.type === 'devin' ? 'bypass' : undefined;+ const spawnOptions = {+ agentType: options.type,+ askUserBridge: askBridge,+ command: resolvedCommand.command,+ cwd: options.cwd || process.cwd(),+ detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',+ env: commandEnv,+ extraArgs,+ // Device and sandbox executions are observed through the same gateway+ // stream as native server agents. Ask Claude Code for content-block+ // deltas so the current conversation receives text while the process is+ // running instead of seeing only the terminal assistant snapshot.+ includePartialMessages: options.type === 'claude-code',+ initialModel:+ options.type === 'droid' || options.type === 'devin' || options.type === 'trae'+ ? options.model+ : undefined,+ // Keep Claude Code's stdin open while it can still use input: closing it+ // early makes print mode kill background tasks after 10 minutes.+ liveInput: options.type === 'claude-code',+ operationId,+ permissionMode,+ uploadImage,+ };+const first = await runOneAgent(- {- agentType: options.type,- askUserBridge: askBridge,- command: resolvedCommand.command,- cwd: options.cwd || process.cwd(),- detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',- env: commandEnv,- extraArgs,- permissionMode,- // Device and sandbox executions are observed through the same gateway- // stream as native server agents. Ask Claude Code for content-block- // deltas so the current conversation receives text while the process is- // running instead of seeing only the terminal assistant snapshot.- includePartialMessages: options.type === 'claude-code',- initialModel:- options.type === 'droid' || options.type === 'devin' || options.type === 'trae'- ? options.model- : undefined,- operationId,- prompt: resolved.prompt,- resumeSessionId: options.resume,- uploadImage,- },+ { ...spawnOptions, prompt: resolved.prompt, resumeSessionId: options.resume },interceptResume,'attempt-1',);@@ -1302,25 +1305,8 @@ const exec = async (options: ExecOptions): Promise<void> => {if (!first.cancelled && !first.ingestError && first.resumeNotFound) {log.info('Resume failed (session not found or context overflow) β retrying without --resume');result = await runOneAgent(- {- agentType: options.type,- askUserBridge: askBridge,- command: resolvedCommand.command,- cwd: options.cwd || process.cwd(),- detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',- env: commandEnv,- extraArgs,- includePartialMessages: options.type === 'claude-code',- initialModel:- options.type === 'droid' || options.type === 'devin' || options.type === 'trae'- ? options.model- : undefined,- operationId,- permissionMode,- prompt: resolved.resumeFallbackPrompt ?? resolved.prompt,- uploadImage,- // No resumeSessionId β start fresh- },+ // No resumeSessionId β start fresh+ { ...spawnOptions, prompt: resolved.resumeFallbackPrompt ?? resolved.prompt },false, // no need to intercept resume errors on a fresh run'attempt-2-noresume',);diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.tsnew file mode 100644index 00000000000..e43dfcd7987--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.liveInput.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from 'vitest';++import { ClaudeCodeAdapter } from './claudeCode';++const init = {+ model: 'claude-sonnet-4-6',+ session_id: 'sess_1',+ subtype: 'init',+ type: 'system',+};+const messageStart = (id: string) => ({+ event: { message: { id, model: 'claude-sonnet-4-6' }, type: 'message_start' },+ type: 'stream_event',+});+const newStepOf = (events: any[]) =>+ events.find((event) => event.type === 'stream_start' && event.data?.newStep);++describe('ClaudeCodeAdapter live input', () => {+ it('opens the turn after a delivered user message as a user turn while a background task runs', () => {+ const adapter = new ClaudeCodeAdapter({+ runtimeEndStrategy: 'on-transport-close',+ signalBackgroundTaskCompletion: true,+ });+ adapter.adapt(init);+ adapter.adapt({+ message: {+ content: [+ {+ id: 'toolu_agent',+ input: { run_in_background: true },+ name: 'Agent',+ type: 'tool_use',+ },+ ],+ id: 'msg_01',+ },+ type: 'assistant',+ });+ adapter.adapt({+ session_id: 'sess_1',+ subtype: 'task_started',+ task_id: 'task_1',+ tool_use_id: 'toolu_agent',+ type: 'system',+ });+ adapter.adapt({+ message: {+ content: [{ content: 'launched', tool_use_id: 'toolu_agent', type: 'tool_result' }],+ },+ type: 'user',+ });+ adapter.adapt(messageStart('msg_02'));+ adapter.adapt({ is_error: false, result: 'launched', subtype: 'success', type: 'result' });++ // The host delivers a message; Claude Code replays it and answers it.+ expect(+ adapter.adapt({+ isReplay: true,+ message: { content: [{ text: 'also open the PRs', type: 'text' }], role: 'user' },+ type: 'user',+ uuid: 'u-2',+ }),+ ).toEqual([]);+ const reply = newStepOf(adapter.adapt(messageStart('msg_03')));++ expect(reply).toBeDefined();+ expect(reply.data.externalSignal).toBeUndefined();+ });++ it('keeps the reply to a delivered message out of a task completion that lands after the replay', () => {+ const adapter = new ClaudeCodeAdapter({+ runtimeEndStrategy: 'on-transport-close',+ signalBackgroundTaskCompletion: true,+ });+ adapter.adapt(init);+ adapter.adapt({+ message: {+ content: [+ {+ id: 'toolu_bash',+ input: { command: 'sleep 1', run_in_background: true },+ name: 'Bash',+ type: 'tool_use',+ },+ ],+ id: 'msg_01',+ },+ type: 'assistant',+ });+ adapter.adapt({+ session_id: 'sess_1',+ subtype: 'task_started',+ task_id: 'task_1',+ tool_use_id: 'toolu_bash',+ type: 'system',+ });+ adapter.adapt({+ message: {+ content: [{ content: 'started', tool_use_id: 'toolu_bash', type: 'tool_result' }],+ },+ type: 'user',+ });+ adapter.adapt(messageStart('msg_02'));+ adapter.adapt({ is_error: false, result: 'started', subtype: 'success', type: 'result' });++ // Replay β task notification β the user's turn (anthropics/claude-code#39632).+ adapter.adapt({+ isReplay: true,+ message: { content: [{ text: 'what next?', type: 'text' }], role: 'user' },+ type: 'user',+ uuid: 'u-2',+ });+ adapter.adapt({+ session_id: 'sess_1',+ subtype: 'task_notification',+ task_id: 'task_1',+ type: 'system',+ });+ const reply = newStepOf(adapter.adapt(messageStart('msg_03')));++ expect(reply.data.externalSignal).toBeUndefined();+ });++ it('still tags a turn the background task opens without user input', () => {+ const adapter = new ClaudeCodeAdapter({+ runtimeEndStrategy: 'on-transport-close',+ signalBackgroundTaskCompletion: true,+ });+ adapter.adapt(init);+ adapter.adapt({+ message: {+ content: [{ id: 'toolu_mon', input: {}, name: 'Monitor', type: 'tool_use' }],+ id: 'msg_01',+ },+ type: 'assistant',+ });+ adapter.adapt({+ session_id: 'sess_1',+ subtype: 'task_started',+ task_id: 'task_1',+ tool_use_id: 'toolu_mon',+ type: 'system',+ });+ adapter.adapt({+ message: { content: [{ content: 'started', tool_use_id: 'toolu_mon', type: 'tool_result' }] },+ type: 'user',+ });+ adapter.adapt(messageStart('msg_02'));++ const callback = newStepOf(adapter.adapt(messageStart('msg_03')));++ expect(callback.data.externalSignal).toMatchObject({ sourceToolCallId: 'toolu_mon' });+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 5968f864f12..5d871d4c46e 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from './claudeCode';+import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from '.';describe('ClaudeCodeAdapter', () => {describe('run cost', () => {diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 19d94fd7b23..e9dbc0ce7f5 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -1871,6 +1871,14 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {* not main-agent-scoped).*/private handleUser(raw: any): HeterogeneousAgentEvent[] {+ // A replayed user message (`--replay-user-messages`) is input the host+ // delivered into a live session: the turn it opens answers the user, not a+ // background task β even if a task notification lands before it opens.+ if (raw.isReplay && !raw.parent_tool_use_id) {+ this.hasUnhandledUserInput = true;+ return [];+ }+const content = raw.message?.content;if (!Array.isArray(content)) return [];@@ -2188,10 +2196,10 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {this.lastApiErrorText = undefined;this.streamedTextByMessageId.clear();this.streamedThinkingByMessageId.clear();- // Drop any unconsumed task-completion lineage so the next LLM run- // doesn't inherit it (e.g. a follow-up user turn would otherwise- // wrongly inherit the previous run's task-completion tag).+ // Drop any unconsumed task-completion lineage so the next LLM run doesn't+ // inherit it; the next turn follows no tool_result of this one either.this.pendingTaskCompletion = undefined;+ this.hasUnhandledUserInput = false;const shouldEmitVisibleOutputEnd =this.options.runtimeEndStrategy === 'on-result' || this.activeTasks.size === 0;@@ -2390,7 +2398,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {sourceToolName: task.sourceToolName,type: 'tool-stdout',};- } else if (this.pendingTaskCompletion) {+ } else if (this.pendingTaskCompletion && !this.hasUnhandledUserInput) {// Natural turn that follows a `task_notification` β this is the// post-task summary. Tag it with the source-tool lineage so the// collector keeps it inside the same AssistantGroup as the@@ -2463,12 +2471,3 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {}export class ClaudeCodeAdapter extends ClaudeCompatibleStreamAdapter {}--export class ClaudeCodeSdkAdapter extends ClaudeCodeAdapter {- constructor() {- super({- runtimeEndStrategy: 'on-transport-close',- signalBackgroundTaskCompletion: true,- });- }-}diff --git a/packages/heterogeneous-agents/src/adapters/claudeCodeSdk.ts b/packages/heterogeneous-agents/src/adapters/claudeCodeSdk.tsnew file mode 100644index 00000000000..764a6db5666--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/claudeCodeSdk.ts@@ -0,0 +1,14 @@+import { ClaudeCodeAdapter } from './claudeCode';++/**+ * Claude Code over the Agent SDK transport. One Query can report several+ * `result`s, so runtime end comes from the transport closing.+ */+export class ClaudeCodeSdkAdapter extends ClaudeCodeAdapter {+ constructor() {+ super({+ runtimeEndStrategy: 'on-transport-close',+ signalBackgroundTaskCompletion: true,+ });+ }+}diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex ded292cb171..a2e48236fc8 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -1,5 +1,6 @@export { AmpAdapter } from './amp';-export { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from './claudeCode';+export { ClaudeCodeAdapter } from './claudeCode';+export { ClaudeCodeSdkAdapter } from './claudeCodeSdk';export { CodeBuddyAdapter } from './codeBuddy';export { CodexAdapter } from './codex';export { CodexAppServerAdapter } from './codexAppServer';diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.tsindex 3682924e8b6..331037ff17a 100644--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts@@ -32,6 +32,8 @@ export type UploadHeterogeneousImage = (image: {}) => Promise<{ fileId: string; url: string } | undefined>;export interface AgentStreamPipelineOptions {+ /** Adapter to use instead of the registered one for `agentType`. */+ adapter?: AgentEventAdapter;/** Agent type key (e.g. `claude-code`, `codex`). */agentType: string;/** Working directory used to resolve relative file paths emitted by CLI tools. */@@ -80,7 +82,7 @@ export class AgentStreamPipeline {private queuedEvents: AgentStreamEvent[] = [];constructor(options: AgentStreamPipelineOptions) {- this.adapter = createAdapter(options.agentType);+ this.adapter = options.adapter ?? createAdapter(options.agentType);this.agentType = options.agentType;this.readCodexImages = createCodexImageOutputReader({env: options.env ?? process.env,diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.tsnew file mode 100644index 00000000000..1b174d0d5b3--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts@@ -0,0 +1,239 @@+import { PassThrough } from 'node:stream';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { ClaudeCodeLiveInput } from './claudeCodeLiveInput';++const userLine = (text: string) =>+ `${JSON.stringify({ message: { content: [{ text, type: 'text' }], role: 'user' }, type: 'user' })}\n`;++const line = (message: Record<string, unknown>) => `${JSON.stringify(message)}\n`;++const setup = (options?: { idleCloseMs?: number }) => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ const ended = vi.fn();+ stdin.on('finish', ended);+ const live = new ClaudeCodeLiveInput(stdin, options);+ return { ended, live, written };+};++const flush = () => new Promise<void>((resolve) => setImmediate(resolve));++describe('ClaudeCodeLiveInput', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('stamps each delivered message with the uuid it is replayed under', async () => {+ const { live, written } = setup();++ expect(live.send(userLine('first'), 'u-1')).toBe(true);+ await flush();++ expect(written).toEqual([+ {+ message: { content: [{ text: 'first', type: 'text' }], role: 'user' },+ type: 'user',+ uuid: 'u-1',+ },+ ]);+ });++ it('closes stdin at the first result when nothing else can still take input', async () => {+ const { ended, live } = setup();+ live.send(userLine('first'), 'u-1');++ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ type: 'assistant' }));+ live.observe(line({ subtype: 'success', type: 'result' }));+ await flush();++ expect(live.isOpen).toBe(false);+ expect(live.lastTurn).toEqual({ aborted: false, terminalReason: undefined });+ expect(ended).toHaveBeenCalled();+ });++ it('keeps stdin open past the result while a background task runs', () => {+ const { live } = setup();+ live.send(userLine('first'), 'u-1');++ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));+ expect(live.isOpen).toBe(true);++ // Print mode still runs the notification turn after stdin closes.+ live.observe(line({ subtype: 'task_notification', task_id: 't-1', type: 'system' }));+ expect(live.isOpen).toBe(false);+ });++ it('holds stdin through a turn in which the last task ends, closing at its result', () => {+ const { live } = setup();+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));++ live.observe(line({ subtype: 'task_notification', task_id: 't-1', type: 'system' }));+ expect(live.isOpen).toBe(true);+ live.observe(line({ subtype: 'success', type: 'result' }));++ expect(live.isOpen).toBe(false);+ });++ it('closes when the last background task ends between turns', () => {+ const { live } = setup();+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));++ live.observe(+ line({+ patch: { status: 'killed' },+ subtype: 'task_updated',+ task_id: 't-1',+ type: 'system',+ }),+ );++ expect(live.isOpen).toBe(false);+ });++ it('waits for a message delivered mid-turn to be picked up before closing', () => {+ const { live } = setup();+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));++ expect(live.send(userLine('interjection'), 'u-2')).toBe(true);+ live.observe(line({ subtype: 'success', type: 'result' }));+ expect(live.isOpen).toBe(true);++ // Claude Code starts a turn for the pending message.+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-2' }));+ live.observe(line({ subtype: 'success', type: 'result' }));+ expect(live.isOpen).toBe(false);+ });++ it('closes on a failed turn even while a task runs, but not on an interrupted one', () => {+ const failed = setup();+ failed.live.send(userLine('first'), 'u-1');+ failed.live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ failed.live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ failed.live.observe(+ line({ is_error: true, subtype: 'error_during_execution', type: 'result' }),+ );+ expect(failed.live.isOpen).toBe(false);++ const interrupted = setup();+ interrupted.live.send(userLine('first'), 'u-1');+ interrupted.live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ interrupted.live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ interrupted.live.observe(+ line({ is_error: true, terminal_reason: 'aborted_streaming', type: 'result' }),+ );+ expect(interrupted.live.isOpen).toBe(true);+ });++ it('rejects input after close so the caller can fall back to a new turn', async () => {+ const { live, written } = setup();+ live.close();+ await flush();++ expect(live.send(userLine('late'))).toBe(false);+ expect(live.interrupt()).toBe(false);+ expect(written).toEqual([]);+ });++ it('interrupts the current turn with a control request instead of a signal', async () => {+ const { live, written } = setup();++ expect(live.interrupt()).toBe(true);+ await flush();++ expect(written).toEqual([+ {+ request: { subtype: 'interrupt' },+ request_id: expect.any(String),+ type: 'control_request',+ },+ ]);+ expect(live.isOpen).toBe(true);+ });++ it('closes stdin after a silent stretch between turns so a stuck task cannot hold it open', () => {+ vi.useFakeTimers();+ const { live } = setup({ idleCloseMs: 1000 });+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));++ vi.advanceTimersByTime(999);+ expect(live.isOpen).toBe(true);+ vi.advanceTimersByTime(1);+ expect(live.isOpen).toBe(false);+ });++ it('treats sub-agent output as background activity that keeps the idle timer fresh', () => {+ vi.useFakeTimers();+ const { live } = setup({ idleCloseMs: 1000 });+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));++ vi.advanceTimersByTime(800);+ live.observe(line({ parent_tool_use_id: 'tu-agent', type: 'assistant' }));+ vi.advanceTimersByTime(800);+ expect(live.isOpen).toBe(true);++ // A task the sub-agent starts still holds the session open.+ live.observe(+ line({+ parent_tool_use_id: 'tu-agent',+ subtype: 'task_started',+ task_id: 't-2',+ type: 'system',+ }),+ );+ live.observe(line({ subtype: 'task_notification', task_id: 't-2', type: 'system' }));+ expect(live.isOpen).toBe(true);++ // The sub-agent opened no main turn, so its end leaves the session idle.+ live.observe(line({ subtype: 'task_notification', task_id: 't-1', type: 'system' }));+ expect(live.isOpen).toBe(false);+ });++ it('does not let the idle timer fire during a main turn', () => {+ vi.useFakeTimers();+ const { live } = setup({ idleCloseMs: 1000 });+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));++ vi.advanceTimersByTime(500);+ live.observe(line({ subtype: 'init', type: 'system' }));+ vi.advanceTimersByTime(5000);++ expect(live.isOpen).toBe(true);+ });++ it('parses messages split across stdout chunks', () => {+ const { live } = setup();+ live.send(userLine('first'), 'u-1');+ const replay = line({ isReplay: true, type: 'user', uuid: 'u-1' });+ const result = line({ subtype: 'success', type: 'result' });++ live.observe(replay.slice(0, 10));+ live.observe(replay.slice(10) + result.slice(0, 5));+ expect(live.isOpen).toBe(true);+ live.observe(result.slice(5));++ expect(live.isOpen).toBe(false);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.tsnew file mode 100644index 00000000000..217be8a7da4--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts@@ -0,0 +1,236 @@+import { randomUUID } from 'node:crypto';+import type { Writable } from 'node:stream';++/**+ * How long the session may sit between turns with no stdout before stdin is+ * closed anyway. Background tasks that stream (sub-agents) keep resetting it;+ * a silent one (a long background shell) would otherwise hold the process open+ * forever, since Claude Code's own wind-down ceiling only starts once stdin is+ * closed.+ */+const DEFAULT_IDLE_CLOSE_MS = 30 * 60 * 1000;++const TERMINAL_TASK_STATUSES = new Set(['completed', 'failed', 'killed']);++const readIdleCloseMs = (): number => {+ const value = Number(process.env.LOBE_CLAUDE_CODE_LIVE_INPUT_IDLE_MS);+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_IDLE_CLOSE_MS;+};++/** Stamp a stream-json `user` line with the uuid Claude Code replays it under. */+export const withUserMessageUuid = (stdinLine: string, uuid: string): string =>+ `${JSON.stringify({ ...JSON.parse(stdinLine), uuid })}\n`;++/** How the session's most recent turn ended. */+export interface ClaudeCodeTurnOutcome {+ /** The turn was stopped by an interrupt (`terminal_reason: aborted_*`), not failed. */+ aborted: boolean;+ terminalReason?: string;+}++const isAbortedResult = (message: any): boolean =>+ !!message.is_error && String(message.terminal_reason ?? '').startsWith('aborted');++export interface ClaudeCodeLiveInputOptions {+ idleCloseMs?: number;+}++/**+ * Keeps a Claude Code print-mode (`-p --input-format stream-json`) stdin open+ * for as long as the run can still use input, so the host can deliver a user+ * message into the running session or interrupt only the current turn.+ *+ * Closing stdin early is not neutral: once input is closed, print mode stops+ * waiting for background tasks after `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`+ * (10 minutes by default) and kills them. So stdin stays open until the session+ * is between turns with no running task and no delivered message it has not+ * picked up yet. A notification for a task that finished during the last turn+ * is still delivered after the close, because print mode drains those itself.+ *+ * Requires `--replay-user-messages`: the replayed `uuid` is how a delivered+ * message is known to have been picked up.+ */+export class ClaudeCodeLiveInput {+ private readonly activeTasks = new Set<string>();+ private closed = false;+ private idleTimer: NodeJS.Timeout | undefined;+ private readonly idleCloseMs: number;+ private lastOutcome: ClaudeCodeTurnOutcome | undefined;+ private lineBuffer = '';+ private turnOpen = true;+ private readonly unconsumed = new Set<string>();++ constructor(+ private readonly stdin: Writable,+ options: ClaudeCodeLiveInputOptions = {},+ ) {+ this.idleCloseMs = options.idleCloseMs ?? readIdleCloseMs();+ stdin.on('error', () => this.markClosed());+ stdin.on('close', () => this.markClosed());+ }++ get isOpen(): boolean {+ return !this.closed;+ }++ /** How the last turn ended; undefined while the session has not finished one. */+ get lastTurn(): ClaudeCodeTurnOutcome | undefined {+ return this.lastOutcome;+ }++ /**+ * Deliver a `user` line into the session; it stays pending until Claude Code+ * replays it. Returns false once input has closed.+ */+ send(stdinLine: string, uuid: string = randomUUID()): boolean {+ if (this.closed) return false;++ this.unconsumed.add(uuid);+ this.clearIdleTimer();+ this.stdin.write(withUserMessageUuid(stdinLine, uuid));+ return true;+ }++ /** Stop the current turn without ending the process. Returns false once input has closed. */+ interrupt(): boolean {+ if (this.closed) return false;++ this.stdin.write(+ `${JSON.stringify({+ request: { subtype: 'interrupt' },+ request_id: randomUUID(),+ type: 'control_request',+ })}\n`,+ );+ return true;+ }++ /** Feed raw stdout so the session state tracks what Claude Code reports. */+ observe(chunk: Buffer | string): void {+ this.lineBuffer += chunk.toString();+ const lines = this.lineBuffer.split('\n');+ this.lineBuffer = lines.pop() ?? '';++ for (const line of lines) {+ if (!line.trim()) continue;+ try {+ const message = JSON.parse(line);+ if (message?.type === 'result') {+ this.lastOutcome = {+ aborted: isAbortedResult(message),+ terminalReason: message.terminal_reason,+ };+ }+ // Turns still run after input closes, so keep tracking them.+ this.observeMessage(message);+ } catch {+ // Non-JSON noise on stdout carries no session state.+ }+ }++ // The idle clock only runs between turns; any output then, a sub-agent's+ // included, restarts it.+ if (this.closed) return;+ if (this.turnOpen) this.clearIdleTimer();+ else this.armIdleTimer();+ }++ /**+ * stdout ended: take a final record left without a trailing newline, then+ * close input, since nothing can read it any more.+ */+ finish(): void {+ if (this.lineBuffer.trim()) this.observe('\n');+ this.close();+ }++ close(): void {+ if (this.closed) return;++ this.markClosed();+ this.stdin.end();+ }++ private observeMessage(message: any): void {+ // A background sub-agent's turn records are activity of its task, not a+ // main turn: they must not hold the session open once the task ends. Its+ // task lifecycle (`system`) still counts.+ if (message?.parent_tool_use_id && message.type !== 'system') return;++ switch (message?.type) {+ case 'user': {+ if (message.isReplay && typeof message.uuid === 'string') {+ this.unconsumed.delete(message.uuid);+ this.openTurn();+ }+ return;+ }+ case 'assistant':+ case 'stream_event': {+ this.openTurn();+ return;+ }+ case 'system': {+ this.observeSystem(message);+ return;+ }+ case 'result': {+ this.turnOpen = false;+ // A failed turn ends the run for the host, so nothing would read later+ // input. An interrupt the host sent reports `aborted_*` and is not one.+ if (message.is_error && !isAbortedResult(message)) this.close();+ else this.closeIfIdle();+ return;+ }+ }+ }++ private observeSystem(message: any): void {+ if (message.subtype === 'init') {+ this.openTurn();+ return;+ }+ if (message.subtype === 'task_started' && message.task_id) {+ this.activeTasks.add(message.task_id);+ return;+ }++ const ended =+ message.subtype === 'task_notification' ||+ (message.subtype === 'task_updated' &&+ TERMINAL_TASK_STATUSES.has(message.patch?.status as string));+ if (ended && message.task_id) {+ this.activeTasks.delete(message.task_id);+ this.closeIfIdle();+ }+ }++ /** A newer turn supersedes how the last one ended until it reports its own. */+ private openTurn(): void {+ this.turnOpen = true;+ this.lastOutcome = undefined;+ }++ private closeIfIdle(): void {+ if (this.turnOpen || this.activeTasks.size > 0 || this.unconsumed.size > 0) return;+ this.close();+ }++ private armIdleTimer(): void {+ this.clearIdleTimer();+ this.idleTimer = setTimeout(() => this.close(), this.idleCloseMs);+ this.idleTimer.unref?.();+ }++ private clearIdleTimer(): void {+ if (!this.idleTimer) return;++ clearTimeout(this.idleTimer);+ this.idleTimer = undefined;+ }++ private markClosed(): void {+ this.closed = true;+ this.clearIdleTimer();+ }+}diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.liveInput.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.liveInput.test.tsnew file mode 100644index 00000000000..41522dec731--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.liveInput.test.ts@@ -0,0 +1,393 @@+import type * as childProcess from 'node:child_process';+import { EventEmitter } from 'node:events';+import type * as os from 'node:os';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { spawnAgent } from './spawnAgent';++const spawnCalls: Array<{ args: string[]; command: string }> = [];+let nextFakeProc: any = null;++vi.mock('node:child_process', async () => {+ const actual = await vi.importActual<typeof childProcess>('node:child_process');+ return {+ ...actual,+ spawn: vi.fn((command: string, args: string[]) => {+ spawnCalls.push({ args, command });+ return nextFakeProc;+ }),+ };+});++vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'linux') };+});++const line = (message: Record<string, unknown>) => `${JSON.stringify(message)}\n`;++const assistantText = (id: string, text: string) =>+ line({+ message: {+ content: [{ text, type: 'text' }],+ id,+ model: 'claude-sonnet-4-6',+ role: 'assistant',+ },+ type: 'assistant',+ });++/** A Claude Code child whose stdout the test drives and whose stdin it reads. */+const createLiveProc = () => {+ const proc = new EventEmitter() as any;+ const stdin = new PassThrough();+ const stdinLines: any[] = [];+ let stdinEnded = false;+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) stdinLines.push(JSON.parse(raw));+ });+ stdin.on('finish', () => {+ stdinEnded = true;+ });+ proc.stdin = stdin;+ proc.stdout = new PassThrough();+ proc.stderr = new PassThrough();+ proc.kill = vi.fn();+ proc.pid = 4321;++ return {+ emit: (chunk: string) => proc.stdout.write(chunk),+ exit: (code: number) => {+ proc.stdout.end();+ proc.stderr.end();+ proc.emit('exit', code, null);+ },+ proc,+ get stdinEnded() {+ return stdinEnded;+ },+ stdinLines,+ };+};++const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 10));++describe('spawnAgent live input (Claude Code)', () => {+ beforeEach(() => {+ spawnCalls.length = 0;+ });++ afterEach(() => {+ nextFakeProc = null;+ });++ it('delivers a mid-run message and reports runtime end once, at process exit', async () => {+ const fake = createLiveProc();+ nextFakeProc = fake.proc;++ const handle = await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-live',+ prompt: 'split the files',+ });+ const events: any[] = [];+ const drained = (async () => {+ for await (const event of handle.events) events.push(event);+ })();++ expect(spawnCalls[0].args).toContain('--replay-user-messages');+ await tick();+ const firstUuid = fake.stdinLines[0].uuid;+ expect(fake.stdinLines[0]).toMatchObject({+ message: { content: [{ text: 'split the files', type: 'text' }] },+ type: 'user',+ uuid: expect.any(String),+ });++ // First turn ends while a background agent is still running.+ fake.emit(+ line({ model: 'claude-sonnet-4-6', session_id: 'cc-1', subtype: 'init', type: 'system' }),+ );+ fake.emit(line({ isReplay: true, message: { content: [] }, type: 'user', uuid: firstUuid }));+ fake.emit(assistantText('msg_1', 'started the agents'));+ fake.emit(+ line({ subtype: 'task_started', task_id: 't-1', tool_use_id: 'tu-1', type: 'system' }),+ );+ fake.emit(line({ is_error: false, result: 'started', subtype: 'success', type: 'result' }));+ await tick();++ expect(fake.stdinEnded).toBe(false);+ expect(events.some((event) => event.type === 'agent_runtime_end')).toBe(false);++ await expect(handle.sendUserMessage!('also open the PRs', { uuid: 'u-2' })).resolves.toBe(true);+ await tick();+ expect(fake.stdinLines[1]).toMatchObject({+ message: { content: [{ text: 'also open the PRs', type: 'text' }] },+ uuid: 'u-2',+ });++ fake.emit(line({ isReplay: true, message: { content: [] }, type: 'user', uuid: 'u-2' }));+ fake.emit(assistantText('msg_2', 'will do'));+ fake.emit(line({ subtype: 'task_notification', task_id: 't-1', type: 'system' }));+ fake.emit(line({ is_error: false, result: 'done', subtype: 'success', type: 'result' }));+ await tick();++ expect(fake.stdinEnded).toBe(true);+ await expect(handle.sendUserMessage!('too late')).resolves.toBe(false);++ fake.exit(0);+ await drained;++ const runtimeEnds = events.filter((event) => event.type === 'agent_runtime_end');+ expect(runtimeEnds).toHaveLength(1);+ expect(events.at(-1)?.type).toBe('agent_runtime_end');+ });++ const runToExit = async (results: Record<string, unknown>[], exitCode: number) => {+ const fake = createLiveProc();+ nextFakeProc = fake.proc;+ const handle = await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-live',+ prompt: 'task',+ });+ const events: any[] = [];+ const drained = (async () => {+ for await (const event of handle.events) events.push(event);+ })();+ await tick();++ fake.emit(+ line({+ isReplay: true,+ message: { content: [] },+ type: 'user',+ uuid: fake.stdinLines[0].uuid,+ }),+ );+ for (const result of results) fake.emit(line({ type: 'result', ...result }));+ await tick();+ fake.exit(exitCode);+ await drained;+ return events.filter((event) => event.type === 'agent_runtime_end');+ };++ /** Ends stdout on a final record with no trailing newline. */+ const runToExitUnterminated = async (records: Record<string, unknown>[], exitCode: number) => {+ const fake = createLiveProc();+ nextFakeProc = fake.proc;+ const handle = await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-live',+ prompt: 'task',+ });+ const events: any[] = [];+ const drained = (async () => {+ for await (const event of handle.events) events.push(event);+ })();+ await tick();++ const uuid = fake.stdinLines[0].uuid;+ fake.emit(line({ isReplay: true, message: { content: [] }, type: 'user', uuid }));+ const body = records.map((record) => JSON.stringify(record)).join('\n');+ fake.emit(body);+ await tick();+ fake.exit(exitCode);+ await drained;+ return events;+ };++ it('completes a run whose final result has no trailing newline', async () => {+ const events = await runToExitUnterminated(+ [{ is_error: false, result: 'done', subtype: 'success', type: 'result' }],+ 0,+ );++ expect(events.filter((event) => event.type === 'agent_runtime_end')).toEqual([+ expect.objectContaining({ data: expect.objectContaining({ reason: 'complete' }) }),+ ]);+ });++ it('does not report completion when an unterminated final result is an error', async () => {+ const events = await runToExitUnterminated(+ [+ { is_error: false, result: 'first', subtype: 'success', type: 'result' },+ { is_error: true, result: 'API Error: 500 boom', subtype: 'success', type: 'result' },+ ],+ 0,+ );++ expect(events.some((event) => event.type === 'error')).toBe(true);+ expect(events.some((event) => event.type === 'agent_runtime_end')).toBe(false);+ });++ it('does not report completion when the CLI exits nonzero after a finished turn', async () => {+ await expect(+ runToExit([{ is_error: false, result: 'done', subtype: 'success' }], 1),+ ).resolves.toEqual([]);+ });++ // Print mode exits 1 after an interrupted last turn (observed with Claude Code 2.1.282).+ it.each([0, 1])(+ 'ends a run whose last turn was interrupted as interrupted, not complete (exit %i)',+ async (exitCode) => {+ const [end] = await runToExit(+ [+ {+ is_error: true,+ subtype: 'error_during_execution',+ terminal_reason: 'aborted_streaming',+ },+ ],+ exitCode,+ );++ expect(end.data).toMatchObject({+ kind: 'aborted',+ reason: 'interrupted',+ terminalReason: 'aborted_streaming',+ });+ },+ );++ it('does not report a stale interrupt when a later turn crashes before its result', async () => {+ await expect(+ runToExit(+ [+ {+ is_error: true,+ subtype: 'error_during_execution',+ terminal_reason: 'aborted_streaming',+ },+ // A background task's callback opens a new turn, then the CLI dies.+ { model: 'claude-sonnet-4-6', session_id: 'cc-1', subtype: 'init', type: 'system' },+ ],+ 1,+ ),+ ).resolves.toEqual([]);+ });++ it('completes when a turn after an interrupt finishes normally', async () => {+ const [end] = await runToExit(+ [+ { is_error: true, subtype: 'error_during_execution', terminal_reason: 'aborted_streaming' },+ { is_error: false, result: 'done', subtype: 'success' },+ ],+ 0,+ );++ expect(end.data).toMatchObject({ reason: 'complete' });+ });++ it('groups the summary after a background Bash completes under the tool that started it', async () => {+ const fake = createLiveProc();+ nextFakeProc = fake.proc;+ const handle = await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-live',+ prompt: 'run it in the background',+ });+ const events: any[] = [];+ const drained = (async () => {+ for await (const event of handle.events) events.push(event);+ })();+ await tick();++ fake.emit(+ line({ model: 'claude-sonnet-4-6', session_id: 'cc-1', subtype: 'init', type: 'system' }),+ );+ fake.emit(+ line({+ message: {+ content: [+ {+ id: 'toolu_bash',+ input: { command: 'sleep 1 && echo done', run_in_background: true },+ name: 'Bash',+ type: 'tool_use',+ },+ ],+ id: 'msg_01',+ },+ type: 'assistant',+ }),+ );+ fake.emit(+ line({ subtype: 'task_started', task_id: 't-1', tool_use_id: 'toolu_bash', type: 'system' }),+ );+ fake.emit(+ line({+ message: {+ content: [{ content: 'started', tool_use_id: 'toolu_bash', type: 'tool_result' }],+ },+ type: 'user',+ }),+ );+ fake.emit(line({ is_error: false, result: 'started', subtype: 'success', type: 'result' }));+ fake.emit(line({ subtype: 'task_notification', task_id: 't-1', type: 'system' }));+ fake.emit(+ line({+ event: { message: { id: 'msg_02', model: 'claude-sonnet-4-6' }, type: 'message_start' },+ type: 'stream_event',+ }),+ );+ await tick();+ fake.exit(0);+ await drained;++ const summary = events.find(+ (event) => event.type === 'stream_start' && event.data?.messageId === 'msg_02',+ );+ expect(summary?.data.externalSignal).toEqual({+ sourceToolCallId: 'toolu_bash',+ sourceToolName: 'Bash',+ type: 'task-completion',+ });+ });++ it('interrupts only the current turn through a control request', async () => {+ const fake = createLiveProc();+ nextFakeProc = fake.proc;++ const handle = await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-live',+ prompt: 'long task',+ });++ expect(handle.interruptTurn!()).toBe(true);+ await tick();++ expect(fake.stdinLines[1]).toMatchObject({+ request: { subtype: 'interrupt' },+ type: 'control_request',+ });+ expect(fake.proc.kill).not.toHaveBeenCalled();+ fake.exit(0);+ });++ it('leaves non-live runs with one-shot stdin and no live controls', async () => {+ const fake = createLiveProc();+ nextFakeProc = fake.proc;++ const handle = await spawnAgent({+ agentType: 'claude-code',+ operationId: 'op-once',+ prompt: 'once',+ });+ await tick();++ expect(spawnCalls[0].args).not.toContain('--replay-user-messages');+ expect(fake.stdinEnded).toBe(true);+ expect(handle.sendUserMessage).toBeUndefined();+ expect(handle.interruptTurn).toBeUndefined();+ fake.exit(0);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex fb4a1de7baa..23e4de93540 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -6,9 +6,11 @@ import { PassThrough } from 'node:stream';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { spawnManaged } from '@lobechat/utils/managedProcess';+import { ClaudeCodeAdapter } from '../adapters/claudeCode';import type { AskUserBridge } from '../askUser/AskUserBridge';import { resolveHeterogeneousAgentCommand } from '../config';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';+import { ClaudeCodeLiveInput } from './claudeCodeLiveInput';import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';@@ -55,6 +57,12 @@ export interface SpawnAgentOptions {* plain string this is unused.*/inputOptions?: BuildAgentInputOptions;+ /**+ * (Claude Code only) Keep stdin open while the session can still use input,+ * exposing `sendUserMessage` / `interruptTurn` on the handle. Runtime end is+ * then reported once at process exit instead of at every `result`.+ */+ liveInput?: boolean;/*** Optional tee for the child's RAW stdout bytes, invoked synchronously for* every chunk BEFORE the adapter sees it. The pipeline still consumes stdout@@ -116,6 +124,11 @@ export interface SpawnAgentHandle {* grace timeout. SIGKILL remains a host-requested force-kill escalation.*/interrupt?: (signal?: NodeJS.Signals) => void;+ /**+ * (Claude Code `liveInput` only) Stop the current turn without ending the+ * process, so background tasks keep running. False once input has closed.+ */+ interruptTurn?: () => boolean;/*** Send a signal to the child. A dedicated Unix process group is signaled as* a tree; inherited-group children receive a direct signal because their@@ -124,6 +137,13 @@ export interface SpawnAgentHandle {kill: (signal?: NodeJS.Signals) => void;/** Spawned child PID, undefined if spawn failed pre-PID. */pid: number | undefined;+ /**+ * (Claude Code `liveInput` only) Deliver a user message into the running+ * session; Claude Code reads it at its next tool boundary, or starts a turn+ * for it when idle. Resolves false once input has closed β the caller then+ * runs the message as a new turn instead.+ */+ sendUserMessage?: (prompt: AgentPromptInput, options?: { uuid?: string }) => Promise<boolean>;/*** The agent's native session id, extracted from the `system:init` event.* Available after the `events` async iterable has been fully consumed.@@ -247,6 +267,8 @@ interface BuildSpawnArgsParams {includePartialMessages: boolean;/** Per-agent input args produced by `buildAgentInput` (e.g. Codex `--image`). */inputArgs: string[];+ /** (Claude Code only) Replay consumed user messages for live input. */+ liveInput?: boolean;/** Native session id for resume; undefined for fresh runs. */resumeSessionId: string | undefined;}@@ -255,10 +277,12 @@ const buildClaudeCodeArgs = ({extraArgs,includePartialMessages,inputArgs,+ liveInput,resumeSessionId,}: BuildSpawnArgsParams) => [...CLAUDE_CODE_BASE_ARGS,...(includePartialMessages ? ['--include-partial-messages'] : []),+ ...(liveInput ? ['--replay-user-messages'] : []),...CLAUDE_CODE_PERMISSION_ARGS(),...(resumeSessionId ? ['--resume', resumeSessionId] : []),...inputArgs,@@ -703,11 +727,13 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent}const inputPlan = await buildAgentInput(options.agentType, options.prompt, options.inputOptions);+ const liveInput = options.agentType === 'claude-code' && options.liveInput === true;const args = buildSpawnArgs({agentType: options.agentType,extraArgs: options.extraArgs ?? [],includePartialMessages: options.includePartialMessages ?? false,inputArgs: inputPlan.args,+ liveInput,resumeSessionId: options.resumeSessionId,});const childEnv: NodeJS.ProcessEnv = {@@ -747,6 +773,15 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent});const pipeline = new AgentStreamPipeline({+ // A live session can run more turns after its first `result`, so the+ // runtime ends once, at process exit, and the turn a background task's+ // completion opens is grouped under the tool that started it.+ adapter: liveInput+ ? new ClaudeCodeAdapter({+ runtimeEndStrategy: 'on-transport-close',+ signalBackgroundTaskCompletion: true,+ })+ : undefined,agentType: options.agentType,cwd,env: childEnv,@@ -766,6 +801,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent// dependency.const queue: AgentStreamEvent[] = [];let killedByUs = false;+ let sawErrorEvent = false;let streamEnded = false;let streamError: Error | undefined;let wakeup: (() => void) | undefined;@@ -794,7 +830,10 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent},);- if (proc.stdin) {+ const live = liveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : undefined;+ if (live) {+ live.send(inputPlan.stdin);+ } else if (proc.stdin) {proc.stdin.write(inputPlan.stdin, () => {proc.stdin?.end();});@@ -815,6 +854,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentpipelineQueue = pipelineQueue.then(async () => {try {const events = await pipeline.push(chunk);+ sawErrorEvent ||= events.some((event) => event.type === 'error');for (const event of events) queue.push(event);wake();} catch (err) {@@ -829,10 +869,23 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentpipelineQueue = pipelineQueue.then(async () => {try {const events = await pipeline.flush();+ live?.finish();+ const { code, signal } = await exit;+ if (code === 0 && !killedByUs) events.push(...pipeline.validateCompletion());+ sawErrorEvent ||= events.some((event) => event.type === 'error');for (const event of events) queue.push(event);- const { code } = await exit;- if (code === 0 && !killedByUs) {- for (const event of pipeline.validateCompletion()) queue.push(event);+ // Only a clean exit after a finished turn ends the run here: a crash+ // after a result is a failure, not a completion. Print mode exits 1+ // when its last turn was an error result, which an interrupt is.+ const lastTurn = live?.lastTurn;+ const cleanExit =+ code === 0 || (lastTurn?.aborted === true && code === 1 && signal === null);+ if (lastTurn && cleanExit && !killedByUs && !sawErrorEvent) {+ const end = lastTurn.aborted+ ? { kind: 'aborted', reason: 'interrupted', terminalReason: lastTurn.terminalReason }+ : { reason: 'complete' };+ for (const event of pipeline.completeRuntime({ ...end, transport: 'cli-live' }))+ queue.push(event);}// Kimi Code reports usage only via its on-disk session wire log, so// it can only be collected now that the process has exited. The hook@@ -860,6 +913,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent// raw dump is diagnostic-only; never let it disrupt the run}}+ live?.observe(chunk);enqueuePush(chunk);});stdout.on('end', enqueueFlush);@@ -896,8 +950,17 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentreturn {events,exit,+ ...(live && {+ interruptTurn: () => live.interrupt(),+ sendUserMessage: async (prompt: AgentPromptInput, sendOptions?: { uuid?: string }) => {+ if (!live.isOpen) return false;+ const plan = await buildAgentInput('claude-code', prompt, options.inputOptions);+ return live.send(plan.stdin, sendOptions?.uuid);+ },+ }),kill: (signal: NodeJS.Signals = 'SIGINT') => {killedByUs = true;+ live?.close();killProcessTree(proc, signal, detached);},pid: proc.pid,