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(cli): make `lh agent run` always exit, with a status that matches the run (#20389)

Arvin Xue6da6aadc0b5
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index af3da3feb31..2b38e566866 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -696,7 +696,12 @@ describe('agent command', () => {
expect(mockStreamAgentEvents).toHaveBeenCalledWith(
'https://example.com/api/agent/stream?operationId=op-sse',
expect.objectContaining({ 'Oidc-Auth': 'test-token' }),
- expect.objectContaining({ json: undefined, verbose: undefined }),
+ expect.objectContaining({
+ json: undefined,
+ // the SSE stream gets the same quiet-window status probe as WebSocket
+ onStall: expect.any(Function),
+ verbose: undefined,
+ }),
);
expect(mockStreamAgentEventsViaWebSocket).not.toHaveBeenCalled();
});
@@ -1143,6 +1148,323 @@ describe('agent command', () => {
});
});
+ describe('run outcome and exit status (#19543 #19613 #19614 #19615)', () => {
+ let errorSpy: ReturnType<typeof vi.spyOn>;
+ let warnSpy: ReturnType<typeof vi.spyOn>;
+ let infoSpy: ReturnType<typeof vi.spyOn>;
+ let stderrSpy: ReturnType<typeof vi.spyOn>;
+
+ const envelope = (status: string, extra: Record<string, unknown> = {}) => ({
+ currentState: { status, stepCount: 3, ...extra },
+ hasError: status === 'error',
+ isActive: !['done', 'error', 'interrupted'].includes(status),
+ isCompleted: ['done', 'error', 'interrupted'].includes(status),
+ metadata: {},
+ needsHumanInput: status === 'waiting_for_human',
+ operationId: 'op-run',
+ stats: { totalSteps: 3 },
+ });
+
+ const run = async (...extra: string[]) => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'run',
+ '--agent-id',
+ 'a1',
+ '--prompt',
+ 'Hello',
+ ...extra,
+ ]);
+ };
+
+ /** Let the poll loop advance through its sleeps under fake timers. */
+ const runWithTimers = async (ms: number, ...extra: string[]) => {
+ const done = run(...extra);
+ await vi.advanceTimersByTimeAsync(ms);
+ await done;
+ };
+
+ const allOutput = () =>
+ [
+ ...consoleSpy.mock.calls,
+ ...errorSpy.mock.calls,
+ ...warnSpy.mock.calls,
+ ...infoSpy.mock.calls,
+ ]
+ .map((c) => String(c[0]))
+ .join('\n');
+
+ beforeEach(() => {
+ process.exitCode = undefined;
+ errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});
+ warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});
+ infoSpy = vi.spyOn(log, 'info').mockImplementation(() => {});
+ stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
+ operationId: 'op-run',
+ success: true,
+ topicId: 'topic-1',
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ process.exitCode = undefined;
+ errorSpy.mockRestore();
+ warnSpy.mockRestore();
+ infoSpy.mockRestore();
+ stderrSpy.mockRestore();
+ });
+
+ // ── #19613: live-stream completion ────────────────────────────
+
+ it('exits 0 when the stream reports the run done', async () => {
+ mockStreamAgentEventsViaWebSocket.mockResolvedValue({ kind: 'completed', status: 'done' });
+ await run();
+ expect(process.exitCode).toBeUndefined();
+ expect(exitSpy).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['waiting_for_human', 2],
+ ['failed', 1],
+ ['interrupted', 1],
+ ] as const)('exits %s β†’ %i from the WebSocket stream', async (kind, code) => {
+ mockStreamAgentEventsViaWebSocket.mockResolvedValue({ kind, status: kind });
+ await run();
+ expect(process.exitCode).toBe(code);
+ });
+
+ it('exits 2 for a run parked on human approval over SSE, in --json mode too', async () => {
+ mockStreamAgentEvents.mockResolvedValue({
+ kind: 'waiting_for_human',
+ status: 'waiting_for_human',
+ });
+ await run('--sse', '--json', '--no-headless');
+ expect(process.exitCode).toBe(2);
+ });
+
+ it('an SSE stream that cannot be opened falls back to polling the run outcome', async () => {
+ mockStreamAgentEvents.mockRejectedValue(new Error('Agent stream failed: 502 Bad Gateway'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('done'));
+
+ await run('--sse');
+
+ expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalled();
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it.each([
+ [{ kind: 'completed', status: 'done' }, undefined],
+ [{ kind: 'failed', status: 'error' }, 1],
+ [{ kind: 'interrupted', status: 'interrupted' }, 1],
+ [{ kind: 'waiting_for_human', status: 'waiting_for_human' }, 2],
+ [undefined, 3],
+ ] as const)('--replay of a recording ending in %o exits %s', async (outcome, code) => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'lh-agent-replay-'));
+ const file = path.join(dir, 'events.json');
+ await writeFile(file, '[]');
+ mockReplayAgentEvents.mockReturnValue(outcome);
+
+ try {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'run', '--replay', file, '--json']);
+ } finally {
+ await rm(dir, { force: true, recursive: true });
+ }
+
+ expect(process.exitCode).toBe(code);
+ });
+
+ it('documents the exit status contract and the parked-run behaviour in --help', () => {
+ const program = createProgram();
+ const runCmd = program.commands
+ .find((c) => c.name() === 'agent')!
+ .commands.find((c) => c.name() === 'run')!;
+ let help = '';
+ runCmd.configureOutput({ writeOut: (s) => (help += s) });
+ runCmd.outputHelp();
+ expect(help).toContain('2 the run is paused waiting for human approval');
+ // commander wraps option descriptions; compare with whitespace collapsed
+ expect(help.replaceAll(/\s+/g, ' ')).toContain('does not wait for that approval');
+ });
+
+ // ── #19543: polling fallback reads the real envelope ──────────
+
+ it('polls the envelope the server returns and stops on currentState.status=done', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(
+ new Error('Agent gateway WebSocket failed: [object ErrorEvent]'),
+ );
+ mockTrpcClient.aiAgent.getOperationStatus.query
+ .mockResolvedValueOnce(envelope('idle'))
+ .mockResolvedValueOnce(envelope('done'));
+
+ await runWithTimers(20_000);
+
+ expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(2);
+ expect(process.exitCode).toBeUndefined();
+ expect(allOutput()).toContain('Agent finished');
+ });
+
+ it('falls back to the envelope summary flags when there is no status string', async () => {
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
+ hasError: false,
+ isCompleted: true,
+ });
+ await run();
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('gives up loudly with exit 3 on an answer whose status it cannot read', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ foo: 1 });
+
+ await runWithTimers(60_000);
+
+ expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(3);
+ expect(process.exitCode).toBe(3);
+ expect(allOutput()).toContain('Could not read a run status');
+ });
+
+ // ── #19614: failure statuses and missing results are not success ──
+
+ it.each([
+ ['error', 1],
+ ['interrupted', 1],
+ ['waiting_for_human', 2],
+ ] as const)('poll ending in %s exits %i', async (status, code) => {
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(
+ envelope(status, status === 'error' ? { error: 'model quota exceeded' } : {}),
+ );
+ await run();
+ expect(process.exitCode).toBe(code);
+ expect(allOutput()).not.toContain('Agent finished');
+ if (status === 'error') expect(allOutput()).toContain('model quota exceeded');
+ });
+
+ it.each(['failed', 'cancelled', 'aborted'])(
+ 'legacy flat status %s is not reported as success',
+ async (status) => {
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ status });
+ await run();
+ expect(process.exitCode).toBe(1);
+ },
+ );
+
+ it('a missing status result exits 3 without claiming the run finished or expired', async () => {
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(null);
+ await run();
+ expect(process.exitCode).toBe(3);
+ const out = allOutput();
+ expect(out).not.toContain('finished (or expired)');
+ expect(out).not.toContain('Agent finished');
+ expect(out).toContain('outcome cannot be confirmed');
+ });
+
+ it('a stream that ends without a terminal event checks the status instead of assuming success', async () => {
+ mockStreamAgentEventsViaWebSocket.mockResolvedValue(undefined); // session_complete only
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('error'));
+ await run();
+ expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+
+ // ── #19615: timeouts must not cut off an active run ───────────
+
+ it('--json no longer throws on a dropped stream; it polls the run to its end', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(
+ new Error('Agent gateway WebSocket sent no progress for 60s; status check failed: x'),
+ );
+ mockTrpcClient.aiAgent.getOperationStatus.query
+ .mockResolvedValueOnce(envelope('running'))
+ .mockResolvedValueOnce(envelope('running'))
+ .mockResolvedValueOnce(envelope('done'));
+
+ await runWithTimers(30_000, '--json');
+
+ expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(3);
+ expect(process.exitCode).toBeUndefined();
+ // progress lines stay off stdout so the --json array is not corrupted
+ expect(consoleSpy.mock.calls.flat().join('\n')).not.toContain('Run status');
+ });
+
+ it('the WebSocket quiet-window probe keeps waiting on an active run instead of failing it', async () => {
+ mockStreamAgentEventsViaWebSocket.mockImplementation(async (opts: any) => {
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValueOnce(envelope('running'));
+ expect(await opts.onStall()).toBeUndefined(); // active β†’ keep streaming
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValueOnce(
+ envelope('waiting_for_human'),
+ );
+ return opts.onStall();
+ });
+
+ await run('--json');
+
+ expect(process.exitCode).toBe(2);
+ });
+
+ it('bounds an in-flight status request that never answers', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query
+ .mockImplementationOnce(() => new Promise(() => {})) // hangs
+ .mockResolvedValueOnce(envelope('done'));
+
+ await runWithTimers(45_000);
+
+ const [, opts] = mockTrpcClient.aiAgent.getOperationStatus.query.mock.calls[0];
+ expect(opts.signal.aborted).toBe(true);
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('no answer within 30s'));
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('stops after repeated failed status requests with exit 3, not success', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockRejectedValue(new Error('ECONNRESET'));
+
+ await runWithTimers(60_000);
+
+ expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(3);
+ expect(process.exitCode).toBe(3);
+ });
+
+ it('--timeout stops waiting with exit 3 and points at lh agent status', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockImplementation(() => new Promise(() => {}));
+
+ await runWithTimers(5_000, '--timeout', '5');
+
+ expect(exitSpy).toHaveBeenCalledWith(3);
+ expect(allOutput()).toContain('lh agent status op-run');
+ });
+
+ it('waits on an active run indefinitely by default (no built-in deadline)', async () => {
+ vi.useFakeTimers();
+ mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('running'));
+
+ const done = vi.fn();
+ void run().then(done);
+ await vi.advanceTimersByTimeAsync(3 * 60 * 60_000); // 3h of a busy run
+
+ expect(done).not.toHaveBeenCalled();
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(process.exitCode).toBeUndefined();
+ });
+ });
+
describe('status', () => {
it('should display operation status', async () => {
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
@@ -1161,6 +1483,31 @@ describe('agent command', () => {
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Operation Status'));
});
+ it('reads the envelope getOperationStatus actually returns (#19543)', async () => {
+ mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
+ currentState: {
+ cost: { total: 0.0042 },
+ error: 'boom',
+ status: 'error',
+ stepCount: 3,
+ usage: { total_tokens: 1500 },
+ },
+ hasError: true,
+ isCompleted: true,
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'agent', 'status', 'op-123']);
+
+ const out = consoleSpy.mock.calls.map((c: unknown[]) => String(c[0])).join('\n');
+ expect(out).toContain('error');
+ expect(out).not.toContain('unknown');
+ expect(out).toContain('Steps: 3');
+ expect(out).toContain('Tokens: 1500');
+ expect(out).toContain('Cost: $0.0042');
+ expect(out).toContain('boom');
+ });
+
it('should output JSON', async () => {
const data = { status: 'completed', stepCount: 2 };
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(data);
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index afe5bd85bc1..866d52bd13a 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { AgentGraphSchema } from '@lobechat/types/agent/graph';
@@ -7,6 +8,8 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { getAgentStreamAuthInfo } from '../api/http';
import { resolveAgentGatewayUrl } from '../settings';
+import type { AgentRunOutcome } from '../utils/agentRunOutcome';
+import { AGENT_RUN_EXIT_CODES, colorStatus, readOperationStatus } from '../utils/agentRunOutcome';
import {
replayAgentEvents,
streamAgentEvents,
@@ -16,6 +19,7 @@ import { resolveLocalDeviceId } from '../utils/device';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
import { log, setVerbose } from '../utils/logger';
import { resolveAgentId } from './agent/resolveAgentId';
+import { pollAgentRunStatus, probeRunOutcome, RUN_POLL_INTERVAL_MS } from './agent/runStatus';
import { registerAgentSpaceFsCommand } from './agent/spaceFs';
import { resolveAppUrlBuilder } from './task/url';
@@ -356,12 +360,26 @@ export function registerAgentCommand(program: Command) {
)
.option(
'--no-headless',
- "Disable headless mode and wait for human approval on tool calls (default: headless β€” tools auto-run, matching the CLI's non-interactive nature)",
+ "Disable headless mode: tool calls that need approval park the run for a human (default: headless β€” tools auto-run, matching the CLI's non-interactive nature). The CLI does not wait for that approval; it returns with exit code 2 and the run continues once it is answered in LobeHub",
)
.option('--json', 'Output full JSON event stream')
.option('-v, --verbose', 'Show detailed tool call info')
.option('--replay <file>', 'Replay events from a saved JSON file (offline)')
.option('--sse', 'Force SSE stream instead of WebSocket gateway')
+ .option(
+ '--timeout <seconds>',
+ 'Stop waiting after this many seconds (exit code 3; the run keeps going server-side). Default: wait as long as the server reports the run active',
+ parsePositiveSeconds,
+ )
+ .addHelpText(
+ 'after',
+ `
+Exit codes:
+ 0 the run finished (done)
+ 1 the run failed or was interrupted
+ 2 the run is paused waiting for human approval / input
+ 3 the outcome could not be confirmed (no or unreadable status, status checks kept failing, or --timeout reached)`,
+ )
.action(
async (options: {
agentId?: string;
@@ -373,6 +391,7 @@ export function registerAgentCommand(program: Command) {
replay?: string;
slug?: string;
sse?: boolean;
+ timeout?: number;
topicId?: string;
verbose?: boolean;
}) => {
@@ -382,7 +401,13 @@ export function registerAgentCommand(program: Command) {
if (options.replay) {
const data = readFileSync(options.replay, 'utf8');
const events = JSON.parse(data);
- replayAgentEvents(events, { json: options.json, verbose: options.verbose });
+ const replayed = replayAgentEvents(events, {
+ json: options.json,
+ verbose: options.verbose,
+ });
+ // A recording without a terminal event cannot tell how the run ended.
+ const replayExitCode = AGENT_RUN_EXIT_CODES[(replayed ?? { kind: 'unknown' }).kind];
+ if (replayExitCode !== 0) process.exitCode = replayExitCode;
return;
}
@@ -464,33 +489,72 @@ export function registerAgentCommand(program: Command) {
const { serverUrl, headers, token, tokenType } = await getAgentStreamAuthInfo();
const agentGatewayUrl = options.sse ? undefined : resolveAgentGatewayUrl();
- try {
- if (agentGatewayUrl) {
- await streamAgentEventsViaWebSocket({
- gatewayUrl: agentGatewayUrl,
- json: options.json,
- operationId,
- serverUrl,
- token,
- tokenType,
- verbose: options.verbose,
- });
- } else {
- const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
- await streamAgentEvents(streamUrl, headers, {
- json: options.json,
- verbose: options.verbose,
- });
+ const waitForRun = async (): Promise<AgentRunOutcome> => {
+ let streamed: AgentRunOutcome | undefined;
+ try {
+ if (agentGatewayUrl) {
+ streamed = await streamAgentEventsViaWebSocket({
+ gatewayUrl: agentGatewayUrl,
+ json: options.json,
+ // A quiet stream is checked against the run status rather than
+ // treated as finished or failed β€” a long tool call can be silent.
+ onStall: () => probeRunOutcome(client, operationId, { json: options.json }),
+ operationId,
+ serverUrl,
+ token,
+ tokenType,
+ verbose: options.verbose,
+ });
+ } else {
+ const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
+ streamed = await streamAgentEvents(streamUrl, headers, {
+ json: options.json,
+ // SSE heartbeats keep the response open even when the terminal
+ // event was published before this subscription (in-memory event
+ // manager), so a quiet stream is checked against the run status.
+ onStall: () => probeRunOutcome(client, operationId, { json: options.json }),
+ verbose: options.verbose,
+ });
+ }
+ } catch (error) {
+ // The live stream (gateway WS / SSE) dropped before the run finished β€”
+ // the run may still be executing server-side, in --json mode too.
+ // Fall back to polling the run status until it reaches a terminal state.
+ log.warn(
+ `Live stream unavailable (${(error as Error).message}). Polling run status every ${RUN_POLL_INTERVAL_MS / 1000}s…`,
+ );
+ return pollAgentRunStatus(client, operationId, { json: options.json });
}
- } catch (error) {
- // The live stream (gateway WS / SSE) dropped before the run finished β€”
- // the run is still executing server-side. Instead of failing, fall back
- // to polling the run status until it reaches a terminal state.
- if (options.json) throw error;
- log.warn(
- `Live stream unavailable (${(error as Error).message}). Polling run status every 10s…`,
- );
- await pollAgentRunStatus(client, operationId);
+
+ // The stream closed without a terminal event: that is not a success
+ // signal, so ask the server how the run actually ended.
+ return streamed ?? pollAgentRunStatus(client, operationId, { json: options.json });
+ };
+
+ let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
+ let didTimeOut = false;
+ const timedOut =
+ options.timeout === undefined
+ ? undefined
+ : new Promise<AgentRunOutcome>((resolve) => {
+ timeoutTimer = setTimeout(() => {
+ didTimeOut = true;
+ log.error(
+ `Stopped waiting after ${options.timeout}s (--timeout). The run may still be executing β€” check it with 'lh agent status ${operationId}'.`,
+ );
+ resolve({ kind: 'unknown' });
+ }, options.timeout! * 1000);
+ });
+
+ const outcome = await (timedOut ? Promise.race([waitForRun(), timedOut]) : waitForRun());
+ clearTimeout(timeoutTimer);
+
+ const exitCode = AGENT_RUN_EXIT_CODES[outcome.kind];
+ if (exitCode !== 0) {
+ // A timeout leaves the stream / poll pending, so exit hard; otherwise
+ // set the code and let stdout (possibly a large --json array) drain.
+ if (didTimeOut) process.exit(exitCode);
+ process.exitCode = exitCode;
}
},
);
@@ -721,14 +785,23 @@ export function registerAgentCommand(program: Command) {
return;
}
+ if (!r) {
+ log.error(
+ `No status for operation ${operationId} (unknown id, not visible to this account, or its run state already expired).`,
+ );
+ process.exit(1);
+ return;
+ }
+
+ const read = readOperationStatus(r);
console.log(pc.bold('Operation Status'));
console.log(` ID: ${operationId}`);
- console.log(` Status: ${colorStatus(r.status || r.state || 'unknown')}`);
+ console.log(` Status: ${colorStatus(read.status || 'unknown')}`);
- if (r.stepCount !== undefined) console.log(` Steps: ${r.stepCount}`);
- if (r.usage?.total_tokens) console.log(` Tokens: ${r.usage.total_tokens}`);
- if (r.cost?.total !== undefined) console.log(` Cost: $${r.cost.total.toFixed(4)}`);
- if (r.error) console.log(` Error: ${pc.red(r.error)}`);
+ if (read.stepCount !== undefined) console.log(` Steps: ${read.stepCount}`);
+ if (read.usage?.total_tokens) console.log(` Tokens: ${read.usage.total_tokens}`);
+ if (read.cost?.total !== undefined) console.log(` Cost: $${read.cost.total.toFixed(4)}`);
+ if (read.error) console.log(` Error: ${pc.red(read.error)}`);
if (r.createdAt) console.log(` Started: ${r.createdAt}`);
if (r.completedAt) console.log(` Ended: ${r.completedAt}`);
},
@@ -782,75 +855,10 @@ export function registerAgentCommand(program: Command) {
);
}
-function colorStatus(status: string): string {
- switch (status) {
- case 'completed':
- case 'success': {
- return pc.green(status);
- }
- case 'failed':
- case 'error': {
- return pc.red(status);
- }
- case 'processing':
- case 'running': {
- return pc.yellow(status);
- }
- default: {
- return pc.dim(status);
- }
- }
-}
-
-const TERMINAL_RUN_STATUSES = new Set([
- 'completed',
- 'done',
- 'success',
- 'failed',
- 'error',
- 'cancelled',
- 'canceled',
- 'aborted',
-]);
-
-/**
- * Fallback when the live stream (gateway WebSocket / SSE) drops before the run
- * finishes: the run is still executing server-side, so poll its status every 10s
- * until it reaches a terminal state (or is no longer tracked, which also means it
- * has finished). Avoids hard-exiting on a transient gateway disconnect.
- */
-async function pollAgentRunStatus(
- client: Awaited<ReturnType<typeof getTrpcClient>>,
- operationId: string,
-): Promise<void> {
- const POLL_MS = 10_000;
- let lastStatus = '';
- for (let i = 0; ; i++) {
- if (i > 0) await new Promise((resolve) => setTimeout(resolve, POLL_MS));
-
- let r: any;
- try {
- r = await client.aiAgent.getOperationStatus.query({ operationId } as any);
- } catch (error) {
- log.error(`Status poll failed: ${(error as Error).message}`);
- process.exit(1);
- }
-
- if (!r) {
- log.info('Run is no longer tracked β€” finished (or expired).');
- return;
- }
-
- const status = r.status || r.state || 'unknown';
- if (status !== lastStatus) {
- lastStatus = status;
- const steps = r.stepCount !== undefined ? ` Β· ${r.stepCount} step(s)` : '';
- log.info(`Run status: ${colorStatus(status)}${steps}`);
- }
-
- if (TERMINAL_RUN_STATUSES.has(status)) {
- if (r.error) log.error(`Run error: ${r.error}`);
- return;
- }
+function parsePositiveSeconds(value: string): number {
+ const seconds = Number(value);
+ if (!Number.isFinite(seconds) || seconds <= 0) {
+ throw new InvalidArgumentError('Expected a positive number of seconds.');
}
+ return seconds;
}
diff --git a/apps/cli/src/commands/agent/runStatus.ts b/apps/cli/src/commands/agent/runStatus.ts
new file mode 100644
index 00000000000..156b5e48d1d
--- /dev/null
+++ b/apps/cli/src/commands/agent/runStatus.ts
@@ -0,0 +1,177 @@
+import type { getTrpcClient } from '../../api/client';
+import type { AgentRunOutcome } from '../../utils/agentRunOutcome';
+import {
+ classifyRunStatus,
+ colorStatus,
+ describeOutcome,
+ readOperationStatus,
+} from '../../utils/agentRunOutcome';
+import { log } from '../../utils/logger';
+
+type TrpcClient = Awaited<ReturnType<typeof getTrpcClient>>;
+
+export const RUN_POLL_INTERVAL_MS = 10_000;
+/** Upper bound for one status request, so a hung request cannot stall the wait. */
+export const RUN_STATUS_REQUEST_TIMEOUT_MS = 30_000;
+/** Consecutive failed / unreadable answers tolerated before giving up. */
+export const RUN_STATUS_MAX_MISSES = 3;
+
+interface StatusOptions {
+ /** `--json` keeps stdout for the event array, so progress goes to stderr */
+ json?: boolean;
+ requestTimeoutMs?: number;
+}
+
+interface PollOptions extends StatusOptions {
+ intervalMs?: number;
+ maxMisses?: number;
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const info = (json: boolean | undefined, msg: string) => {
+ if (json) console.error(msg);
+ else log.info(msg);
+};
+
+const MISSING_RESULT_MESSAGE =
+ "The server returned no status for this operation (unknown id, not visible to this account, or its run state already expired) β€” the run's outcome cannot be confirmed.";
+
+/**
+ * Query `getOperationStatus` with a hard deadline. The abort signal cancels
+ * the request; the race guarantees the deadline even if a transport ignores it.
+ */
+export const queryOperationStatus = async (
+ client: TrpcClient,
+ operationId: string,
+ timeoutMs = RUN_STATUS_REQUEST_TIMEOUT_MS,
+): Promise<any> => {
+ const controller = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ controller.abort();
+ reject(new Error(`status request got no answer within ${Math.round(timeoutMs / 1000)}s`));
+ }, timeoutMs);
+ });
+
+ try {
+ return await Promise.race([
+ client.aiAgent.getOperationStatus.query({ operationId } as any, {
+ signal: controller.signal,
+ }),
+ deadline,
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/**
+ * One status check while the live stream is still open but quiet. Returns the
+ * outcome once the run has ended, `undefined` while it is still active, and
+ * throws when the status cannot be fetched (the caller falls back to polling).
+ */
+export const probeRunOutcome = async (
+ client: TrpcClient,
+ operationId: string,
+ options: StatusOptions = {},
+): Promise<AgentRunOutcome | undefined> => {
+ const r = await queryOperationStatus(client, operationId, options.requestTimeoutMs);
+ if (!r) {
+ log.error(MISSING_RESULT_MESSAGE);
+ return { kind: 'unknown' };
+ }
+
+ const read = readOperationStatus(r);
+ const kind = classifyRunStatus(read.status);
+ if (kind === 'active') return undefined;
+ // Never guess an outcome from an answer it cannot read: hand over to the
+ // poller, which gives up loudly if the shape stays unreadable.
+ if (!kind) throw new Error(`unreadable run status (${read.status ?? 'none'})`);
+ return { error: read.error, kind, status: read.status };
+};
+
+/**
+ * Fallback when the live stream (gateway WebSocket / SSE) is unavailable or
+ * ended without a terminal event: the run may still be executing server-side,
+ * so poll its status until it reaches a terminal state.
+ *
+ * Never reports success it cannot see: failure / interruption statuses come
+ * back as such, and a missing, unreadable or unreachable status ends as
+ * `unknown` instead of being read as "finished".
+ */
+export const pollAgentRunStatus = async (
+ client: TrpcClient,
+ operationId: string,
+ options: PollOptions = {},
+): Promise<AgentRunOutcome> => {
+ const {
+ intervalMs = RUN_POLL_INTERVAL_MS,
+ json,
+ maxMisses = RUN_STATUS_MAX_MISSES,
+ requestTimeoutMs,
+ } = options;
+
+ const finish = (outcome: AgentRunOutcome): AgentRunOutcome => {
+ if (!json) {
+ console.log();
+ console.log(describeOutcome(outcome));
+ }
+ return outcome;
+ };
+
+ let lastStatus = '';
+ let failures = 0;
+ let unreadable = 0;
+
+ for (let i = 0; ; i++) {
+ if (i > 0) await sleep(intervalMs);
+
+ let r: any;
+ try {
+ r = await queryOperationStatus(client, operationId, requestTimeoutMs);
+ failures = 0;
+ } catch (error) {
+ failures++;
+ log.warn(`Status poll failed (${failures}/${maxMisses}): ${(error as Error).message}`);
+ if (failures >= maxMisses) {
+ log.error('Giving up on the run status; the run may still be executing server-side.');
+ return finish({ error: (error as Error).message, kind: 'unknown' });
+ }
+ continue;
+ }
+
+ if (!r) {
+ log.error(MISSING_RESULT_MESSAGE);
+ return finish({ kind: 'unknown' });
+ }
+
+ const read = readOperationStatus(r);
+ const kind = classifyRunStatus(read.status);
+
+ if (!kind) {
+ unreadable++;
+ if (unreadable >= maxMisses) {
+ const keys = typeof r === 'object' ? Object.keys(r).join(', ') : typeof r;
+ log.error(
+ `Could not read a run status from the server's answer (status: ${read.status ?? 'none'}; keys: ${keys}).`,
+ );
+ return finish({ kind: 'unknown', status: read.status });
+ }
+ continue;
+ }
+ unreadable = 0;
+
+ if (read.status !== lastStatus) {
+ lastStatus = read.status!;
+ const steps = read.stepCount !== undefined ? ` Β· ${read.stepCount} step(s)` : '';
+ info(json, `Run status: ${colorStatus(read.status!)}${steps}`);
+ }
+
+ if (kind !== 'active') {
+ if (read.error) log.error(`Run error: ${read.error}`);
+ return finish({ error: read.error, kind, status: read.status });
+ }
+ }
+};
diff --git a/apps/cli/src/commands/task/lifecycle.test.ts b/apps/cli/src/commands/task/lifecycle.test.ts
new file mode 100644
index 00000000000..7dc73076ed4
--- /dev/null
+++ b/apps/cli/src/commands/task/lifecycle.test.ts
@@ -0,0 +1,91 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerLifecycleCommands } from './lifecycle';
+
+const { client, streamAgentEvents } = vi.hoisted(() => ({
+ client: {
+ task: {
+ find: { query: vi.fn() },
+ heartbeat: { mutate: vi.fn() },
+ run: { mutate: vi.fn() },
+ update: { mutate: vi.fn() },
+ updateStatus: { mutate: vi.fn() },
+ },
+ },
+ streamAgentEvents: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn(async () => client) }));
+vi.mock('../../api/http', () => ({
+ getAuthInfo: vi.fn(async () => ({ headers: {}, serverUrl: 'https://example.com' })),
+}));
+vi.mock('../../utils/agentStream', () => ({ streamAgentEvents }));
+vi.mock('../../utils/logger', () => ({
+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+const createProgram = () => {
+ const program = new Command();
+ program.exitOverride();
+ registerLifecycleCommands(program.command('task'));
+ return program;
+};
+
+describe('task lifecycle β€” following the agent stream', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`process.exit(${code})`);
+ }) as any);
+ for (const fn of Object.values(client.task)) Object.values(fn)[0].mockReset();
+ streamAgentEvents.mockReset();
+ client.task.find.query.mockResolvedValue({
+ data: { assigneeAgentId: 'agt_1', identifier: 'T-1', status: 'pending' },
+ });
+ client.task.updateStatus.mutate.mockResolvedValue({ data: { identifier: 'T-1' } });
+ client.task.run.mutate.mockResolvedValue({
+ operationId: 'op-1',
+ success: true,
+ taskIdentifier: 'T-1',
+ topicId: 'tpc_1',
+ });
+ client.task.heartbeat.mutate.mockResolvedValue({});
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ });
+
+ it('task run --topics 2 stops with exit 1 when a run fails, without starting the next one', async () => {
+ streamAgentEvents.mockResolvedValue({ error: 'boom', kind: 'failed', status: 'error' });
+
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'task', 'run', 'T-1', '--topics', '2']),
+ ).rejects.toThrow('process.exit(1)');
+
+ expect(client.task.run.mutate).toHaveBeenCalledTimes(1);
+ expect(client.task.heartbeat.mutate).not.toHaveBeenCalled();
+ });
+
+ it('task start --follow exits 1 on a failed run', async () => {
+ streamAgentEvents.mockResolvedValue({ error: 'boom', kind: 'failed', status: 'error' });
+
+ await expect(
+ createProgram().parseAsync(['node', 'test', 'task', 'start', 'T-1', '--follow']),
+ ).rejects.toThrow('process.exit(1)');
+ });
+
+ it('a completed run sends the heartbeat and continues the sequence', async () => {
+ streamAgentEvents.mockResolvedValue({ kind: 'completed', status: 'done' });
+
+ await createProgram().parseAsync(['node', 'test', 'task', 'run', 'T-1', '--topics', '2']);
+
+ expect(client.task.run.mutate).toHaveBeenCalledTimes(2);
+ expect(client.task.heartbeat.mutate).toHaveBeenCalledTimes(2);
+ expect(exitSpy).not.toHaveBeenCalled();
+ // task streams opt out of the quiet-window probe: a long silent tool call is healthy
+ expect(streamAgentEvents.mock.calls[0][2]).not.toHaveProperty('onStall');
+ });
+});
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.ts
index 40fabdfe682..c7e268dd290 100644
--- a/apps/cli/src/commands/task/lifecycle.ts
+++ b/apps/cli/src/commands/task/lifecycle.ts
@@ -74,10 +74,13 @@ export function registerLifecycleCommands(task: Command) {
const { serverUrl, headers } = await getAuthInfo();
const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(result.operationId)}`;
- await streamAgentEvents(streamUrl, headers, {
+ const outcome = await streamAgentEvents(streamUrl, headers, {
json: options.json,
verbose: options.verbose,
});
+ // The stream helper reports an `error` event as a failed outcome rather
+ // than exiting; keep this command's contract of failing on it.
+ if (outcome?.kind === 'failed') process.exit(1);
// Send heartbeat after completion
try {
@@ -169,10 +172,12 @@ export function registerLifecycleCommands(task: Command) {
const { serverUrl, headers } = await getAuthInfo();
const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
- await streamAgentEvents(streamUrl, headers, {
+ const outcome = await streamAgentEvents(streamUrl, headers, {
json: options.json,
verbose: options.verbose,
});
+ // A failed run stops the sequence, as the stream helper used to exit on it.
+ if (outcome?.kind === 'failed') process.exit(1);
// Update heartbeat after each topic
try {
diff --git a/apps/cli/src/utils/agentRunOutcome.ts b/apps/cli/src/utils/agentRunOutcome.ts
new file mode 100644
index 00000000000..9e6f4986d12
--- /dev/null
+++ b/apps/cli/src/utils/agentRunOutcome.ts
@@ -0,0 +1,147 @@
+import pc from 'picocolors';
+
+/**
+ * How `lh agent run` ended, as far as the CLI could establish it.
+ *
+ * - `completed`: the run reached `done`
+ * - `failed`: the run reached `error`
+ * - `interrupted`: the run was cancelled / interrupted
+ * - `waiting_for_human`: the run is parked on a human approval or prompt
+ * - `unknown`: the CLI could not confirm an outcome (no status, unreadable
+ * status, status probes kept failing, or the wait timed out). The run may
+ * still be executing server-side.
+ */
+export type AgentRunOutcomeKind =
+ 'completed' | 'failed' | 'interrupted' | 'unknown' | 'waiting_for_human';
+
+export interface AgentRunOutcome {
+ error?: string;
+ kind: AgentRunOutcomeKind;
+ /** Raw status / end reason the outcome was derived from, when there was one */
+ status?: string;
+}
+
+/**
+ * Exit status contract of `lh agent run`. Scripts can tell a parked run apart
+ * from a finished one, and both apart from a run the CLI could not confirm.
+ */
+export const AGENT_RUN_EXIT_CODES: Record<AgentRunOutcomeKind, number> = {
+ completed: 0,
+ failed: 1,
+ interrupted: 1,
+ unknown: 3,
+ waiting_for_human: 2,
+};
+
+const COMPLETED_STATUSES = new Set(['completed', 'done', 'success']);
+const FAILED_STATUSES = new Set(['error', 'failed']);
+const INTERRUPTED_STATUSES = new Set(['aborted', 'canceled', 'cancelled', 'interrupted']);
+/** Non-terminal runtime statuses: the run is still going (or about to resume). */
+const ACTIVE_STATUSES = new Set([
+ 'idle',
+ 'pending',
+ 'processing',
+ 'running',
+ 'waiting_for_async_tool',
+]);
+
+/**
+ * Classify a runtime status or `agent_runtime_end` reason. Returns `active`
+ * for a run that is still going and `undefined` for a value the CLI does not
+ * recognise.
+ */
+export const classifyRunStatus = (
+ status: string | undefined,
+): AgentRunOutcomeKind | 'active' | undefined => {
+ if (!status) return undefined;
+ if (COMPLETED_STATUSES.has(status)) return 'completed';
+ if (FAILED_STATUSES.has(status)) return 'failed';
+ if (INTERRUPTED_STATUSES.has(status)) return 'interrupted';
+ if (status === 'waiting_for_human') return 'waiting_for_human';
+ if (ACTIVE_STATUSES.has(status)) return 'active';
+ return undefined;
+};
+
+export interface ReadOperationStatus {
+ cost?: { total?: number };
+ error?: string;
+ status?: string;
+ stepCount?: number;
+ usage?: { total_tokens?: number };
+}
+
+const errorText = (error: unknown): string | undefined => {
+ if (!error) return undefined;
+ if (typeof error === 'string') return error;
+ if (typeof error === 'object' && 'message' in error) return String((error as any).message);
+ return JSON.stringify(error);
+};
+
+/**
+ * Read `aiAgent.getOperationStatus`. The server answers with an envelope β€”
+ * `{ currentState: { status, stepCount, usage, cost, error }, isCompleted,
+ * hasError, needsHumanInput, isActive, ... }` β€” so the run's fields live under
+ * `currentState`, not at the top level. The flat reads are kept as fallbacks
+ * for older servers, and the envelope's summary flags stand in when there is
+ * no status string at all.
+ */
+export const readOperationStatus = (r: any): ReadOperationStatus => {
+ const state = r?.currentState ?? {};
+ let status: string | undefined = state.status ?? r?.status ?? r?.state;
+
+ if (!status) {
+ if (r?.isCompleted) status = r.hasError ? 'error' : 'done';
+ else if (r?.needsHumanInput) status = 'waiting_for_human';
+ else if (r?.isActive) status = 'running';
+ }
+
+ return {
+ cost: state.cost ?? r?.cost,
+ error: errorText(state.error ?? r?.error),
+ status,
+ stepCount: state.stepCount ?? r?.stepCount ?? r?.stats?.totalSteps,
+ usage: state.usage ?? r?.usage,
+ };
+};
+
+export const colorStatus = (status: string): string => {
+ switch (classifyRunStatus(status)) {
+ case 'completed': {
+ return pc.green(status);
+ }
+ case 'failed': {
+ return pc.red(status);
+ }
+ case 'interrupted':
+ case 'waiting_for_human': {
+ return pc.yellow(status);
+ }
+ case 'active': {
+ return pc.cyan(status);
+ }
+ default: {
+ return pc.dim(status);
+ }
+ }
+};
+
+/** One-line human summary of an outcome, used by the stream and poll paths. */
+export const describeOutcome = (outcome: AgentRunOutcome): string => {
+ switch (outcome.kind) {
+ case 'completed': {
+ return `${pc.green('βœ“')} Agent finished`;
+ }
+ case 'failed': {
+ return `${pc.red('βœ—')} Agent failed${outcome.error ? `: ${outcome.error}` : ''}`;
+ }
+ case 'interrupted': {
+ return `${pc.yellow('β– ')} Agent interrupted`;
+ }
+ case 'waiting_for_human': {
+ return `${pc.yellow('⏸')} Agent paused: waiting for human approval β€” approve or answer it in LobeHub, the CLI does not wait for it`;
+ }
+ case 'unknown': {
+ return `${pc.yellow('?')} Agent run outcome unknown${outcome.status ? ` (status: ${outcome.status})` : ''}`;
+ }
+ }
+};
diff --git a/apps/cli/src/utils/agentStream.test.ts b/apps/cli/src/utils/agentStream.test.ts
index f3e13aed8d4..88248a89e82 100644
--- a/apps/cli/src/utils/agentStream.test.ts
+++ b/apps/cli/src/utils/agentStream.test.ts
@@ -176,20 +176,32 @@ describe('streamAgentEvents', () => {
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Agent finished'));
});
- it('should exit on HTTP error', async () => {
+ it('rejects on an HTTP error instead of exiting, so the caller can poll the run', async () => {
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {
throw new Error('process.exit');
}) as any);
- const { log } = await import('./logger');
fetchSpy.mockResolvedValue(new Response('Not Found', { status: 404 }));
await expect(streamAgentEvents('https://example.com/stream', {})).rejects.toThrow(
- 'process.exit',
+ 'Agent stream failed: 404 Not Found',
);
+ expect(exitSpy).not.toHaveBeenCalled();
+
+ exitSpy.mockRestore();
+ });
- expect(log.error).toHaveBeenCalledWith(expect.stringContaining('404'));
- expect(exitSpy).toHaveBeenCalledWith(1);
+ it('rejects on a response without a body instead of exiting', async () => {
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('process.exit');
+ }) as any);
+
+ fetchSpy.mockResolvedValue(new Response(null, { status: 200 }));
+
+ await expect(streamAgentEvents('https://example.com/stream', {})).rejects.toThrow(
+ 'No response body received from agent stream',
+ );
+ expect(exitSpy).not.toHaveBeenCalled();
exitSpy.mockRestore();
});
@@ -672,3 +684,482 @@ describe('renderEvent tool_end', () => {
expect(log.toolResult).toHaveBeenCalledWith('tc-1', true, ' 120ms');
});
});
+
+describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
+ let stdoutSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
+ const originalWebSocket = globalThis.WebSocket;
+ const flush = () => new Promise((r) => setTimeout(r, 20));
+ const printed = () => consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');
+
+ beforeEach(() => {
+ capturedWs = undefined;
+ stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ (globalThis as any).WebSocket = MockWebSocket;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ stdoutSpy.mockRestore();
+ consoleSpy.mockRestore();
+ fetchSpy.mockRestore();
+ globalThis.WebSocket = originalWebSocket;
+ });
+
+ const endEvent = (reason: string) => ({
+ data: { reason, stepCount: 2 },
+ operationId: 'op-1',
+ stepIndex: 1,
+ timestamp: Date.now(),
+ type: 'agent_runtime_end',
+ });
+
+ describe.each([
+ ['done', 'completed', 'Agent finished'],
+ ['waiting_for_human', 'waiting_for_human', 'Agent paused: waiting for human approval'],
+ ['error', 'failed', 'Agent failed'],
+ ['interrupted', 'interrupted', 'Agent interrupted'],
+ ])('agent_runtime_end reason=%s', (reason, kind, label) => {
+ it(`SSE resolves ${kind} and prints "${label}"`, async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(createSSEStream([sseMessage('data', endEvent(reason))]), { status: 200 }),
+ );
+
+ const outcome = await streamAgentEvents('https://example.com/stream', {});
+
+ expect(outcome).toEqual(expect.objectContaining({ kind, status: reason }));
+ expect(printed()).toContain(label);
+ if (reason !== 'done') expect(printed()).not.toContain('Agent finished');
+ });
+
+ it(`WebSocket resolves ${kind} and prints "${label}"`, async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 't',
+ });
+ await flush();
+ capturedWs!.simulateMessage({ event: endEvent(reason), id: '1', type: 'agent_event' });
+
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind, status: reason }));
+ expect(printed()).toContain(label);
+ if (reason !== 'done') expect(printed()).not.toContain('Agent finished');
+ });
+ });
+
+ it('resolves an error event as a failed outcome instead of exiting the process', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 't',
+ });
+ await flush();
+ capturedWs!.simulateMessage({
+ event: { data: { message: 'boom' }, type: 'error' },
+ id: '1',
+ type: 'agent_event',
+ });
+
+ await expect(promise).resolves.toEqual({ error: 'boom', kind: 'failed', status: 'error' });
+ });
+
+ describe('replayAgentEvents outcome', () => {
+ it.each([
+ ['done', 'completed'],
+ ['error', 'failed'],
+ ['interrupted', 'interrupted'],
+ ['waiting_for_human', 'waiting_for_human'],
+ ])('returns %s β†’ %s from the recorded end event, in --json mode too', (reason, kind) => {
+ const events = [endEvent(reason)] as any;
+ expect(replayAgentEvents(events)).toEqual(expect.objectContaining({ kind, status: reason }));
+ expect(replayAgentEvents(events, { json: true })).toEqual(
+ expect.objectContaining({ kind, status: reason }),
+ );
+ });
+
+ it('returns a failed outcome for a recorded error event', () => {
+ const events = [{ data: { message: 'boom' }, type: 'error' }] as any;
+ expect(replayAgentEvents(events)).toEqual({ error: 'boom', kind: 'failed', status: 'error' });
+ expect(replayAgentEvents(events, { json: true })).toEqual({
+ error: 'boom',
+ kind: 'failed',
+ status: 'error',
+ });
+ });
+
+ it('returns undefined for a recording without a terminal event', () => {
+ expect(replayAgentEvents([{ data: {}, type: 'stream_start' }] as any)).toBeUndefined();
+ });
+ });
+
+ it('SSE that closes without a terminal event resolves undefined, not success', async () => {
+ fetchSpy.mockResolvedValue(new Response(createSSEStream([]), { status: 200 }));
+ await expect(streamAgentEvents('https://example.com/stream', {})).resolves.toBeUndefined();
+ });
+
+ it('a gateway that only acks heartbeats can no longer hang the stream forever', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ stallTimeoutMs: 1000,
+ token: 't',
+ });
+ const settled = vi.fn();
+ promise.then(settled, settled);
+ await vi.advanceTimersByTimeAsync(0);
+
+ // heartbeat acks keep arriving but never count as progress
+ for (let i = 0; i < 5; i++) {
+ capturedWs!.simulateMessage({ type: 'heartbeat_ack' });
+ await vi.advanceTimersByTimeAsync(300);
+ }
+
+ await expect(promise).rejects.toThrow('sent no progress for 1s');
+ });
+
+ it('a quiet stream asks onStall and keeps waiting while the run is still active', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ const onStall = vi
+ .fn()
+ .mockResolvedValueOnce(undefined) // still running β†’ keep streaming
+ .mockResolvedValueOnce({ kind: 'completed', status: 'done' });
+
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ onStall,
+ operationId: 'op-1',
+ stallTimeoutMs: 1000,
+ token: 't',
+ });
+ const settled = vi.fn();
+ promise.then(settled, settled);
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onStall).toHaveBeenCalledTimes(1);
+ expect(settled).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(promise).resolves.toEqual({ kind: 'completed', status: 'done' });
+ expect(onStall).toHaveBeenCalledTimes(2);
+ expect(printed()).toContain('Agent finished');
+ });
+
+ it('real stream progress restarts the quiet window, so a slow healthy run is not probed', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ const onStall = vi.fn();
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ onStall,
+ operationId: 'op-1',
+ stallTimeoutMs: 1000,
+ token: 't',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ for (let i = 0; i < 10; i++) {
+ await vi.advanceTimersByTimeAsync(700);
+ capturedWs!.simulateMessage({
+ event: { data: {}, stepIndex: 0, type: 'step_complete' },
+ id: String(i),
+ type: 'agent_event',
+ });
+ }
+ expect(onStall).not.toHaveBeenCalled();
+
+ capturedWs!.simulateMessage({ event: endEvent('done'), id: 'end', type: 'agent_event' });
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'completed' }));
+ });
+
+ it('does not let the heartbeat interval hold the process open', async () => {
+ const unref = vi.fn();
+ const realSetInterval = globalThis.setInterval;
+ const intervalSpy = vi.spyOn(globalThis, 'setInterval').mockImplementation(((
+ fn: any,
+ ms: any,
+ ) => {
+ const handle = realSetInterval(fn, ms);
+ const original = handle.unref.bind(handle);
+ handle.unref = () => {
+ unref();
+ return original();
+ };
+ return handle;
+ }) as any);
+
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 't',
+ });
+ await flush();
+ expect(unref).toHaveBeenCalled();
+
+ capturedWs!.simulateMessage({ event: endEvent('done'), id: '1', type: 'agent_event' });
+ await promise;
+ intervalSpy.mockRestore();
+ });
+});
+
+describe('SSE quiet window (terminal event published before the subscription)', () => {
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let stdoutSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ fetchSpy.mockRestore();
+ consoleSpy.mockRestore();
+ stdoutSpy.mockRestore();
+ });
+
+ /**
+ * What the SSE route serves when `agent_runtime_end` fired before the
+ * subscription: heartbeats forever, never a terminal event, never EOF.
+ * `events` are emitted first, then one heartbeat every `everyMs`.
+ */
+ const heartbeatOnlyBody = (everyMs: number, events: string[] = []) => {
+ const encoder = new TextEncoder();
+ let timer: ReturnType<typeof setInterval> | undefined;
+ return new ReadableStream<Uint8Array>({
+ cancel() {
+ clearInterval(timer);
+ },
+ start(controller) {
+ for (const e of events) controller.enqueue(encoder.encode(e));
+ timer = setInterval(
+ () => controller.enqueue(encoder.encode(sseMessage('heartbeat', { type: 'heartbeat' }))),
+ everyMs,
+ );
+ },
+ });
+ };
+
+ const settledFlag = (p: Promise<unknown>) => {
+ const settled = vi.fn();
+ p.then(settled, settled);
+ return settled;
+ };
+
+ it('asks onStall instead of hanging on heartbeats, and returns the run outcome', async () => {
+ fetchSpy.mockResolvedValue(new Response(heartbeatOnlyBody(300), { status: 200 }));
+ const onStall = vi.fn().mockResolvedValue({ kind: 'completed', status: 'done' });
+
+ const promise = streamAgentEvents(
+ 'https://example.com/stream',
+ {},
+ { onStall, stallTimeoutMs: 1000 },
+ );
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await expect(promise).resolves.toEqual({ kind: 'completed', status: 'done' });
+ expect(onStall).toHaveBeenCalledTimes(1);
+ expect(consoleSpy.mock.calls.flat().join('\n')).toContain('Agent finished');
+ });
+
+ it('keeps streaming while the run is still active', async () => {
+ fetchSpy.mockResolvedValue(new Response(heartbeatOnlyBody(300), { status: 200 }));
+ const onStall = vi
+ .fn()
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce({ kind: 'waiting_for_human', status: 'waiting_for_human' });
+
+ const promise = streamAgentEvents(
+ 'https://example.com/stream',
+ {},
+ { onStall, stallTimeoutMs: 1000 },
+ );
+ const settled = settledFlag(promise);
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onStall).toHaveBeenCalledTimes(1);
+ expect(settled).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'waiting_for_human' }));
+ });
+
+ it('rejects when the status check fails, so the caller falls back to polling', async () => {
+ fetchSpy.mockResolvedValue(new Response(heartbeatOnlyBody(300), { status: 200 }));
+ const onStall = vi.fn().mockRejectedValue(new Error('ECONNRESET'));
+
+ const promise = streamAgentEvents(
+ 'https://example.com/stream',
+ {},
+ { onStall, stallTimeoutMs: 1000 },
+ );
+ const assertion = expect(promise).rejects.toThrow('status check failed: ECONNRESET');
+ await vi.advanceTimersByTimeAsync(1000);
+ await assertion;
+ });
+
+ it('without onStall a quiet stream is never cut off (task --follow streams)', async () => {
+ const encoder = new TextEncoder();
+ let controllerRef!: ReadableStreamDefaultController<Uint8Array>;
+ let timer: ReturnType<typeof setInterval> | undefined;
+ fetchSpy.mockResolvedValue(
+ new Response(
+ new ReadableStream<Uint8Array>({
+ cancel() {
+ clearInterval(timer);
+ },
+ start(c) {
+ controllerRef = c;
+ timer = setInterval(
+ () => c.enqueue(encoder.encode(sseMessage('heartbeat', { type: 'heartbeat' }))),
+ 300,
+ );
+ },
+ }),
+ { status: 200 },
+ ),
+ );
+
+ const promise = streamAgentEvents('https://example.com/stream', {}, { stallTimeoutMs: 1000 });
+ const settled = settledFlag(promise);
+ await vi.advanceTimersByTimeAsync(10_000); // a long silent tool call
+ expect(settled).not.toHaveBeenCalled();
+
+ clearInterval(timer);
+ controllerRef.enqueue(
+ encoder.encode(
+ sseMessage('data', { data: { reason: 'done' }, stepIndex: 0, type: 'agent_runtime_end' }),
+ ),
+ );
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'completed' }));
+ });
+
+ it('real events restart the window, heartbeats do not', async () => {
+ const encoder = new TextEncoder();
+ let controllerRef!: ReadableStreamDefaultController<Uint8Array>;
+ fetchSpy.mockResolvedValue(
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(c) {
+ controllerRef = c;
+ },
+ }),
+ { status: 200 },
+ ),
+ );
+ const onStall = vi.fn().mockResolvedValue(undefined);
+ const promise = streamAgentEvents(
+ 'https://example.com/stream',
+ {},
+ { onStall, stallTimeoutMs: 1000 },
+ );
+
+ for (let i = 0; i < 10; i++) {
+ await vi.advanceTimersByTimeAsync(700);
+ controllerRef.enqueue(
+ encoder.encode(sseMessage('data', { data: {}, stepIndex: 0, type: 'step_complete' })),
+ );
+ }
+ expect(onStall).not.toHaveBeenCalled();
+
+ controllerRef.enqueue(
+ encoder.encode(
+ sseMessage('data', { data: { reason: 'done' }, stepIndex: 0, type: 'agent_runtime_end' }),
+ ),
+ );
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'completed' }));
+ });
+});
+
+describe('--json prints exactly one array, even when no event arrived', () => {
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ const originalWebSocket = globalThis.WebSocket;
+ const flush = () => new Promise((r) => setTimeout(r, 20));
+ /** Every stdout line written via console.log, parsed β€” must be exactly `[[]]`. */
+ const jsonOutputs = () => consoleSpy.mock.calls.map((c) => JSON.parse(String(c[0])));
+
+ beforeEach(() => {
+ capturedWs = undefined;
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ (globalThis as any).WebSocket = MockWebSocket;
+ });
+
+ afterEach(() => {
+ fetchSpy.mockRestore();
+ consoleSpy.mockRestore();
+ globalThis.WebSocket = originalWebSocket;
+ });
+
+ it('SSE that fails to open (HTTP 502) prints [] before rejecting', async () => {
+ fetchSpy.mockResolvedValue(new Response('bad gateway', { status: 502 }));
+ await expect(
+ streamAgentEvents('https://example.com/stream', {}, { json: true }),
+ ).rejects.toThrow('Agent stream failed: 502');
+ expect(jsonOutputs()).toEqual([[]]);
+ });
+
+ it('SSE whose request rejects (network error) prints [] before rejecting', async () => {
+ fetchSpy.mockRejectedValue(new TypeError('fetch failed'));
+ await expect(
+ streamAgentEvents('https://example.com/stream', {}, { json: true }),
+ ).rejects.toThrow('fetch failed');
+ expect(jsonOutputs()).toEqual([[]]);
+ });
+
+ it('SSE that closes with no events prints []', async () => {
+ fetchSpy.mockResolvedValue(new Response(createSSEStream([]), { status: 200 }));
+ await expect(
+ streamAgentEvents('https://example.com/stream', {}, { json: true }),
+ ).resolves.toBeUndefined();
+ expect(jsonOutputs()).toEqual([[]]);
+ });
+
+ it('WebSocket auth failure before any event prints [] once', async () => {
+ (globalThis as any).WebSocket = class extends MockWebSocket {
+ constructor(url: string) {
+ super(url, false);
+ }
+
+ override send(data: string) {
+ this.sent.push(data);
+ if (JSON.parse(data).type === 'auth') {
+ queueMicrotask(() =>
+ this.onmessage?.({ data: JSON.stringify({ reason: 'bad', type: 'auth_failed' }) }),
+ );
+ }
+ }
+ };
+
+ await expect(
+ streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ json: true,
+ operationId: 'op-1',
+ token: 't',
+ }),
+ ).rejects.toThrow('Gateway auth failed');
+ await flush(); // the close that follows must not print a second array
+ expect(jsonOutputs()).toEqual([[]]);
+ });
+
+ it('WebSocket session_complete with no events prints []', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ json: true,
+ operationId: 'op-1',
+ token: 't',
+ });
+ await flush();
+ capturedWs!.simulateMessage({ id: '1', type: 'session_complete' });
+ await promise;
+ await flush();
+ expect(jsonOutputs()).toEqual([[]]);
+ });
+});
diff --git a/apps/cli/src/utils/agentStream.ts b/apps/cli/src/utils/agentStream.ts
index 109c3dbb8a3..141544fa1ae 100644
--- a/apps/cli/src/utils/agentStream.ts
+++ b/apps/cli/src/utils/agentStream.ts
@@ -2,6 +2,8 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import pc from 'picocolors';
import urlJoin from 'url-join';
+import type { AgentRunOutcome } from './agentRunOutcome';
+import { classifyRunStatus, describeOutcome } from './agentRunOutcome';
import { log } from './logger';
export type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
@@ -11,7 +13,22 @@ interface StreamOptions {
verbose?: boolean;
}
-interface WebSocketStreamOptions extends StreamOptions {
+interface LiveStreamOptions extends StreamOptions {
+ /**
+ * Called when the stream has carried no progress for `stallTimeoutMs`. Both
+ * transports can keep a connection alive with heartbeats while never
+ * delivering the terminal event (a gateway that does not forward it, or an
+ * SSE subscription opened after a fast run already ended), so silence alone
+ * must not be read as either "finished" or "failed". Return the run's
+ * outcome to finish, `undefined` when the run is still active (keep
+ * streaming), or throw to give up on the stream.
+ */
+ onStall?: () => Promise<AgentRunOutcome | undefined>;
+ /** Progress window before `onStall` is consulted. Defaults to 60s. */
+ stallTimeoutMs?: number;
+}
+
+interface WebSocketStreamOptions extends LiveStreamOptions {
gatewayUrl: string;
operationId: string;
/**
@@ -28,32 +45,73 @@ interface WebSocketStreamOptions extends StreamOptions {
tokenType?: 'jwt' | 'apiKey';
}
+/**
+ * Map an `agent_runtime_end` event to the run outcome. The server ends the
+ * stream on `done`, `error`, `interrupted` and `waiting_for_human` alike, so the
+ * end event alone does not mean the run succeeded β€” `data.reason` says how.
+ */
+export const outcomeFromEndEvent = (event: AgentStreamEvent): AgentRunOutcome => {
+ const reason: string | undefined = event.data?.reason;
+ const kind = classifyRunStatus(reason);
+ const error = event.data?.finalState?.error;
+ return {
+ error: typeof error === 'string' ? error : (error?.message ?? undefined),
+ // An end event without a reason predates `reason` and has always meant done.
+ kind: !reason ? 'completed' : kind && kind !== 'active' ? kind : 'unknown',
+ status: reason,
+ };
+};
+
+const STALL_TIMEOUT = 60_000;
+
+const outcomeFromErrorEvent = (event: AgentStreamEvent): AgentRunOutcome => ({
+ error: event.data?.message || event.data?.error || 'Unknown error',
+ kind: 'failed',
+ status: 'error',
+});
+
/**
* Connect to the agent SSE stream and render events to the terminal.
- * Resolves when the stream ends (agent_runtime_end or connection close).
+ * Resolves with the run outcome once a terminal event arrives, or `undefined`
+ * when the stream closed without one (the caller should check the status).
+ * Rejects when the stream cannot be opened β€” the run may still be executing
+ * server-side, so the caller falls back to polling rather than exiting here.
*/
export async function streamAgentEvents(
url: string,
headers: Record<string, string>,
- options: StreamOptions = {},
-): Promise<void> {
- const res = await fetch(url, { headers });
-
- if (!res.ok) {
- const text = await res.text();
- log.error(`Agent stream failed: ${res.status} ${text}`);
- process.exit(1);
- }
-
- if (!res.body) {
- log.error('No response body received from agent stream');
- process.exit(1);
+ options: LiveStreamOptions = {},
+): Promise<AgentRunOutcome | undefined> {
+ const { onStall, stallTimeoutMs = STALL_TIMEOUT } = options;
+ const jsonEvents: AgentStreamEvent[] = [];
+ // `--json` promises one JSON array on stdout whatever happens next β€” even
+ // `[]` when the stream fails before any event and the caller falls back to
+ // polling β€” so every exit path prints through here exactly once.
+ let jsonPrinted = false;
+ const printJsonOnce = () => {
+ if (!options.json || jsonPrinted) return;
+ jsonPrinted = true;
+ console.log(JSON.stringify(jsonEvents, null, 2));
+ };
+
+ let res: Response;
+ try {
+ res = await fetch(url, { headers });
+ if (!res.ok) {
+ const text = await res.text();
+ throw new Error(`Agent stream failed: ${res.status} ${text}`);
+ }
+ if (!res.body) {
+ throw new Error('No response body received from agent stream');
+ }
+ } catch (error) {
+ printJsonOnce();
+ throw error;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
- const jsonEvents: AgentStreamEvent[] = [];
const ctx = createRenderContext();
// Declared outside the read loop so partial SSE frames that span
@@ -61,9 +119,53 @@ export async function streamAgentEvents(
let eventType = '';
let eventData = '';
+ // Progress window, restarted by real events only β€” SSE heartbeats keep the
+ // response open even when the terminal event was missed, so they must not
+ // count. When it expires, `onStall` decides; its verdict is handed back to
+ // the read loop by cancelling the pending read. Without `onStall` there is no
+ // window at all: silence is not evidence, and a quiet tool call is legitimate.
+ let finished = false;
+ let stallTimer: ReturnType<typeof setTimeout> | undefined;
+ let stalled: { error: Error } | { outcome: AgentRunOutcome } | undefined;
+ const armStallTimer = () => {
+ if (!onStall) return;
+ if (stallTimer) clearTimeout(stallTimer);
+ stallTimer = setTimeout(async () => {
+ if (finished) return;
+ const silence = `Agent stream sent no progress for ${Math.round(stallTimeoutMs / 1000)}s`;
+ log.debug(`${silence}; checking the run status`);
+ try {
+ const outcome = await onStall();
+ if (finished) return;
+ if (!outcome) {
+ armStallTimer();
+ return;
+ }
+ stalled = { outcome };
+ } catch (error) {
+ if (finished) return;
+ stalled = {
+ error: new Error(`${silence}; status check failed: ${(error as Error).message}`),
+ };
+ }
+ void reader.cancel();
+ }, stallTimeoutMs);
+ };
+ armStallTimer();
+
try {
while (true) {
const { done, value } = await reader.read();
+ if (stalled) {
+ finished = true;
+ if ('error' in stalled) {
+ printJsonOnce();
+ throw stalled.error;
+ }
+ if (options.json) printJsonOnce();
+ else renderOutcome(stalled.outcome);
+ return stalled.outcome;
+ }
if (done) break;
buffer += decoder.decode(value, { stream: true });
@@ -89,6 +191,7 @@ export async function streamAgentEvents(
continue;
}
+ armStallTimer();
try {
const event: AgentStreamEvent = JSON.parse(eventData);
@@ -99,22 +202,20 @@ export async function streamAgentEvents(
}
if (event.type === 'agent_runtime_end') {
+ const outcome = outcomeFromEndEvent(event);
if (options.json) {
- console.log(JSON.stringify(jsonEvents, null, 2));
+ printJsonOnce();
} else {
- renderEnd(event);
+ renderEnd(event, outcome);
}
- return;
+ return outcome;
}
if (event.type === 'error') {
- if (options.json) {
- console.log(JSON.stringify(jsonEvents, null, 2));
- }
- log.error(
- `Agent error: ${event.data?.message || event.data?.error || 'Unknown error'}`,
- );
- process.exit(1);
+ printJsonOnce();
+ const outcome = outcomeFromErrorEvent(event);
+ log.error(`Agent error: ${outcome.error}`);
+ return outcome;
}
} catch {
// Not JSON, skip
@@ -127,22 +228,31 @@ export async function streamAgentEvents(
}
// Stream ended without agent_runtime_end
- if (options.json && jsonEvents.length > 0) {
- console.log(JSON.stringify(jsonEvents, null, 2));
- }
+ printJsonOnce();
+ return undefined;
} finally {
+ finished = true;
+ if (stallTimer) clearTimeout(stallTimer);
reader.releaseLock();
}
}
/**
* Replay previously saved JSON events (from --json output) to the terminal.
- * No network calls needed.
+ * No network calls needed. Returns the outcome carried by the recorded terminal
+ * event, or `undefined` when the recording has none (e.g. a truncated capture).
*/
-export function replayAgentEvents(events: AgentStreamEvent[], options: StreamOptions = {}): void {
+export function replayAgentEvents(
+ events: AgentStreamEvent[],
+ options: StreamOptions = {},
+): AgentRunOutcome | undefined {
if (options.json) {
console.log(JSON.stringify(events, null, 2));
- return;
+ for (const event of events) {
+ if (event.type === 'agent_runtime_end') return outcomeFromEndEvent(event);
+ if (event.type === 'error') return outcomeFromErrorEvent(event);
+ }
+ return undefined;
}
const ctx = createRenderContext();
@@ -153,27 +263,42 @@ export function replayAgentEvents(events: AgentStreamEvent[], options: StreamOpt
renderEvent(event, ctx, options);
if (event.type === 'agent_runtime_end') {
- renderEnd(event);
- return;
+ const outcome = outcomeFromEndEvent(event);
+ renderEnd(event, outcome);
+ return outcome;
}
if (event.type === 'error') {
- log.error(`Agent error: ${event.data?.message || event.data?.error || 'Unknown error'}`);
- return;
+ const outcome = outcomeFromErrorEvent(event);
+ log.error(`Agent error: ${outcome.error}`);
+ return outcome;
}
}
+
+ return undefined;
}
const HEARTBEAT_INTERVAL = 30_000;
/**
* Connect to the Agent Gateway via WebSocket and render events to the terminal.
- * Resolves when the session completes or the connection closes.
+ * Resolves with the run outcome once a terminal event arrives, `undefined` when
+ * the gateway completed the session without one, and rejects when the
+ * connection fails so the caller can fall back to polling.
*/
export async function streamAgentEventsViaWebSocket(
options: WebSocketStreamOptions,
-): Promise<void> {
- const { gatewayUrl, operationId, serverUrl, token, tokenType = 'jwt', ...streamOpts } = options;
+): Promise<AgentRunOutcome | undefined> {
+ const {
+ gatewayUrl,
+ onStall,
+ operationId,
+ serverUrl,
+ stallTimeoutMs = STALL_TIMEOUT,
+ token,
+ tokenType = 'jwt',
+ ...streamOpts
+ } = options;
const wsUrl = urlJoin(
gatewayUrl.replace(/^http/, 'ws'),
`/ws?operationId=${encodeURIComponent(operationId)}`,
@@ -181,31 +306,87 @@ export async function streamAgentEventsViaWebSocket(
log.debug(`Connecting to gateway: ${wsUrl} (auth: ${tokenType})`);
- return new Promise<void>((resolve, reject) => {
+ return new Promise<AgentRunOutcome | undefined>((resolve, reject) => {
const ws = new WebSocket(wsUrl);
const jsonEvents: AgentStreamEvent[] = [];
const ctx = createRenderContext();
let lastEventId = '';
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
+ let stallTimer: ReturnType<typeof setTimeout> | undefined;
let isSettled = false;
let jsonPrinted = false;
const cleanup = () => {
if (heartbeatTimer) clearInterval(heartbeatTimer);
+ if (stallTimer) clearTimeout(stallTimer);
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
ws.close();
}
};
+ // Same `--json` contract as SSE: exactly one array per run, `[]` included.
+ const printJsonOnce = () => {
+ if (streamOpts.json && !jsonPrinted) {
+ jsonPrinted = true;
+ console.log(JSON.stringify(jsonEvents, null, 2));
+ }
+ };
+
+ const settle = (outcome: AgentRunOutcome | undefined) => {
+ if (isSettled) return;
+ isSettled = true;
+ cleanup();
+ resolve(outcome);
+ };
+
+ const fail = (error: Error) => {
+ if (isSettled) return;
+ isSettled = true;
+ cleanup();
+ printJsonOnce();
+ reject(error);
+ };
+
+ // Progress window: restarted by real stream traffic only. `heartbeat_ack`
+ // must not restart it β€” a gateway that keeps acking while never forwarding
+ // the terminal event is exactly the shape that used to hang forever.
+ const armStallTimer = () => {
+ if (stallTimer) clearTimeout(stallTimer);
+ stallTimer = setTimeout(async () => {
+ if (isSettled) return;
+ const silence = `Agent gateway WebSocket sent no progress for ${Math.round(stallTimeoutMs / 1000)}s`;
+ if (!onStall) {
+ fail(new Error(`${silence} and never reported completion`));
+ return;
+ }
+ log.debug(`${silence}; checking the run status`);
+ try {
+ const outcome = await onStall();
+ if (isSettled) return;
+ if (outcome) {
+ if (!streamOpts.json) renderOutcome(outcome);
+ printJsonOnce();
+ settle(outcome);
+ } else {
+ armStallTimer();
+ }
+ } catch (error) {
+ fail(new Error(`${silence}; status check failed: ${(error as Error).message}`));
+ }
+ }, stallTimeoutMs);
+ };
+
ws.onopen = () => {
// `serverUrl` is required so the gateway can call back to verify an
// apiKey token. Harmless (but unused) for JWT, so we always include it
// when available to match the device-gateway-client contract.
ws.send(JSON.stringify({ serverUrl, token, tokenType, type: 'auth' }));
+ armStallTimer();
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string);
+ if (msg.type !== 'heartbeat_ack') armStallTimer();
if (msg.type === 'auth_success') {
log.debug('Gateway authenticated');
@@ -216,12 +397,13 @@ export async function streamAgentEventsViaWebSocket(
ws.send(JSON.stringify({ type: 'heartbeat' }));
}
}, HEARTBEAT_INTERVAL);
+ // The heartbeat alone must never keep the process alive.
+ heartbeatTimer.unref?.();
return;
}
if (msg.type === 'auth_failed') {
- cleanup();
- reject(new Error(`Gateway auth failed: ${msg.reason}`));
+ fail(new Error(`Gateway auth failed: ${msg.reason}`));
return;
}
@@ -238,67 +420,38 @@ export async function streamAgentEventsViaWebSocket(
}
if (agentEvent.type === 'agent_runtime_end') {
- if (streamOpts.json && !jsonPrinted) {
- jsonPrinted = true;
- console.log(JSON.stringify(jsonEvents, null, 2));
- } else if (!streamOpts.json) {
- renderEnd(agentEvent);
- }
if (isSettled) return;
- isSettled = true;
- cleanup();
- resolve();
+ const outcome = outcomeFromEndEvent(agentEvent);
+ if (!streamOpts.json) renderEnd(agentEvent, outcome);
+ printJsonOnce();
+ settle(outcome);
return;
}
if (agentEvent.type === 'error') {
- if (streamOpts.json && !jsonPrinted) {
- jsonPrinted = true;
- console.log(JSON.stringify(jsonEvents, null, 2));
- }
- log.error(
- `Agent error: ${agentEvent.data?.message || agentEvent.data?.error || 'Unknown error'}`,
- );
- cleanup();
- process.exit(1);
+ if (isSettled) return;
+ const outcome = outcomeFromErrorEvent(agentEvent);
+ printJsonOnce();
+ log.error(`Agent error: ${outcome.error}`);
+ settle(outcome);
+ return;
}
}
if (msg.type === 'session_complete') {
- if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
- jsonPrinted = true;
- console.log(JSON.stringify(jsonEvents, null, 2));
- }
- if (isSettled) return;
- isSettled = true;
- cleanup();
- resolve();
+ printJsonOnce();
+ settle(undefined);
}
};
ws.onerror = (err) => {
- cleanup();
- if (isSettled) return;
- if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
- jsonPrinted = true;
- console.log(JSON.stringify(jsonEvents, null, 2));
- }
- isSettled = true;
- reject(new Error(`Agent gateway WebSocket failed: ${String(err)}`));
+ fail(new Error(`Agent gateway WebSocket failed: ${String(err)}`));
};
ws.onclose = (event) => {
- if (heartbeatTimer) clearInterval(heartbeatTimer);
- if (isSettled) return;
-
- if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
- jsonPrinted = true;
- console.log(JSON.stringify(jsonEvents, null, 2));
- }
- isSettled = true;
// Surface the close code + reason β€” `String(event)` is just "[object CloseEvent]".
const reason = event.reason ? `: ${event.reason}` : '';
- reject(
+ fail(
new Error(`Agent gateway WebSocket closed before completion (code ${event.code}${reason})`),
);
};
@@ -398,10 +551,15 @@ function renderEvent(event: AgentStreamEvent, ctx: RenderContext, options: Strea
}
}
-function renderEnd(event: AgentStreamEvent): void {
+function renderOutcome(outcome: AgentRunOutcome): void {
+ console.log();
+ console.log(describeOutcome(outcome));
+}
+
+function renderEnd(event: AgentStreamEvent, outcome: AgentRunOutcome): void {
console.log();
- const data = event.data || {};
- const parts: string[] = [`${pc.green('βœ“')} Agent finished`];
+ const data = { ...event.data?.finalState, ...event.data };
+ const parts: string[] = [describeOutcome(outcome)];
if (data.stepCount !== undefined) {
parts.push(`${data.stepCount} step${data.stepCount !== 1 ? 's' : ''}`);