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): replace SSE with reconnectable WebSocket and complete history recovery (#20501)

Arvin Xue8d2ab3a3c9e
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.md
index cbfb15e2415..60f79569acd 100644
--- a/.agents/acceptance/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -218,13 +218,15 @@ stale standalone install: a recently added workspace package fails to resolve
edited-file cards, works, topic content), drive the run with
```bash
- lh agent run -a local --sse --json -p '<prompt>' [-t < agentId > --device < topicId > ]
+ lh agent run -a <agentId> --json -p '<prompt>' [-t <topicId>] [--device local]
```
- and use the browser only to capture the rendered evidence afterwards. `--sse`
- is REQUIRED against a local dev server β€” without it the run dies with
- `Gateway auth failed: signature verification failed` (local agent-gateway
- JWKS mismatch; see `references/probe-field-notes.md` E43). `--json` gives assertable
+ and use the browser only to capture the rendered evidence afterwards. CLI
+ streaming uses the agent gateway WebSocket only. For local runs, configure
+ both the backend and CLI to use the same local `AGENT_GATEWAY_URL`, with
+ matching service-token and local JWT verification configuration (see
+ `references/agent-gateway.md`). The production gateway cannot verify local
+ JWT signatures; there is no SSE fallback. `--json` gives assertable
output; reuse `-t` to chain multi-step cases in one topic. This is faster and
far more deterministic than typing prompts through agent-browser, and the
server-side state it produces is identical.
diff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.md
index c6d7b17cef6..b597568f22c 100644
--- a/.agents/skills/cli/SKILL.md
+++ b/.agents/skills/cli/SKILL.md
@@ -81,7 +81,7 @@ apps/cli/src/
β”œβ”€β”€ utils/
β”‚ β”œβ”€β”€ logger.ts # Logging (verbose mode)
β”‚ β”œβ”€β”€ format.ts # Table output, JSON, timeAgo/timeUntil, truncate
-β”‚ └── agentStream.ts # SSE streaming for agent runs
+β”‚ └── agentStream.ts # WebSocket streaming for agent runs and task follow
└── constants/
└── urls.ts # Official server & gateway URLs
```
diff --git a/.agents/skills/cli/references/agent.md b/.agents/skills/cli/references/agent.md
index 0358ab2a46f..b2b90f3ce7a 100644
--- a/.agents/skills/cli/references/agent.md
+++ b/.agents/skills/cli/references/agent.md
@@ -112,11 +112,10 @@ lh agent duplicate <agentId> [-t <title>]
## `lh agent run`
-Start an agent execution. Streams over the agent gateway WebSocket by default, or via SSE with
-`--sse`.
+Start an agent execution. Streams over the agent gateway WebSocket.
```bash
-lh agent run [-a <id>] [-s <slug>] [-p <text>] [-t <id>] [--no-auto-start] [--device <target>] [--no-headless] [--tool <id>]... [--skill <id>]... [--json] [-v] [--replay <file>] [--sse]
+lh agent run [-a <id>] [-s <slug>] [-p <text>] [-t <id>] [--no-auto-start] [--device <target>] [--no-headless] [--tool <id>]... [--skill <id>]... [--json] [-v] [--replay <file>]
```
| Option | Description |
@@ -133,19 +132,37 @@ lh agent run [-a <id>] [-s <slug>] [-p <text>] [-t <id>] [--no-auto-start] [--de
| `--json` | Output full JSON event stream |
| `-v, --verbose` | Show detailed tool call info |
| `--replay <file>` | Replay events from saved JSON file (offline) |
-| `--sse` | Force SSE stream instead of the WebSocket gateway |
### Streaming Behavior
-Uses `utils/agentStream.ts`. By default, streams over the agent gateway WebSocket; pass `--sse` to
-force the legacy SSE endpoint instead. If the live stream drops before the run finishes, the CLI
-falls back to polling `agent status` every 10 seconds until the run reaches a terminal state.
+Uses `utils/agentStream.ts`. The agent gateway WebSocket delivers real-time notifications;
+the authenticated `aiAgent.getOperationStreamHistory` API supplies the ordered event journal.
+JWT and API-key authentication are supported. Reconnects refresh credentials and retry with
+exponential backoff (up to six consecutive failures, capped at 15 seconds). A heartbeat
+watchdog detects half-open sockets. History reads also check for a lost terminal notification.
+
+The journal is replayed in exclusive-cursor pages on connection and reconnect, so output
+is not duplicated or lost when the gateway buffer is trimmed or hibernated. JSON output
+remains one array. Missing/truncated/expired history is an unknown outcome (exit 3), never
+a successful recovery. Transport recovery does not restart the server-side run.
+
+Self-hosted and local servers need a matching gateway configured with `AGENT_GATEWAY_URL`
+on both the server and CLI, and a matching server-side gateway service token. The gateway
+must trust the server's JWT signing key or support API-key verification against that server.
1. Sends agent run request to backend, receiving an `operationId`
-2. Connects to the gateway WebSocket (or SSE endpoint with `--sse`) and streams events in real-time
+2. Connects to the gateway WebSocket and streams events in real-time
3. Displays: text chunks, tool call status, operation progress
4. Shows final token usage and cost summary
+Task `start --follow`, `run --follow`, and `run --topics N` use the same WebSocket
+transport. Each topic waits for completion before the next begins. A failed stream
+stops the sequence without sending a completion heartbeat or starting another topic.
+Full history recovery is available within the server stream's existing two-hour inactivity
+retention window (each publish renews it). Streams are no longer trimmed at 1,000 events.
+This is temporary Redis retention, not permanent archival storage; it increases Redis
+memory requirements. Existing pre-deploy streams with a trimmed prefix cannot be recovered.
+
### Replay Mode
`--replay <file>` reads a saved JSON event stream for offline debugging without server connection.
diff --git a/.agents/skills/cli/references/generate.md b/.agents/skills/cli/references/generate.md
index 5fb223b95ee..c7fd1610470 100644
--- a/.agents/skills/cli/references/generate.md
+++ b/.agents/skills/cli/references/generate.md
@@ -27,12 +27,13 @@ lh generate (alias: gen)
## `lh generate text <prompt>` / `lh gen text <prompt>`
-Generate text completion.
+Generate a complete text response. Incremental streaming is not supported; the agent
+gateway WebSocket handles agent operations, not this single-completion endpoint.
**Source**: `apps/cli/src/commands/generate/text.ts`
```bash
-lh gen text <prompt> [-m <model>] [-p <provider>] [-s <prompt>] [--temperature <n>] [--max-tokens <n>] [--stream] [--json] [--pipe]
+lh gen text <prompt> [-m <model>] [-p <provider>] [-s <prompt>] [--temperature <n>] [--max-tokens <n>] [--json] [--pipe]
```
```bash
@@ -46,7 +47,6 @@ echo "context" | lh gen text "summarize" --pipe
| `-s, --system <prompt>` | System prompt | - |
| `--temperature <n>` | Temperature (0-2) | - |
| `--max-tokens <n>` | Maximum output tokens | - |
-| `--stream` | Enable streaming output | `false` |
| `--json` | Output full JSON response | `false` |
| `--pipe` | Read additional context from stdin | `false` |
diff --git a/apps/cli/e2e/agent.e2e.test.ts b/apps/cli/e2e/agent.e2e.test.ts
index 7bf7cc1a743..5f245ce9a7e 100644
--- a/apps/cli/e2e/agent.e2e.test.ts
+++ b/apps/cli/e2e/agent.e2e.test.ts
@@ -12,7 +12,7 @@ import { describe, expect, it } from 'vitest';
*
* These tests create a real agent, verify CRUD operations, then clean up.
* Note: `agent run` and `agent status` are not tested here as they require
- * active SSE connections and running agents.
+ * active WebSocket connections and running agents.
*/
const CLI = process.env.LH_CLI_PATH || 'lh';
@@ -20,7 +20,7 @@ const TIMEOUT = 30_000;
function run(args: string): string {
return execSync(`${CLI} ${args}`, {
- encoding: 'utf-8',
+ encoding: 'utf8',
env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },
timeout: TIMEOUT,
}).trim();
diff --git a/apps/cli/src/api/client.test.ts b/apps/cli/src/api/client.test.ts
index 72bb8bf5617..92ac55659f5 100644
--- a/apps/cli/src/api/client.test.ts
+++ b/apps/cli/src/api/client.test.ts
@@ -27,6 +27,7 @@ const headersOfLastLink = () => {
describe('api/client workspace scoping', () => {
const originalJwt = process.env.LOBEHUB_JWT;
+ const originalApiKey = process.env.LOBEHUB_CLI_API_KEY;
const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;
beforeEach(() => {
@@ -40,6 +41,9 @@ describe('api/client workspace scoping', () => {
if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;
else process.env.LOBEHUB_JWT = originalJwt;
+ if (originalApiKey === undefined) delete process.env.LOBEHUB_CLI_API_KEY;
+ else process.env.LOBEHUB_CLI_API_KEY = originalApiKey;
+
if (originalWorkspaceId === undefined) delete process.env.LOBEHUB_WORKSPACE_ID;
else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;
});
@@ -53,10 +57,36 @@ describe('api/client workspace scoping', () => {
it('sends a renewed LOBEHUB_JWT on requests from an existing client', async () => {
const { getTrpcClient } = await import('./client');
await getTrpcClient();
- expect(headersOfLastLink()).toMatchObject({ 'Oidc-Auth': 'env-jwt' });
+ expect(await headersOfLastLink()).toMatchObject({ 'Oidc-Auth': 'env-jwt' });
process.env.LOBEHUB_JWT = 'renewed-jwt';
- expect(headersOfLastLink()).toMatchObject({ 'Oidc-Auth': 'renewed-jwt' });
+ expect(await headersOfLastLink()).toMatchObject({ 'Oidc-Auth': 'renewed-jwt' });
+ });
+
+ it('refreshes stored-login credentials for journal reads on a cached client', async () => {
+ delete process.env.LOBEHUB_JWT;
+ delete process.env.LOBEHUB_CLI_API_KEY;
+ const { getValidToken } = await import('../auth/refresh');
+ vi.mocked(getValidToken).mockResolvedValue({
+ credentials: { accessToken: 'original-token' },
+ status: 'ok',
+ });
+ const { getTrpcClient } = await import('./client');
+ const client = await getTrpcClient('workspace-1');
+ expect(await headersOfLastLink()).toMatchObject({
+ 'Oidc-Auth': 'original-token',
+ 'X-Workspace-Id': 'workspace-1',
+ });
+
+ vi.mocked(getValidToken).mockResolvedValue({
+ credentials: { accessToken: 'renewed-token' },
+ status: 'ok',
+ });
+ expect(await getTrpcClient('workspace-1')).toBe(client);
+ expect(await headersOfLastLink()).toMatchObject({
+ 'Oidc-Auth': 'renewed-token',
+ 'X-Workspace-Id': 'workspace-1',
+ });
});
it('creates an anonymous Lambda client without resolving credentials or workspace headers', async () => {
@@ -90,14 +120,14 @@ describe('api/client workspace scoping', () => {
const { getToolsTrpcClient } = await import('./client');
await getToolsTrpcClient();
- expect(headersOfLastLink()).toMatchObject({ 'X-Workspace-Id': 'workspace-1' });
+ expect(await headersOfLastLink()).toMatchObject({ 'X-Workspace-Id': 'workspace-1' });
});
it('omits the header for the tools client in personal mode', async () => {
const { getToolsTrpcClient } = await import('./client');
await getToolsTrpcClient();
- expect(headersOfLastLink()).not.toHaveProperty('X-Workspace-Id');
+ expect(await headersOfLastLink()).not.toHaveProperty('X-Workspace-Id');
});
it('caches tools clients per workspace instead of returning the first one forever', async () => {
diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.ts
index a1ccfae06f9..870c76ed908 100644
--- a/apps/cli/src/api/client.ts
+++ b/apps/cli/src/api/client.ts
@@ -21,7 +21,7 @@ const _clients = new Map<string, TrpcClient>();
const _toolsClients = new Map<string, ToolsTrpcClient>();
async function getAuthAndServer(): Promise<{
- headers: () => Record<string, string>;
+ headers: () => Record<string, string> | Promise<Record<string, string>>;
serverUrl: string;
}> {
// Precedence lives in `pickAuthSource`, shared with `resolveToken` and
@@ -61,10 +61,17 @@ async function getAuthAndServer(): Promise<{
}
const serverUrl = resolveServerUrl();
- const { accessToken } = result.credentials;
-
return {
- headers: () => ({ 'Oidc-Auth': accessToken }),
+ // Cached clients outlive access tokens. Resolve stored credentials for
+ // every request, including journal pages after a WebSocket reconnect.
+ headers: async () => {
+ const current = await getValidToken();
+ if (current.status !== 'ok') {
+ const report = describeTokenLookup(current);
+ throw new Error(report ? `${report.detail} ${report.fix}` : 'No authentication found');
+ }
+ return { 'Oidc-Auth': current.credentials.accessToken };
+ },
serverUrl,
};
}
@@ -79,7 +86,7 @@ export async function getTrpcClient(workspaceId?: string): Promise<TrpcClient> {
const client = createTRPCClient<LambdaRouter>({
links: [
httpLink({
- headers: () => withWorkspaceHeader(headers(), wsId),
+ headers: async () => withWorkspaceHeader(await headers(), wsId),
transformer: superjson,
url: `${serverUrl}/trpc/lambda`,
}),
@@ -153,7 +160,7 @@ export async function getToolsTrpcClient(workspaceId?: string): Promise<ToolsTrp
const client = createTRPCClient<ToolsRouter>({
links: [
httpLink({
- headers: () => withWorkspaceHeader(headers(), wsId),
+ headers: async () => withWorkspaceHeader(await headers(), wsId),
transformer: superjson,
url: `${serverUrl}/trpc/tools`,
}),
diff --git a/apps/cli/src/api/http.test.ts b/apps/cli/src/api/http.test.ts
index 48ad0f93a8e..d38f01020e7 100644
--- a/apps/cli/src/api/http.test.ts
+++ b/apps/cli/src/api/http.test.ts
@@ -80,4 +80,22 @@ describe('api/http auth helpers', () => {
'X-Workspace-Id': 'workspace-1',
});
});
+
+ /**
+ * A reconnect must not end the process: the journal and the status endpoint may still accept the
+ * current access token, and the command's polling fallback only runs if this rejects.
+ */
+ it('should throw instead of exiting when a reconnect resolves no credential', async () => {
+ mockGetValidToken.mockResolvedValue({ status: 'no-login' });
+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('process.exit must not run on a reconnect');
+ }) as unknown as typeof process.exit);
+
+ const { resolveAgentStreamAuthInfo } = await import('./http');
+
+ await expect(resolveAgentStreamAuthInfo()).rejects.toThrow(/No authentication found/);
+ expect(exit).not.toHaveBeenCalled();
+
+ exit.mockRestore();
+ });
});
diff --git a/apps/cli/src/api/http.ts b/apps/cli/src/api/http.ts
index f9677af45ab..28c57fceac5 100644
--- a/apps/cli/src/api/http.ts
+++ b/apps/cli/src/api/http.ts
@@ -80,7 +80,25 @@ export interface AgentStreamAuthInfo {
tokenType: AgentStreamTokenType;
}
-export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<AgentStreamAuthInfo> {
+export interface AgentStreamAuthOptions {
+ /**
+ * `false` for the auth resolver a socket reconnect calls.
+ *
+ * Exiting is right before a command has produced anything: there is no
+ * outcome to report and no channel to report it on. It is wrong for a
+ * reconnect in the middle of a run β€” the stored access token may still
+ * authenticate the journal and the status endpoint, and the caller has its
+ * own polling fallback. Throwing lets the transport fail as a Gateway
+ * problem and hand control back instead of killing the process.
+ */
+ exitOnMissing?: boolean;
+}
+
+export async function getAgentStreamAuthInfo(
+ workspaceId?: string,
+ options: AgentStreamAuthOptions = {},
+): Promise<AgentStreamAuthInfo> {
+ const { exitOnMissing = true } = options;
const serverUrl = resolveServerUrl();
const envJwt = process.env.LOBEHUB_JWT;
@@ -106,11 +124,12 @@ export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<Agen
const result = await getValidToken();
if (result.status !== 'ok') {
const report = describeTokenLookup(result);
- log.error(
- report
- ? `${report.detail} ${report.fix}`
- : `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}.`,
- );
+ const message = report
+ ? `${report.detail} ${report.fix}`
+ : `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}.`;
+ if (!exitOnMissing) throw new Error(message);
+
+ log.error(message);
process.exit(1);
return {
@@ -128,3 +147,11 @@ export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<Agen
tokenType: 'jwt',
};
}
+
+/**
+ * Auth for a stream that may reconnect mid-run: same resolution as
+ * {@link getAgentStreamAuthInfo}, but a missing or unrefreshable credential
+ * throws instead of ending the process.
+ */
+export const resolveAgentStreamAuthInfo = (workspaceId?: string) =>
+ getAgentStreamAuthInfo(workspaceId, { exitOnMissing: false });
diff --git a/apps/cli/src/auth/refresh.test.ts b/apps/cli/src/auth/refresh.test.ts
index 4572d8e7081..c1503d8c3e9 100644
--- a/apps/cli/src/auth/refresh.test.ts
+++ b/apps/cli/src/auth/refresh.test.ts
@@ -108,6 +108,42 @@ describe('getValidToken', () => {
});
});
+ /**
+ * A socket reconnect races the journal catch-up it triggers. Both used to spend the same rotating
+ * refresh token, the loser came back `invalid_grant`, and a passing disconnect was then reported
+ * as a dead login.
+ */
+ it('refreshes once when two callers race on the same rotating token', async () => {
+ vi.mocked(loadCredentials).mockReturnValue(expiredCredentials('stored-refresh-token'));
+
+ let release: () => void = () => {};
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ vi.mocked(fetch).mockImplementation(async () => {
+ await gate;
+ return {
+ json: vi.fn().mockResolvedValue({
+ access_token: 'new-access-token',
+ expires_in: 3600,
+ refresh_token: 'rotated-token',
+ token_type: 'Bearer',
+ }),
+ ok: true,
+ } as any;
+ });
+
+ const first = getValidToken();
+ const second = getValidToken();
+ release();
+
+ const [a, b] = await Promise.all([first, second]);
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(a).toMatchObject({ credentials: { refreshToken: 'rotated-token' }, status: 'ok' });
+ expect(b).toBe(a);
+ });
+
/**
* The regression this classification exists for: a refresh that never got an answer used to be
* indistinguishable from having no login at all, so every caller told the user to run `login`
diff --git a/apps/cli/src/auth/refresh.ts b/apps/cli/src/auth/refresh.ts
index 5621371cdf9..baf9eed9736 100644
--- a/apps/cli/src/auth/refresh.ts
+++ b/apps/cli/src/auth/refresh.ts
@@ -39,6 +39,18 @@ const TRANSIENT_STATUSES = new Set([408, 425, 429]);
*/
const CREDENTIAL_SPENT_ERROR = 'invalid_grant';
+/**
+ * The refresh currently on the wire, shared by every caller.
+ *
+ * A WebSocket reconnect and the journal catch-up it triggers can both find the
+ * stored token inside the refresh window. The provider rotates refresh tokens,
+ * so the second request spends one that is already gone, comes back
+ * `invalid_grant`, and a transient disconnect is then reported as a dead login β€”
+ * which is exactly the case where the run still has recovery attempts left. One
+ * refresh at a time; concurrent callers ride the same result.
+ */
+let refreshInFlight: Promise<TokenLookup> | undefined;
+
/**
* Get a valid access token, refreshing if expired.
*/
@@ -54,8 +66,20 @@ export async function getValidToken(bufferSeconds = 60): Promise<TokenLookup> {
// Token expired β€” try refresh
if (!credentials.refreshToken) return { status: 'no-login' };
+ if (refreshInFlight) return refreshInFlight;
+
+ const pending = refreshStoredToken(credentials);
+ refreshInFlight = pending;
+ try {
+ return await pending;
+ } finally {
+ if (refreshInFlight === pending) refreshInFlight = undefined;
+ }
+}
+
+const refreshStoredToken = async (credentials: StoredCredentials): Promise<TokenLookup> => {
const serverUrl = resolveServerUrl();
- const refreshed = await refreshAccessToken(serverUrl, credentials.refreshToken);
+ const refreshed = await refreshAccessToken(serverUrl, credentials.refreshToken!);
if (refreshed.status !== 'ok') return refreshed;
const updated: StoredCredentials = {
@@ -68,7 +92,7 @@ export async function getValidToken(bufferSeconds = 60): Promise<TokenLookup> {
saveCredentials(updated);
return { credentials: updated, status: 'ok' };
-}
+};
/**
* What went wrong, and what the user can do about it.
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index a5ea4860f3d..2123570cba1 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -63,17 +63,9 @@ const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
getTrpcClient: vi.fn(),
}));
-const { mockStreamAgentEvents } = vi.hoisted(() => ({
- mockStreamAgentEvents: vi.fn(),
-}));
-
-const { mockReplayAgentEvents, mockStreamAgentEventsViaWebSocket } = vi.hoisted(() => ({
+const { mockFollowAgentRun, mockReplayAgentEvents } = vi.hoisted(() => ({
+ mockFollowAgentRun: vi.fn(),
mockReplayAgentEvents: vi.fn(),
- mockStreamAgentEventsViaWebSocket: vi.fn(),
-}));
-
-const { mockGetAgentStreamAuthInfo } = vi.hoisted(() => ({
- mockGetAgentStreamAuthInfo: vi.fn(),
}));
const { mockResolveLocalDeviceId } = vi.hoisted(() => ({
@@ -86,12 +78,8 @@ const { mockReadStdinText } = vi.hoisted(() => ({
vi.mock('node:stream/consumers', () => ({ text: mockReadStdinText }));
vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
-vi.mock('../api/http', () => ({ getAgentStreamAuthInfo: mockGetAgentStreamAuthInfo }));
-vi.mock('../utils/agentStream', () => ({
- replayAgentEvents: mockReplayAgentEvents,
- streamAgentEvents: mockStreamAgentEvents,
- streamAgentEventsViaWebSocket: mockStreamAgentEventsViaWebSocket,
-}));
+vi.mock('../utils/agentStream', () => ({ replayAgentEvents: mockReplayAgentEvents }));
+vi.mock('./agent/followRun', () => ({ followAgentRun: mockFollowAgentRun }));
vi.mock('../utils/device', () => ({ resolveLocalDeviceId: mockResolveLocalDeviceId }));
describe('agent command', () => {
let exitSpy: ReturnType<typeof vi.spyOn>;
@@ -102,14 +90,9 @@ describe('agent command', () => {
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
- mockGetAgentStreamAuthInfo.mockResolvedValue({
- headers: { 'Oidc-Auth': 'test-token' },
- serverUrl: 'https://example.com',
- });
- mockStreamAgentEvents.mockResolvedValue(undefined);
mockReplayAgentEvents.mockReset();
- mockStreamAgentEventsViaWebSocket.mockReset();
- mockStreamAgentEventsViaWebSocket.mockResolvedValue(undefined);
+ mockFollowAgentRun.mockReset();
+ mockFollowAgentRun.mockResolvedValue({ kind: 'completed', status: 'done' });
mockResolveLocalDeviceId.mockReset();
mockReadStdinText.mockReset();
for (const method of Object.values(mockTrpcClient.agent)) {
@@ -727,51 +710,13 @@ describe('agent command', () => {
expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
expect.objectContaining({ agentId: 'a1', prompt: 'Hello' }),
);
- expect(mockStreamAgentEventsViaWebSocket).toHaveBeenCalledWith(
- expect.objectContaining({
- gatewayUrl: expect.any(String),
- json: undefined,
- operationId: 'op-123',
- serverUrl: 'https://example.com',
- token: undefined,
- tokenType: undefined,
- verbose: undefined,
- }),
- );
- expect(mockStreamAgentEvents).not.toHaveBeenCalled();
- });
-
- it('should fall back to SSE when --sse is provided', async () => {
- mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
- operationId: 'op-sse',
- success: true,
+ expect(mockFollowAgentRun).toHaveBeenCalledWith('op-123', {
+ json: undefined,
+ onStall: expect.any(Function),
+ verbose: undefined,
});
-
- const program = createProgram();
- await program.parseAsync([
- 'node',
- 'test',
- 'agent',
- 'run',
- '--agent-id',
- 'a1',
- '--prompt',
- 'Hello',
- '--sse',
- ]);
-
- expect(mockStreamAgentEvents).toHaveBeenCalledWith(
- 'https://example.com/api/agent/stream?operationId=op-sse',
- expect.objectContaining({ 'Oidc-Auth': 'test-token' }),
- 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();
});
+
it('should support --slug option', async () => {
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
operationId: 'op-456',
@@ -1057,8 +1002,9 @@ describe('agent command', () => {
'--json',
]);
- expect(mockStreamAgentEventsViaWebSocket).toHaveBeenCalledWith(
- expect.objectContaining({ json: true, operationId: 'op-j' }),
+ expect(mockFollowAgentRun).toHaveBeenCalledWith(
+ 'op-j',
+ expect.objectContaining({ json: true }),
);
});
});
@@ -1289,7 +1235,7 @@ describe('agent command', () => {
// ── #19613: live-stream completion ────────────────────────────
it('exits 0 when the stream reports the run done', async () => {
- mockStreamAgentEventsViaWebSocket.mockResolvedValue({ kind: 'completed', status: 'done' });
+ mockFollowAgentRun.mockResolvedValue({ kind: 'completed', status: 'done' });
await run();
expect(process.exitCode).toBeUndefined();
expect(exitSpy).not.toHaveBeenCalled();
@@ -1300,25 +1246,25 @@ describe('agent command', () => {
['failed', 1],
['interrupted', 1],
] as const)('exits %s β†’ %i from the WebSocket stream', async (kind, code) => {
- mockStreamAgentEventsViaWebSocket.mockResolvedValue({ kind, status: kind });
+ mockFollowAgentRun.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({
+ it('exits 2 for a run parked on human approval over WebSocket, in --json mode too', async () => {
+ mockFollowAgentRun.mockResolvedValue({
kind: 'waiting_for_human',
status: 'waiting_for_human',
});
- await run('--sse', '--json', '--no-headless');
+ await run('--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'));
+ it('a WebSocket stream that cannot be opened falls back to polling the run outcome', async () => {
+ mockFollowAgentRun.mockRejectedValue(new Error('Agent stream failed: 502 Bad Gateway'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('done'));
- await run('--sse');
+ await run();
expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalled();
expect(exitSpy).not.toHaveBeenCalled();
@@ -1364,7 +1310,7 @@ describe('agent command', () => {
it('polls the envelope the server returns and stops on currentState.status=done', async () => {
vi.useFakeTimers();
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(
+ mockFollowAgentRun.mockRejectedValue(
new Error('Agent gateway WebSocket failed: [object ErrorEvent]'),
);
mockTrpcClient.aiAgent.getOperationStatus.query
@@ -1379,7 +1325,7 @@ describe('agent command', () => {
});
it('falls back to the envelope summary flags when there is no status string', async () => {
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
hasError: false,
isCompleted: true,
@@ -1390,7 +1336,7 @@ describe('agent command', () => {
it('gives up loudly with exit 3 on an answer whose status it cannot read', async () => {
vi.useFakeTimers();
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ foo: 1 });
await runWithTimers(60_000);
@@ -1407,7 +1353,7 @@ describe('agent command', () => {
['interrupted', 1],
['waiting_for_human', 2],
] as const)('poll ending in %s exits %i', async (status, code) => {
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(
envelope(status, status === 'error' ? { error: 'model quota exceeded' } : {}),
);
@@ -1420,7 +1366,7 @@ describe('agent command', () => {
it.each(['failed', 'cancelled', 'aborted'])(
'legacy flat status %s is not reported as success',
async (status) => {
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ status });
await run();
expect(process.exitCode).toBe(1);
@@ -1428,7 +1374,7 @@ describe('agent command', () => {
);
it('a missing status result exits 3 without claiming the run finished or expired', async () => {
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(null);
await run();
expect(process.exitCode).toBe(3);
@@ -1438,19 +1384,11 @@ describe('agent command', () => {
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(
+ mockFollowAgentRun.mockRejectedValue(
new Error('Agent gateway WebSocket sent no progress for 60s; status check failed: x'),
);
mockTrpcClient.aiAgent.getOperationStatus.query
@@ -1467,7 +1405,7 @@ describe('agent command', () => {
});
it('the WebSocket quiet-window probe keeps waiting on an active run instead of failing it', async () => {
- mockStreamAgentEventsViaWebSocket.mockImplementation(async (opts: any) => {
+ mockFollowAgentRun.mockImplementation(async (_operationId: string, opts: any) => {
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValueOnce(envelope('running'));
expect(await opts.onStall()).toBeUndefined(); // active β†’ keep streaming
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValueOnce(
@@ -1483,7 +1421,7 @@ describe('agent command', () => {
it('bounds an in-flight status request that never answers', async () => {
vi.useFakeTimers();
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query
.mockImplementationOnce(() => new Promise(() => {})) // hangs
.mockResolvedValueOnce(envelope('done'));
@@ -1498,7 +1436,7 @@ describe('agent command', () => {
it('stops after repeated failed status requests with exit 3, not success', async () => {
vi.useFakeTimers();
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockRejectedValue(new Error('ECONNRESET'));
await runWithTimers(60_000);
@@ -1509,7 +1447,7 @@ describe('agent command', () => {
it('--timeout stops waiting with exit 3 and points at lh agent status', async () => {
vi.useFakeTimers();
- mockStreamAgentEventsViaWebSocket.mockImplementation(() => new Promise(() => {}));
+ mockFollowAgentRun.mockImplementation(() => new Promise(() => {}));
await runWithTimers(5_000, '--timeout', '5');
@@ -1519,7 +1457,7 @@ describe('agent command', () => {
it('waits on an active run indefinitely by default (no built-in deadline)', async () => {
vi.useFakeTimers();
- mockStreamAgentEventsViaWebSocket.mockRejectedValue(new Error('ws down'));
+ mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('running'));
const done = vi.fn();
diff --git a/apps/cli/src/commands/agent/followRun.test.ts b/apps/cli/src/commands/agent/followRun.test.ts
new file mode 100644
index 00000000000..80d4e547b19
--- /dev/null
+++ b/apps/cli/src/commands/agent/followRun.test.ts
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentGatewayUnavailableError, AgentStreamHistoryError } from '../../utils/agentStreamTransport';
+import { followAgentRun } from './followRun';
+
+const { getTrpcClient, historyQuery, streamAgentEvents } = vi.hoisted(() => {
+ const historyQuery = vi.fn();
+ return {
+ getTrpcClient: vi.fn(async () => ({
+ aiAgent: { getOperationStreamHistory: { query: historyQuery } },
+ })),
+ historyQuery,
+ streamAgentEvents: vi.fn(),
+ };
+});
+
+vi.mock('../../api/client', () => ({ getTrpcClient }));
+vi.mock('../../api/http', () => ({ getAgentStreamAuthInfo: vi.fn() }));
+vi.mock('../../settings', () => ({ resolveAgentGatewayUrl: () => 'https://gateway.test' }));
+vi.mock('../../utils/agentStream', () => ({ streamAgentEvents }));
+vi.mock('../../utils/logger', () => ({ log: { error: vi.fn() } }));
+
+describe('followAgentRun', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ historyQuery.mockResolvedValue({
+ available: true,
+ events: [],
+ hasMore: false,
+ nextCursor: '0',
+ });
+ });
+
+ it('reads history pages through the credential-refreshing tRPC client', async () => {
+ streamAgentEvents.mockImplementation(async ({ readHistory }) => {
+ await readHistory('1-0', new AbortController().signal);
+ return { kind: 'completed', status: 'done' };
+ });
+
+ await expect(followAgentRun('op-1')).resolves.toEqual({ kind: 'completed', status: 'done' });
+
+ expect(getTrpcClient).toHaveBeenCalled();
+ expect(historyQuery).toHaveBeenCalledWith(
+ { cursor: '1-0', operationId: 'op-1' },
+ { signal: expect.any(AbortSignal) },
+ );
+ });
+
+ it('resolves an incomplete history as an unknown outcome, never a success', async () => {
+ streamAgentEvents.mockRejectedValue(new AgentStreamHistoryError('History expired'));
+
+ await expect(followAgentRun('op-1')).resolves.toEqual({ kind: 'unknown' });
+ });
+
+ it('rethrows other failures so the caller can choose a fallback', async () => {
+ streamAgentEvents.mockRejectedValue(new Error('boom'));
+
+ await expect(followAgentRun('op-1')).rejects.toThrow('boom');
+ });
+
+ it('rethrows an exhausted gateway so the caller keeps polling the run status', async () => {
+ streamAgentEvents.mockRejectedValue(
+ new AgentGatewayUnavailableError('Reconnect attempts exhausted'),
+ );
+
+ await expect(followAgentRun('op-1')).rejects.toBeInstanceOf(AgentGatewayUnavailableError);
+ });
+
+ it('surfaces a server without the journal as a compatibility failure, not a lost history', async () => {
+ historyQuery.mockRejectedValue(
+ Object.assign(new Error('No procedure found on path "aiAgent.getOperationStreamHistory"'), {
+ data: { code: 'NOT_FOUND' },
+ }),
+ );
+ streamAgentEvents.mockImplementation(async ({ readHistory }) => {
+ await readHistory('1-0', new AbortController().signal);
+ return { kind: 'completed' };
+ });
+
+ await expect(followAgentRun('op-1')).rejects.toMatchObject({
+ name: 'AgentJournalUnsupportedError',
+ });
+ });
+
+ it('keeps an unknown operation id on the incomplete-history path', async () => {
+ historyQuery.mockRejectedValue(
+ Object.assign(new Error('Operation not found'), { data: { code: 'NOT_FOUND' } }),
+ );
+ // Mirror the transport: a non-compatibility read failure becomes a history failure.
+ streamAgentEvents.mockImplementation(async ({ readHistory }) => {
+ try {
+ await readHistory('1-0', new AbortController().signal);
+ } catch (error) {
+ throw new AgentStreamHistoryError((error as Error).message);
+ }
+ return { kind: 'completed' };
+ });
+
+ await expect(followAgentRun('op-1')).resolves.toEqual({ kind: 'unknown' });
+ });
+});
diff --git a/apps/cli/src/commands/agent/followRun.ts b/apps/cli/src/commands/agent/followRun.ts
new file mode 100644
index 00000000000..6d51d4f7bb3
--- /dev/null
+++ b/apps/cli/src/commands/agent/followRun.ts
@@ -0,0 +1,83 @@
+import { getTrpcClient } from '../../api/client';
+import { resolveAgentStreamAuthInfo } from '../../api/http';
+import { resolveAgentGatewayUrl } from '../../settings';
+import type { AgentRunOutcome } from '../../utils/agentRunOutcome';
+import { streamAgentEvents } from '../../utils/agentStream';
+import {
+ AgentGatewayUnavailableError,
+ AgentJournalUnsupportedError,
+ AgentStreamHistoryError,
+} from '../../utils/agentStreamTransport';
+import { log } from '../../utils/logger';
+
+interface FollowAgentRunOptions {
+ json?: boolean;
+ /** See `streamAgentEvents`; omit for runs where long silence is healthy. */
+ onStall?: () => Promise<AgentRunOutcome | undefined>;
+ verbose?: boolean;
+}
+
+/**
+ * tRPC answers a procedure the server does not implement with `NOT_FOUND` and
+ * the path in the message. The CLI ships independently of the server, so an
+ * upgraded CLI against an older self-hosted server hits exactly this.
+ */
+const MISSING_PROCEDURE = /no procedure|not found on path/i;
+
+const isMissingJournalProcedure = (error: unknown) =>
+ MISSING_PROCEDURE.test(String((error as { message?: string })?.message ?? error));
+
+/**
+ * Follow a started operation until its terminal event and render it.
+ *
+ * An incomplete event history resolves as an `unknown` outcome (exit 3), never
+ * a success. Other errors (no gateway configured, or a server without the
+ * journal endpoint) reject so the caller can choose a fallback.
+ */
+export const followAgentRun = async (
+ operationId: string,
+ options: FollowAgentRunOptions = {},
+): Promise<AgentRunOutcome> => {
+ const gatewayUrl = resolveAgentGatewayUrl();
+ if (!gatewayUrl) throw new Error('Agent gateway URL is not configured');
+
+ try {
+ const outcome = await streamAgentEvents({
+ ...options,
+ gatewayUrl,
+ getAuth: () => resolveAgentStreamAuthInfo(),
+ operationId,
+ // The cached client resolves stored credentials per request, so pages
+ // read after a token refresh still authenticate.
+ readHistory: async (cursor, signal) => {
+ try {
+ return await (await getTrpcClient()).aiAgent.getOperationStreamHistory.query(
+ { cursor, operationId },
+ { signal },
+ );
+ } catch (error) {
+ // Server predates the journal: no event stream can be produced, but the
+ // run is still observable through status polling.
+ if (isMissingJournalProcedure(error))
+ throw new AgentJournalUnsupportedError(
+ 'This server has no agent event journal (getOperationStreamHistory); the CLI is newer than the server',
+ );
+ throw error;
+ }
+ },
+ });
+ return outcome ?? { kind: 'unknown' };
+ } catch (error) {
+ // A missing journal is a compatibility gap, not a lost history: let the
+ // caller degrade to polling instead of exiting with an unknown outcome.
+ if (error instanceof AgentJournalUnsupportedError) throw error;
+ // The Gateway never came back while the run was quiet. The journal and the
+ // status endpoint may still be healthy, so this is not an unconfirmable
+ // history either β€” reject so the caller can keep polling instead of
+ // reporting `unknown` and skipping its fallback.
+ if (error instanceof AgentGatewayUnavailableError) throw error;
+ if (!(error instanceof AgentStreamHistoryError)) throw error;
+ log.error(error.message);
+ return { kind: 'unknown' };
+ }
+};
diff --git a/apps/cli/src/commands/agent/run.test.ts b/apps/cli/src/commands/agent/run.test.ts
index a547070acb8..18ce7571ed1 100644
--- a/apps/cli/src/commands/agent/run.test.ts
+++ b/apps/cli/src/commands/agent/run.test.ts
@@ -10,12 +10,8 @@ const { mockExecAgent, mockGetTrpcClient, mockGetUserState } = vi.hoisted(() =>
}));
vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
-vi.mock('../../api/http', () => ({ getAgentStreamAuthInfo: vi.fn() }));
-vi.mock('../../utils/agentStream', () => ({
- replayAgentEvents: vi.fn(),
- streamAgentEvents: vi.fn(),
- streamAgentEventsViaWebSocket: vi.fn(),
-}));
+vi.mock('../../utils/agentStream', () => ({ replayAgentEvents: vi.fn() }));
+vi.mock('./followRun', () => ({ followAgentRun: vi.fn() }));
vi.mock('../../utils/device', () => ({ resolveLocalDeviceId: vi.fn() }));
const runAgent = async (...args: string[]) => {
@@ -42,6 +38,29 @@ describe('lh agent run', () => {
mockExecAgent.mockReset();
});
+ it('declares the member-terminal stream feature so a group run keeps streaming', async () => {
+ const input = await runAgent('--agent-id', 'agt-1', '--prompt', 'Hello');
+
+ // Without it the server mirrors a member's terminal as `agent_runtime_end`,
+ // which the Gateway treats as this session's end and closes the socket.
+ expect(input.streamFeatures).toEqual(['member_runtime_end']);
+ });
+
+ it('retries without streamFeatures when an older server rejects the key', async () => {
+ mockExecAgent
+ .mockRejectedValueOnce(
+ Object.assign(new Error('unrecognized_keys: ["streamFeatures"]'), {
+ data: { code: 'BAD_REQUEST' },
+ }),
+ )
+ .mockResolvedValueOnce({ operationId: 'op-1', success: true, topicId: 'tpc-1' });
+
+ await runAgent('--agent-id', 'agt-1', '--prompt', 'Hello');
+
+ expect(mockExecAgent).toHaveBeenCalledTimes(2);
+ expect(mockExecAgent.mock.calls[1][0]).not.toHaveProperty('streamFeatures');
+ });
+
it('enables each --tool for the run, as an @-mention in chat does', async () => {
const input = await runAgent(
'--agent-id',
diff --git a/apps/cli/src/commands/agent/run.ts b/apps/cli/src/commands/agent/run.ts
index f61eabf9b97..98c0a3978bc 100644
--- a/apps/cli/src/commands/agent/run.ts
+++ b/apps/cli/src/commands/agent/run.ts
@@ -5,20 +5,41 @@ import { type Command, InvalidArgumentError } from 'commander';
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 } from '../../utils/agentRunOutcome';
-import {
- replayAgentEvents,
- streamAgentEvents,
- streamAgentEventsViaWebSocket,
-} from '../../utils/agentStream';
+import { replayAgentEvents } from '../../utils/agentStream';
import { resolveLocalDeviceId } from '../../utils/device';
import { outputJson } from '../../utils/format';
import { log, setVerbose } from '../../utils/logger';
+import { followAgentRun } from './followRun';
import { pollAgentRunStatus, probeRunOutcome, RUN_POLL_INTERVAL_MS } from './runStatus';
+/**
+ * Start a run, retrying without `streamFeatures` on a server old enough to
+ * validate its input strictly: the CLI ships independently of the server, and
+ * `streamFeatures` is an optional key that such a server rejects outright.
+ */
+const startAgentRun = async (
+ client: Awaited<ReturnType<typeof getTrpcClient>>,
+ input: Record<string, any>,
+) => {
+ try {
+ return await client.aiAgent.execAgent.mutate(input as any);
+ } catch (error) {
+ const { data, message } = (error ?? {}) as { data?: { code?: string }; message?: unknown };
+ if (
+ data?.code !== 'BAD_REQUEST' ||
+ typeof message !== 'string' ||
+ !message.includes('unrecognized_keys') ||
+ !message.includes('streamFeatures')
+ ) {
+ throw error;
+ }
+ const { streamFeatures: _rejected, ...legacyInput } = input;
+ return await client.aiAgent.execAgent.mutate(legacyInput as any);
+ }
+};
+
export function registerAgentRunCommand(agent: Command) {
agent
.command('run')
@@ -50,7 +71,6 @@ export function registerAgentRunCommand(agent: Command) {
.option('--detach', 'Start the operation and return its IDs without waiting for events')
.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',
@@ -77,7 +97,6 @@ Exit codes:
replay?: string;
skill?: string[];
slug?: string;
- sse?: boolean;
timeout?: number;
tool?: string[];
topicId?: string;
@@ -148,7 +167,17 @@ Exit codes:
}
// 1. Exec agent to get operationId
- const input: Record<string, any> = { prompt: options.prompt, trigger: 'cli' };
+ const input: Record<string, any> = {
+ prompt: options.prompt,
+ trigger: 'cli',
+ // A group/supervisor run mirrors each member's events onto this
+ // operation's socket. Declaring the feature is what makes the server
+ // forward a member's terminal as the non-terminal `member_runtime_end`
+ // instead of `agent_runtime_end` β€” the Gateway closes the session on
+ // the latter, which would drop every later member and supervisor event
+ // before this CLI could render it.
+ streamFeatures: ['member_runtime_end'],
+ };
if (options.agentId) input.agentId = options.agentId;
if (deviceId) input.deviceId = deviceId;
if (options.slug) input.slug = options.slug;
@@ -206,7 +235,7 @@ Exit codes:
};
}
- const result = await client.aiAgent.execAgent.mutate(input as any);
+ const result = await startAgentRun(client, input);
const r = result as any;
if (!r.success) {
@@ -230,50 +259,25 @@ Exit codes:
log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
}
- // 2. Connect to stream (WebSocket via Gateway, or fallback to SSE)
- const { serverUrl, headers, token, tokenType } = await getAgentStreamAuthInfo();
- const agentGatewayUrl = options.sse ? undefined : resolveAgentGatewayUrl();
-
+ // 2. Follow the run over the agent gateway WebSocket
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,
- });
- }
+ return await followAgentRun(operationId, {
+ 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 }),
+ 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.
+ // The live stream could not be followed at all β€” 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 });
}
-
- // 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;
diff --git a/apps/cli/src/commands/agent/runStatus.ts b/apps/cli/src/commands/agent/runStatus.ts
index 156b5e48d1d..176704514de 100644
--- a/apps/cli/src/commands/agent/runStatus.ts
+++ b/apps/cli/src/commands/agent/runStatus.ts
@@ -93,7 +93,7 @@ export const probeRunOutcome = async (
};
/**
- * Fallback when the live stream (gateway WebSocket / SSE) is unavailable or
+ * Fallback when the live stream (gateway WebSocket) 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.
*
diff --git a/apps/cli/src/commands/generate.test.ts b/apps/cli/src/commands/generate.test.ts
index 9997aaa82c9..dec2a34caaf 100644
--- a/apps/cli/src/commands/generate.test.ts
+++ b/apps/cli/src/commands/generate.test.ts
@@ -189,7 +189,7 @@ describe('generate command', () => {
expect(log.error).not.toHaveBeenCalled();
});
- it('should output collected SSE as JSON when --json is used without --stream', async () => {
+ it('should output collected SSE as JSON when --json is used', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents)));
const program = createProgram();
@@ -202,24 +202,11 @@ describe('generate command', () => {
});
});
- it('should stream Gemini content parts without printing the stop reason', async () => {
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents)));
-
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream']);
-
- const fetchCall = vi.mocked(fetch).mock.calls[0];
- const body = JSON.parse(fetchCall[1]!.body as string);
- expect(body.stream).toBe(true);
-
- expect(writtenText()).toBe('Hello there, how are you?\n');
- });
-
- it('should stream only text events from the LobeHub protocol', async () => {
+ it('should collect only text events from the LobeHub protocol', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(openaiEvents)));
const program = createProgram();
- await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream']);
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi']);
expect(writtenText()).toBe('Hello, world\n');
});
@@ -272,7 +259,7 @@ describe('generate command', () => {
expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('generate image'));
});
- it('should stream plain OpenAI chat-completion chunks', async () => {
+ it('should collect plain OpenAI chat-completion chunks', async () => {
vi.stubGlobal(
'fetch',
vi
@@ -286,22 +273,11 @@ describe('generate command', () => {
);
const program = createProgram();
- await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream']);
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi']);
expect(writtenText()).toBe('Hello\n');
});
- it('should print each SSE event as a JSON line with --stream --json', async () => {
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents.slice(0, 3))));
-
- const program = createProgram();
- await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream', '--json']);
-
- expect(consoleSpy.mock.calls.map(([line]) => JSON.parse(line as string))).toEqual(
- geminiEvents.slice(0, 3),
- );
- });
-
it('should exit when the SSE stream reports an error', async () => {
vi.stubGlobal(
'fetch',
diff --git a/apps/cli/src/commands/generate/text.ts b/apps/cli/src/commands/generate/text.ts
index 0d4457db84f..1f0894b0b10 100644
--- a/apps/cli/src/commands/generate/text.ts
+++ b/apps/cli/src/commands/generate/text.ts
@@ -13,7 +13,6 @@ export function registerTextCommand(parent: Command) {
.option('-s, --system <prompt>', 'System prompt')
.option('--temperature <n>', 'Temperature (0-2)')
.option('--max-tokens <n>', 'Maximum output tokens')
- .option('--stream', 'Enable streaming (SSE, renders incrementally)')
.option('--json', 'Output full JSON response')
.option('--pipe', 'Pipe mode: read additional context from stdin')
.action(
@@ -25,7 +24,6 @@ export function registerTextCommand(parent: Command) {
model: string;
pipe?: boolean;
provider?: string;
- stream?: boolean;
system?: string;
temperature?: string;
},
@@ -54,15 +52,13 @@ export function registerTextCommand(parent: Command) {
}
messages.push({ content: fullPrompt, role: 'user' });
- const useStream = options.stream === true;
-
const payload: Record<string, any> = {
messages,
model,
- // Ask for a plain JSON body when not streaming; runtimes that ignore
- // responseMode still reply with SSE, handled below
- responseMode: useStream ? 'stream' : 'json',
- stream: useStream,
+ // Ask for a plain JSON body; runtimes that ignore responseMode still
+ // reply with SSE, which is collected into one complete result below
+ responseMode: 'json',
+ stream: false,
};
if (options.temperature) payload.temperature = Number.parseFloat(options.temperature);
if (options.maxTokens) payload.max_tokens = Number.parseInt(options.maxTokens, 10);
@@ -109,11 +105,7 @@ export function registerTextCommand(parent: Command) {
return;
}
- if (useStream) {
- await streamSSEResponse(res.body, options.json);
- } else {
- await collectSSEResponse(res.body, options.json);
- }
+ await collectSSEResponse(res.body, options.json);
},
);
}
@@ -242,36 +234,6 @@ function reportSSEError(data: unknown): void {
process.exit(1);
}
-async function streamSSEResponse(body: ReadableStream<Uint8Array>, json?: boolean): Promise<void> {
- let hasText = false;
- let imageCount = 0;
-
- for await (const event of parseSSE(body)) {
- const payload = classifySSEEvent(event);
- if (payload.kind === 'done') break;
-
- if (json) {
- console.log(JSON.stringify(event));
- if (payload.kind === 'error') process.exit(1);
- continue;
- }
-
- if (payload.kind === 'error') {
- process.stdout.write('\n');
- reportSSEError(payload.data);
- return;
- }
- if (payload.kind === 'text') {
- hasText = true;
- process.stdout.write(payload.text);
- } else if (payload.kind === 'image') imageCount++;
- }
-
- if (json) return;
- process.stdout.write('\n');
- if (!hasText && imageCount > 0) warnImageOnlyReply(imageCount);
-}
-
async function collectSSEResponse(body: ReadableStream<Uint8Array>, json?: boolean): Promise<void> {
let content = '';
let reasoning = '';
diff --git a/apps/cli/src/commands/task/lifecycle.test.ts b/apps/cli/src/commands/task/lifecycle.test.ts
index 23512f1376a..8920147405c 100644
--- a/apps/cli/src/commands/task/lifecycle.test.ts
+++ b/apps/cli/src/commands/task/lifecycle.test.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { registerLifecycleCommands } from './lifecycle';
-const { client, streamAgentEvents } = vi.hoisted(() => ({
+const { client, followAgentRun, pollAgentRunStatus } = vi.hoisted(() => ({
client: {
task: {
addComment: { mutate: vi.fn() },
@@ -15,14 +15,16 @@ const { client, streamAgentEvents } = vi.hoisted(() => ({
},
topic: { getTopicDetail: { query: vi.fn() } },
},
- streamAgentEvents: vi.fn(),
+ followAgentRun: vi.fn(),
+ pollAgentRunStatus: 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('../agent/followRun', () => ({ followAgentRun }));
+vi.mock('../agent/runStatus', () => ({
+ RUN_POLL_INTERVAL_MS: 10_000,
+ pollAgentRunStatus,
}));
-vi.mock('../../utils/agentStream', () => ({ streamAgentEvents }));
vi.mock('../../utils/logger', () => ({
log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
}));
@@ -160,7 +162,8 @@ describe('task lifecycle β€” following the agent stream', () => {
throw new Error(`process.exit(${code})`);
}) as any);
for (const fn of Object.values(client.task)) Object.values(fn)[0].mockReset();
- streamAgentEvents.mockReset();
+ followAgentRun.mockReset();
+ pollAgentRunStatus.mockReset();
client.task.find.query.mockResolvedValue({
data: { assigneeAgentId: 'agt_1', identifier: 'T-1', status: 'pending' },
});
@@ -176,29 +179,36 @@ describe('task lifecycle β€” following the agent stream', () => {
afterEach(() => {
exitSpy.mockRestore();
+ process.exitCode = undefined;
});
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' });
+ followAgentRun.mockResolvedValue({
+ error: 'boom',
+ kind: 'failed',
+ status: 'error',
+ });
- await expect(
- createProgram().parseAsync(['node', 'test', 'task', 'run', 'T-1', '--topics', '2']),
- ).rejects.toThrow('process.exit(1)');
+ await createProgram().parseAsync(['node', 'test', 'task', 'run', 'T-1', '--topics', '2']);
+ expect(process.exitCode).toBe(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' });
+ followAgentRun.mockResolvedValue({
+ error: 'boom',
+ kind: 'failed',
+ status: 'error',
+ });
- await expect(
- createProgram().parseAsync(['node', 'test', 'task', 'start', 'T-1', '--follow']),
- ).rejects.toThrow('process.exit(1)');
+ await createProgram().parseAsync(['node', 'test', 'task', 'start', 'T-1', '--follow']);
+ expect(process.exitCode).toBe(1);
});
it('a completed run sends the heartbeat and continues the sequence', async () => {
- streamAgentEvents.mockResolvedValue({ kind: 'completed', status: 'done' });
+ followAgentRun.mockResolvedValue({ kind: 'completed', status: 'done' });
await createProgram().parseAsync(['node', 'test', 'task', 'run', 'T-1', '--topics', '2']);
@@ -206,6 +216,40 @@ describe('task lifecycle β€” following the agent stream', () => {
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');
+ expect(followAgentRun.mock.calls[0][1]).not.toHaveProperty('onStall');
+ });
+
+ it('falls back to status polling when the server has no agent event journal', async () => {
+ followAgentRun.mockRejectedValue(
+ Object.assign(new Error('This server has no agent event journal'), {
+ name: 'AgentJournalUnsupportedError',
+ }),
+ );
+ pollAgentRunStatus.mockResolvedValue({ kind: 'completed', status: 'done' });
+
+ await createProgram().parseAsync(['node', 'test', 'task', 'start', 'T-1', '--follow']);
+
+ expect(pollAgentRunStatus).toHaveBeenCalledWith(
+ client,
+ 'op-1',
+ expect.objectContaining({ json: undefined }),
+ );
+ expect(client.task.heartbeat.mutate).toHaveBeenCalled();
+ expect(process.exitCode).toBeUndefined();
});
+
+ it.each([
+ ['waiting_for_human', 2],
+ ['interrupted', 1],
+ ['unknown', 3],
+ ] as const)(
+ 'stops the topic sequence for %s without a completion heartbeat',
+ async (kind, code) => {
+ followAgentRun.mockResolvedValue({ kind });
+ await createProgram().parseAsync(['node', 'test', 'task', 'run', 'T-1', '--topics', '2']);
+ expect(process.exitCode).toBe(code);
+ expect(client.task.run.mutate).toHaveBeenCalledTimes(1);
+ expect(client.task.heartbeat.mutate).not.toHaveBeenCalled();
+ },
+ );
});
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.ts
index 5872fffc869..d2b9f27d5bc 100644
--- a/apps/cli/src/commands/task/lifecycle.ts
+++ b/apps/cli/src/commands/task/lifecycle.ts
@@ -2,11 +2,36 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
-import { getAuthInfo } from '../../api/http';
-import { streamAgentEvents } from '../../utils/agentStream';
+import { AGENT_RUN_EXIT_CODES } from '../../utils/agentRunOutcome';
import { resolveLocalDeviceId } from '../../utils/device';
import { outputJson } from '../../utils/format';
import { log } from '../../utils/logger';
+import { followAgentRun } from '../agent/followRun';
+import { pollAgentRunStatus, RUN_POLL_INTERVAL_MS } from '../agent/runStatus';
+
+type LifecycleClient = Awaited<ReturnType<typeof getTrpcClient>>;
+
+/**
+ * Follow a task run, degrading to status polling whenever the live stream cannot
+ * be used β€” a gateway that is unreachable, or a server predating the CLI's agent
+ * event journal (the CLI ships independently of the server). Without this the
+ * task would exit 3 having printed nothing.
+ */
+const followTaskRun = async (
+ client: LifecycleClient,
+ operationId: string,
+ options: { json?: boolean; verbose?: boolean },
+) => {
+ try {
+ return await followAgentRun(operationId, { json: options.json, verbose: options.verbose });
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ log.warn(
+ `Live stream unavailable (${reason}). Polling run status every ${RUN_POLL_INTERVAL_MS / 1000}s…`,
+ );
+ return pollAgentRunStatus(client, operationId, { json: options.json });
+ }
+};
export function registerLifecycleCommands(task: Command) {
// ── start ──────────────────────────────────────────────
@@ -73,16 +98,16 @@ export function registerLifecycleCommands(task: Command) {
return;
}
- const { serverUrl, headers } = await getAuthInfo();
- const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(result.operationId)}`;
-
- const outcome = await streamAgentEvents(streamUrl, headers, {
+ const outcome = await followTaskRun(client, result.operationId, {
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);
+ if (outcome.kind !== 'completed') {
+ process.exitCode = AGENT_RUN_EXIT_CODES[outcome.kind];
+ return;
+ }
// Send heartbeat after completion
try {
@@ -201,16 +226,16 @@ export function registerLifecycleCommands(task: Command) {
return;
}
- // Connect to SSE stream and wait for completion
- const { serverUrl, headers } = await getAuthInfo();
- const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
-
- const outcome = await streamAgentEvents(streamUrl, headers, {
+ // Connect to the gateway WebSocket and wait for completion
+ const outcome = await followTaskRun(client, operationId, {
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);
+ if (outcome.kind !== 'completed') {
+ process.exitCode = AGENT_RUN_EXIT_CODES[outcome.kind];
+ return;
+ }
// Update heartbeat after each topic
try {
diff --git a/apps/cli/src/doctor/checks/endpoints.ts b/apps/cli/src/doctor/checks/endpoints.ts
index a670eb735b0..1bba4d5c052 100644
--- a/apps/cli/src/doctor/checks/endpoints.ts
+++ b/apps/cli/src/doctor/checks/endpoints.ts
@@ -113,7 +113,7 @@ const endpointResolution: DoctorCheck = {
return {
detail: `Server is ${shown.serverUrl} but agent streaming still points at the official agent gateway.`,
evidence,
- fix: 'Set AGENT_GATEWAY_URL to your own agent gateway, or run agent commands with --sse.',
+ fix: 'Set AGENT_GATEWAY_URL to your own agent gateway configured for this server.',
status: 'warn',
};
diff --git a/apps/cli/src/utils/agentStream.test.ts b/apps/cli/src/utils/agentStream.test.ts
index 88248a89e82..66ba98c3543 100644
--- a/apps/cli/src/utils/agentStream.test.ts
+++ b/apps/cli/src/utils/agentStream.test.ts
@@ -1,6 +1,42 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { replayAgentEvents, streamAgentEvents, streamAgentEventsViaWebSocket } from './agentStream';
+import type { AgentStreamEvent } from './agentStream';
+import { replayAgentEvents, streamAgentEvents as streamImpl } from './agentStream';
+import type { AgentHistoryPage, AgentStreamAuth } from './agentStreamTransport';
+
+type StreamOptions = Parameters<typeof streamImpl>[0];
+
+/** Server journal backing the stream; the socket only carries wake-ups. */
+let journal: Array<AgentStreamEvent & { id: string }>;
+
+const readHistory = async (cursor: string): Promise<AgentHistoryPage> => {
+ const after = Number(cursor.split('-')[0]);
+ const events = journal.filter((event) => Number(event.id.split('-')[0]) > after);
+ return { available: true, events, hasMore: false, nextCursor: events.at(-1)?.id ?? cursor };
+};
+
+const testAuth: AgentStreamAuth = {
+ serverUrl: 'https://server.test',
+ token: 'test-token',
+ tokenType: 'jwt',
+};
+
+const streamAgentEvents = (
+ options: Partial<StreamOptions> & Pick<StreamOptions, 'gatewayUrl' | 'operationId'>,
+) =>
+ streamImpl({
+ getAuth: async () => testAuth,
+ maxRetries: 0,
+ readHistory,
+ ...options,
+ });
+
+/** Append an event to the journal and notify over the gateway socket. */
+const emit = (event: Record<string, unknown>) => {
+ const id = `${journal.length + 1}-0`;
+ journal.push({ operationId: 'op-1', stepIndex: 0, timestamp: 0, ...event, id } as any);
+ capturedWs!.simulateMessage({ id, type: 'agent_event' });
+};
vi.mock('./logger', () => ({
log: {
@@ -13,200 +49,6 @@ vi.mock('./logger', () => ({
},
}));
-function createSSEStream(events: string[]): ReadableStream<Uint8Array> {
- const encoder = new TextEncoder();
- const payload = events.join('');
-
- return new ReadableStream({
- start(controller) {
- controller.enqueue(encoder.encode(payload));
- controller.close();
- },
- });
-}
-
-/** Create a stream that delivers content in separate chunks to simulate network splitting */
-function createChunkedSSEStream(chunks: string[]): ReadableStream<Uint8Array> {
- const encoder = new TextEncoder();
-
- return new ReadableStream({
- start(controller) {
- for (const chunk of chunks) {
- controller.enqueue(encoder.encode(chunk));
- }
- controller.close();
- },
- });
-}
-
-function sseMessage(type: string, data: Record<string, any>): string {
- return `event:${type}\ndata:${JSON.stringify(data)}\n\n`;
-}
-
-describe('streamAgentEvents', () => {
- let fetchSpy: ReturnType<typeof vi.spyOn>;
- let stdoutSpy: ReturnType<typeof vi.spyOn>;
- let consoleSpy: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- fetchSpy = vi.spyOn(globalThis, 'fetch');
- stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
- });
-
- afterEach(() => {
- fetchSpy.mockRestore();
- stdoutSpy.mockRestore();
- consoleSpy.mockRestore();
- });
-
- it('should render text stream chunks', async () => {
- const body = createSSEStream([
- sseMessage('data', {
- data: null,
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'agent_runtime_init',
- }),
- sseMessage('data', {
- data: null,
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'step_start',
- }),
- sseMessage('data', {
- data: { chunkType: 'text', content: 'Hello ' },
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'stream_chunk',
- }),
- sseMessage('data', {
- data: { chunkType: 'text', content: 'world!' },
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'stream_chunk',
- }),
- sseMessage('data', {
- data: { stepCount: 1, usage: { total_tokens: 100 } },
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'agent_runtime_end',
- }),
- ]);
-
- fetchSpy.mockResolvedValue(new Response(body, { status: 200 }));
-
- await streamAgentEvents('https://example.com/stream', {});
-
- expect(stdoutSpy).toHaveBeenCalledWith('Hello ');
- expect(stdoutSpy).toHaveBeenCalledWith('world!');
- });
-
- it('should output JSON when json option is true', async () => {
- const events = [
- {
- data: null,
- operationId: 'op1',
- stepIndex: 0,
- timestamp: 1000,
- type: 'agent_runtime_init',
- },
- {
- data: { stepCount: 1 },
- operationId: 'op1',
- stepIndex: 0,
- timestamp: 2000,
- type: 'agent_runtime_end',
- },
- ];
-
- const body = createSSEStream(events.map((e) => sseMessage('data', e)));
- fetchSpy.mockResolvedValue(new Response(body, { status: 200 }));
-
- await streamAgentEvents('https://example.com/stream', {}, { json: true });
-
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"agent_runtime_init"'));
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"agent_runtime_end"'));
- });
-
- it('should handle heartbeat events', async () => {
- const { log } = await import('./logger');
- const body = createSSEStream([
- `event:heartbeat\ndata:{}\n\n`,
- sseMessage('data', {
- data: null,
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'agent_runtime_end',
- }),
- ]);
-
- fetchSpy.mockResolvedValue(new Response(body, { status: 200 }));
-
- await streamAgentEvents('https://example.com/stream', {});
-
- expect(log.heartbeat).toHaveBeenCalled();
- });
-
- it('should preserve SSE frame state across read boundaries', async () => {
- const endEvent = JSON.stringify({
- data: { stepCount: 1 },
- operationId: 'op1',
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'agent_runtime_end',
- });
-
- // Split SSE message across two chunks: first chunk has event: + data:,
- // second chunk has the terminating blank line.
- const body = createChunkedSSEStream([`event:data\ndata:${endEvent}\n`, `\n`]);
-
- fetchSpy.mockResolvedValue(new Response(body, { status: 200 }));
-
- await streamAgentEvents('https://example.com/stream', {});
-
- // If frame state was lost the event would be silently dropped,
- // and the stream would end without printing the finish line.
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Agent finished'));
- });
-
- 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);
-
- fetchSpy.mockResolvedValue(new Response('Not Found', { status: 404 }));
-
- await expect(streamAgentEvents('https://example.com/stream', {})).rejects.toThrow(
- 'Agent stream failed: 404 Not Found',
- );
- expect(exitSpy).not.toHaveBeenCalled();
-
- exitSpy.mockRestore();
- });
-
- 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();
- });
-});
-
// ── WebSocket stream tests ──────────────────────────────
let capturedWs: MockWebSocket | undefined;
@@ -260,13 +102,14 @@ class MockWebSocket {
}
}
-describe('streamAgentEventsViaWebSocket', () => {
+describe('streamAgentEvents', () => {
let stdoutSpy: ReturnType<typeof vi.spyOn>;
let consoleSpy: ReturnType<typeof vi.spyOn>;
const originalWebSocket = globalThis.WebSocket;
beforeEach(() => {
capturedWs = undefined;
+ journal = [];
stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
(globalThis as any).WebSocket = MockWebSocket;
@@ -281,34 +124,39 @@ describe('streamAgentEventsViaWebSocket', () => {
/** Wait for microtasks + short delay so WS open/auth cycle completes */
const flush = () => new Promise((r) => setTimeout(r, 20));
- it('should connect, authenticate, and send resume', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const end = (data: Record<string, unknown> = {}) =>
+ emit({ data: { reason: 'done', ...data }, type: 'agent_runtime_end' });
+
+ it('should connect, authenticate with fresh credentials, and send resume', async () => {
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'test-token',
});
await flush();
const ws = capturedWs!;
- // Note: serverUrl is not set here, and JSON.stringify drops undefined keys,
- // so the parsed auth message will not contain a `serverUrl` field.
expect(ws.sent.map((s) => JSON.parse(s))).toEqual([
- { token: 'test-token', tokenType: 'jwt', type: 'auth' },
+ { serverUrl: 'https://server.test', token: 'test-token', tokenType: 'jwt', type: 'auth' },
{ lastEventId: '', type: 'resume' },
]);
- ws.simulateMessage({ id: '1', type: 'session_complete' });
+ end();
await promise;
});
it('should send tokenType=apiKey and serverUrl when the caller uses an API key', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
+ // `getAgentStreamAuthInfo` also returns HTTP headers; they must not reach the gateway.
+ getAuth: async () =>
+ ({
+ headers: { 'X-API-Key': 'lh_sk_abc' },
+ serverUrl: 'https://app.lobehub.com',
+ token: 'lh_sk_abc',
+ tokenType: 'apiKey',
+ }) as AgentStreamAuth,
operationId: 'op-1',
- serverUrl: 'https://app.lobehub.com',
- token: 'lh_sk_abc',
- tokenType: 'apiKey',
});
await flush();
@@ -323,85 +171,37 @@ describe('streamAgentEventsViaWebSocket', () => {
type: 'auth',
});
- ws.simulateMessage({ id: '1', type: 'session_complete' });
+ end();
await promise;
});
- it('should render agent_event messages using existing renderEvent', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ it('should render journal events woken by agent_event notifications', async () => {
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'test-token',
});
await flush();
- const ws = capturedWs!;
- ws.simulateMessage({
- event: { data: null, operationId: 'op-1', stepIndex: 0, timestamp: 1, type: 'step_start' },
- id: '1',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { chunkType: 'text', content: 'Hello WS!' },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 2,
- type: 'stream_chunk',
- },
- id: '2',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { stepCount: 1 },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 3,
- type: 'agent_runtime_end',
- },
- id: '3',
- type: 'agent_event',
- });
+ emit({ data: null, type: 'step_start' });
+ emit({ data: { chunkType: 'text', content: 'Hello WS!' }, type: 'stream_chunk' });
+ end({ stepCount: 1 });
await promise;
expect(stdoutSpy).toHaveBeenCalledWith('Hello WS!');
});
it('should output JSON when json option is set', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
json: true,
operationId: 'op-1',
- token: 'test-token',
});
await flush();
- const ws = capturedWs!;
- ws.simulateMessage({
- event: {
- data: null,
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_init',
- },
- id: '1',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { stepCount: 1 },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 2,
- type: 'agent_runtime_end',
- },
- id: '2',
- type: 'agent_event',
- });
+ emit({ data: null, type: 'agent_runtime_init' });
+ end({ stepCount: 1 });
await promise;
@@ -431,32 +231,29 @@ describe('streamAgentEventsViaWebSocket', () => {
};
await expect(
- streamAgentEventsViaWebSocket({
+ streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'bad-token',
}),
).rejects.toThrow('Gateway auth failed');
});
- it('should reject when websocket onerror fires', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ it('should reject once reconnects are exhausted after onerror', async () => {
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'test-token',
});
await flush();
capturedWs!.onerror?.({ message: 'socket exploded', type: 'error' });
- await expect(promise).rejects.toThrow('Agent gateway WebSocket failed: [object Object]');
+ await expect(promise).rejects.toThrow('Agent gateway WebSocket failed');
});
- it('should reject when websocket closes before completion', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ it('should reject once reconnects are exhausted after the socket closes', async () => {
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'test-token',
});
await flush();
@@ -468,172 +265,98 @@ describe('streamAgentEventsViaWebSocket', () => {
);
});
- it('should resolve on session_complete', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ it('should resolve from the journal terminal on session_complete', async () => {
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'test-token',
});
await flush();
+ journal.push({
+ data: { reason: 'done' },
+ id: '1-0',
+ operationId: 'op-1',
+ stepIndex: 0,
+ timestamp: 0,
+ type: 'agent_runtime_end',
+ });
capturedWs!.simulateMessage({ id: '1', summary: 'All done', type: 'session_complete' });
- await expect(promise).resolves.toBeUndefined();
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'completed' }));
});
it('should ignore heartbeat_ack messages', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'test-token',
});
await flush();
- const ws = capturedWs!;
- ws.simulateMessage({ type: 'heartbeat_ack' });
+ capturedWs!.simulateMessage({ type: 'heartbeat_ack' });
expect(stdoutSpy).not.toHaveBeenCalled();
- ws.simulateMessage({ id: '1', type: 'session_complete' });
+ end();
await promise;
});
it('should construct correct WebSocket URL from HTTPS gateway URL', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
gatewayUrl: 'https://agent-gateway.lobehub.com',
operationId: 'op-123',
- token: 'tok',
});
await flush();
expect(capturedWs!.url).toBe('wss://agent-gateway.lobehub.com/ws?operationId=op-123');
- capturedWs!.simulateMessage({ id: '1', type: 'session_complete' });
+ journal.push({
+ data: { reason: 'done' },
+ id: '1-0',
+ operationId: 'op-123',
+ stepIndex: 0,
+ timestamp: 0,
+ type: 'agent_runtime_end',
+ });
+ capturedWs!.simulateMessage({ type: 'session_complete' });
await promise;
});
it('should render a multi-step agent run with tool calls', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 'tok',
verbose: true,
});
await flush();
- const ws = capturedWs!;
const { log } = await import('./logger');
// Step 1: thinking + text + tool call
- ws.simulateMessage({
- event: {
- data: null,
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 1,
- type: 'agent_runtime_init',
- },
- id: '1',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: { data: null, operationId: 'op-1', stepIndex: 0, timestamp: 2, type: 'step_start' },
- id: '2',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { chunkType: 'reasoning', reasoning: 'Let me search...' },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 3,
- type: 'stream_chunk',
- },
- id: '3',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { chunkType: 'text', content: 'Searching for news.' },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 4,
- type: 'stream_chunk',
- },
- id: '4',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { toolCalling: { apiName: 'search', id: 'tc-1' } },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 5,
- type: 'tool_start',
- },
- id: '5',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: { data: null, operationId: 'op-1', stepIndex: 0, timestamp: 6, type: 'stream_end' },
- id: '6',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { stepIndex: 0 },
- operationId: 'op-1',
- stepIndex: 0,
- timestamp: 7,
- type: 'step_complete',
- },
- id: '7',
- type: 'agent_event',
- });
+ emit({ data: null, type: 'agent_runtime_init' });
+ emit({ data: null, type: 'step_start' });
+ emit({ data: { chunkType: 'reasoning', reasoning: 'Let me search...' }, type: 'stream_chunk' });
+ emit({ data: { chunkType: 'text', content: 'Searching for news.' }, type: 'stream_chunk' });
+ emit({ data: { toolCalling: { apiName: 'search', id: 'tc-1' } }, type: 'tool_start' });
+ emit({ data: null, type: 'stream_end' });
+ emit({ data: { stepIndex: 0 }, type: 'step_complete' });
// Step 2: tool result + final text
- ws.simulateMessage({
- event: { data: null, operationId: 'op-1', stepIndex: 1, timestamp: 8, type: 'step_start' },
- id: '8',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: {
- isSuccess: true,
- payload: { toolCalling: { id: 'tc-1' } },
- result: { content: 'Results...' },
- },
- operationId: 'op-1',
- stepIndex: 1,
- timestamp: 9,
- type: 'tool_end',
+ emit({ data: null, stepIndex: 1, type: 'step_start' });
+ emit({
+ data: {
+ isSuccess: true,
+ payload: { toolCalling: { id: 'tc-1' } },
+ result: { content: 'Results...' },
},
- id: '9',
- type: 'agent_event',
+ stepIndex: 1,
+ type: 'tool_end',
});
- ws.simulateMessage({
- event: {
- data: { chunkType: 'text', content: 'Here are the results.' },
- operationId: 'op-1',
- stepIndex: 1,
- timestamp: 10,
- type: 'stream_chunk',
- },
- id: '10',
- type: 'agent_event',
- });
- ws.simulateMessage({
- event: {
- data: { cost: { total: 0.05 }, stepCount: 2, usage: { total_tokens: 500 } },
- operationId: 'op-1',
- stepIndex: 1,
- timestamp: 11,
- type: 'agent_runtime_end',
- },
- id: '11',
- type: 'agent_event',
+ emit({
+ data: { chunkType: 'text', content: 'Here are the results.' },
+ stepIndex: 1,
+ type: 'stream_chunk',
});
+ end({ cost: { total: 0.05 }, stepCount: 2, usage: { total_tokens: 500 } });
await promise;
@@ -695,6 +418,7 @@ describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
beforeEach(() => {
capturedWs = undefined;
+ journal = [];
stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
fetchSpy = vi.spyOn(globalThis, 'fetch');
@@ -716,6 +440,10 @@ describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
timestamp: Date.now(),
type: 'agent_runtime_end',
});
+ const emitEnd = (reason: string) => {
+ const { operationId: _, ...event } = endEvent(reason);
+ emit(event);
+ };
describe.each([
['done', 'completed', 'Agent finished'],
@@ -723,26 +451,13 @@ describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
['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({
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
operationId: 'op-1',
- token: 't',
});
await flush();
- capturedWs!.simulateMessage({ event: endEvent(reason), id: '1', type: 'agent_event' });
+ emitEnd(reason);
await expect(promise).resolves.toEqual(expect.objectContaining({ kind, status: reason }));
expect(printed()).toContain(label);
@@ -751,17 +466,12 @@ describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
});
it('resolves an error event as a failed outcome instead of exiting the process', async () => {
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
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',
- });
+ emit({ data: { message: 'boom' }, type: 'error' });
await expect(promise).resolves.toEqual({ error: 'boom', kind: 'failed', status: 'error' });
});
@@ -795,82 +505,83 @@ describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
});
});
- 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 () => {
+ it('a quiet stream asks onStall, keeps waiting while active, and fails when the run ended without a journal terminal', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
- const promise = streamAgentEventsViaWebSocket({
+ const onStall = vi
+ .fn()
+ .mockResolvedValueOnce(undefined) // still running β†’ keep streaming
+ .mockResolvedValueOnce({ kind: 'completed', status: 'done' });
+
+ const promise = streamAgentEvents({
gatewayUrl: 'https://gw.test.com',
+ onStall,
operationId: 'op-1',
stallTimeoutMs: 1000,
- token: 't',
});
const settled = vi.fn();
promise.then(settled, settled);
- await vi.advanceTimersByTimeAsync(0);
+ const failure = expect(promise).rejects.toMatchObject({ name: 'AgentStreamHistoryError' });
- // 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 vi.advanceTimersByTimeAsync(1000);
+ expect(onStall).toHaveBeenCalledTimes(1);
+ expect(settled).not.toHaveBeenCalled();
- await expect(promise).rejects.toThrow('sent no progress for 1s');
+ await vi.advanceTimersByTimeAsync(1000);
+ // A terminal status now gets a bounded final catch-up before the failure.
+ await vi.advanceTimersByTimeAsync(1500);
+ await failure;
+ expect(onStall).toHaveBeenCalledTimes(2);
+ expect(printed()).not.toContain('Agent finished');
});
- it('a quiet stream asks onStall and keeps waiting while the run is still active', async () => {
+ it('gives the journal a bounded grace after a terminal status before calling the history incomplete', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
- const onStall = vi
- .fn()
- .mockResolvedValueOnce(undefined) // still running β†’ keep streaming
- .mockResolvedValueOnce({ kind: 'completed', status: 'done' });
+ const onStall = vi.fn().mockResolvedValue({ kind: 'completed', status: 'done' });
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
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(0);
- await vi.advanceTimersByTimeAsync(1000);
- await expect(promise).resolves.toEqual({ kind: 'completed', status: 'done' });
- expect(onStall).toHaveBeenCalledTimes(2);
- expect(printed()).toContain('Agent finished');
+ // `saveAgentState` persists the terminal state before publishing it, so the
+ // status probe wins the race and the journal event lands a beat later.
+ const { operationId: _ignored, ...end } = endEvent('done');
+ journal.push({
+ ...end,
+ id: `${journal.length + 1}-0`,
+ operationId: 'op-1',
+ } as any);
+ await vi.advanceTimersByTimeAsync(600);
+
+ await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'completed' }));
});
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({
+ const promise = streamAgentEvents({
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',
- });
+ emit({ data: {}, type: 'step_complete' });
}
expect(onStall).not.toHaveBeenCalled();
- capturedWs!.simulateMessage({ event: endEvent('done'), id: 'end', type: 'agent_event' });
+ emitEnd('done');
+ // The chunk that carried the terminal opened a coalescing window; the
+ // trailing read delivers it within that window.
+ await vi.advanceTimersByTimeAsync(600);
await expect(promise).resolves.toEqual(expect.objectContaining({ kind: 'completed' }));
});
@@ -890,192 +601,19 @@ describe('run outcome of the live stream (#19543 #19613 #19615)', () => {
return handle;
}) as any);
- const promise = streamAgentEventsViaWebSocket({
+ const promise = streamAgentEvents({
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' });
+ emitEnd('done');
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>;
@@ -1086,6 +624,7 @@ describe('--json prints exactly one array, even when no event arrived', () => {
beforeEach(() => {
capturedWs = undefined;
+ journal = [];
fetchSpy = vi.spyOn(globalThis, 'fetch');
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
(globalThis as any).WebSocket = MockWebSocket;
@@ -1097,30 +636,6 @@ describe('--json prints exactly one array, even when no event arrived', () => {
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) {
@@ -1138,27 +653,30 @@ describe('--json prints exactly one array, even when no event arrived', () => {
};
await expect(
- streamAgentEventsViaWebSocket({
+ streamAgentEvents({
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;
+ it('an expired journal before any event prints [] once', async () => {
+ await expect(
+ streamAgentEvents({
+ gatewayUrl: 'https://gw.test.com',
+ json: true,
+ operationId: 'op-1',
+ readHistory: async () => ({
+ available: false,
+ events: [],
+ hasMore: false,
+ nextCursor: '0',
+ }),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentStreamHistoryError' });
await flush();
expect(jsonOutputs()).toEqual([[]]);
});
diff --git a/apps/cli/src/utils/agentStream.ts b/apps/cli/src/utils/agentStream.ts
index 141544fa1ae..deed8e67acb 100644
--- a/apps/cli/src/utils/agentStream.ts
+++ b/apps/cli/src/utils/agentStream.ts
@@ -1,9 +1,10 @@
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 type { AgentStreamTransportOptions } from './agentStreamTransport';
+import { AgentStreamHistoryError, consumeAgentStream } from './agentStreamTransport';
import { log } from './logger';
export type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
@@ -13,38 +14,21 @@ interface StreamOptions {
verbose?: boolean;
}
-interface LiveStreamOptions extends StreamOptions {
+interface FollowStreamOptions extends StreamOptions, AgentStreamTransportOptions {
/**
- * 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.
+ * Called when the stream has carried no progress for `stallTimeoutMs`. A
+ * gateway can keep a connection alive with heartbeats while never
+ * delivering the terminal event, so silence alone must not be read as either
+ * "finished" or "failed". Return `undefined` while the run is still active
+ * (keep streaming). A terminal outcome gets a bounded final catch-up for the
+ * terminal journal event first, then the stream fails as incomplete; throwing
+ * does too.
*/
onStall?: () => Promise<AgentRunOutcome | undefined>;
/** Progress window before `onStall` is consulted. Defaults to 60s. */
stallTimeoutMs?: number;
}
-interface WebSocketStreamOptions extends LiveStreamOptions {
- gatewayUrl: string;
- operationId: string;
- /**
- * LobeHub server URL the gateway should call back to when verifying
- * an apiKey token (via `/api/v1/users/me`). Required when
- * `tokenType === 'apiKey'`; ignored for JWT.
- */
- serverUrl?: string;
- token: string;
- /**
- * How the gateway should verify `token`. `jwt` is the default for
- * backwards compatibility with existing callers.
- */
- 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
@@ -70,173 +54,6 @@ const outcomeFromErrorEvent = (event: AgentStreamEvent): AgentRunOutcome => ({
status: 'error',
});
-/**
- * Connect to the agent SSE stream and render events to the terminal.
- * 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: 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 ctx = createRenderContext();
-
- // Declared outside the read loop so partial SSE frames that span
- // chunk boundaries are not lost between reader.read() calls.
- 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 });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
-
- for (const line of lines) {
- if (line.startsWith('event:')) {
- eventType = line.slice(6).trim();
- continue;
- }
-
- if (line.startsWith('data:')) {
- eventData = line.slice(5).trim();
- }
-
- // Empty line = end of SSE message
- if (line === '' && eventData) {
- if (eventType === 'heartbeat') {
- log.heartbeat();
- eventType = '';
- eventData = '';
- continue;
- }
-
- armStallTimer();
- try {
- const event: AgentStreamEvent = JSON.parse(eventData);
-
- if (options.json) {
- jsonEvents.push(event);
- } else {
- renderEvent(event, ctx, options);
- }
-
- if (event.type === 'agent_runtime_end') {
- const outcome = outcomeFromEndEvent(event);
- if (options.json) {
- printJsonOnce();
- } else {
- renderEnd(event, outcome);
- }
- return outcome;
- }
-
- if (event.type === 'error') {
- printJsonOnce();
- const outcome = outcomeFromErrorEvent(event);
- log.error(`Agent error: ${outcome.error}`);
- return outcome;
- }
- } catch {
- // Not JSON, skip
- }
-
- eventType = '';
- eventData = '';
- }
- }
- }
-
- // Stream ended without agent_runtime_end
- 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. Returns the outcome carried by the recorded terminal
@@ -278,184 +95,120 @@ export function replayAgentEvents(
return undefined;
}
-const HEARTBEAT_INTERVAL = 30_000;
-
/**
- * Connect to the Agent Gateway via WebSocket and render events to the terminal.
- * 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.
+ * Consult `onStall` whenever `timeoutMs` passes without progress. Re-arms while
+ * the run is still active; a terminal status means the journal should hold the
+ * terminal event too, so `onFinalCatchUp` gets a bounded grace to read it before
+ * the history is declared incomplete. (The coordinator persists the terminal
+ * state *before* publishing it, so a status probe can win that race β€” and with
+ * it the simultaneous periodic catch-up.)
*/
-export async function streamAgentEventsViaWebSocket(
- options: WebSocketStreamOptions,
-): 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)}`,
- );
-
- log.debug(`Connecting to gateway: ${wsUrl} (auth: ${tokenType})`);
-
- 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 TERMINAL_HISTORY_GRACE_ATTEMPTS = 3;
+const TERMINAL_HISTORY_GRACE_DELAY_MS = 500;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const watchForStall = (
+ timeoutMs: number,
+ onStall: () => Promise<AgentRunOutcome | undefined>,
+ onIncomplete: (error: AgentStreamHistoryError) => void,
+ onFinalCatchUp?: () => Promise<boolean>,
+) => {
+ let stopped = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const arm = () => {
+ if (stopped) return;
+ clearTimeout(timer);
+ timer = setTimeout(async () => {
+ let message = 'Run status is terminal but the complete event history has no terminal event';
+ try {
+ if (!(await onStall())) return arm();
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
}
- };
-
- 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();
+ // A terminal status does not guarantee the terminal journal event already
+ // landed; read once more, then retry over a short bounded window.
+ if (onFinalCatchUp) {
+ const readTerminal = onFinalCatchUp;
+ for (let attempt = 0; attempt < TERMINAL_HISTORY_GRACE_ATTEMPTS; attempt++) {
+ if (attempt > 0) {
+ await sleep(TERMINAL_HISTORY_GRACE_DELAY_MS);
+ if (stopped) return;
}
- } catch (error) {
- fail(new Error(`${silence}; status check failed: ${(error as Error).message}`));
+ if (await readTerminal()) return;
+ if (stopped) return;
}
- }, 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');
- // Request all buffered events (covers events pushed before WS connected)
- ws.send(JSON.stringify({ lastEventId: '', type: 'resume' }));
- heartbeatTimer = setInterval(() => {
- if (ws.readyState === WebSocket.OPEN) {
- 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') {
- fail(new Error(`Gateway auth failed: ${msg.reason}`));
- return;
}
+ if (!stopped) onIncomplete(new AgentStreamHistoryError(message));
+ }, timeoutMs);
+ };
+ const stop = () => {
+ stopped = true;
+ clearTimeout(timer);
+ };
+ arm();
+ return { arm, stop };
+};
- if (msg.type === 'heartbeat_ack') return;
-
- if (msg.type === 'agent_event') {
- const agentEvent: AgentStreamEvent = msg.event;
- if (msg.id) lastEventId = msg.id;
-
- if (streamOpts.json) {
- jsonEvents.push(agentEvent);
- } else {
- renderEvent(agentEvent, ctx, streamOpts);
- }
-
- if (agentEvent.type === 'agent_runtime_end') {
- if (isSettled) return;
- const outcome = outcomeFromEndEvent(agentEvent);
- if (!streamOpts.json) renderEnd(agentEvent, outcome);
- printJsonOnce();
- settle(outcome);
- return;
- }
-
- if (agentEvent.type === 'error') {
- if (isSettled) return;
- const outcome = outcomeFromErrorEvent(agentEvent);
- printJsonOnce();
- log.error(`Agent error: ${outcome.error}`);
- settle(outcome);
- return;
- }
+/**
+ * Follow an operation's events (server journal, woken by the Gateway
+ * WebSocket) and render them to the terminal. Resolves with the outcome of the
+ * terminal event; rejects with `AgentStreamHistoryError` when the complete
+ * event history cannot be confirmed.
+ */
+export async function streamAgentEvents(
+ options: FollowStreamOptions,
+): Promise<AgentRunOutcome | undefined> {
+ const jsonEvents: AgentStreamEvent[] = [];
+ const ctx = createRenderContext();
+ let outcome: AgentRunOutcome | undefined;
+
+ const transport = consumeAgentStream(
+ {
+ ...options,
+ // A group member's events ride the supervisor's socket but never its
+ // journal, so they are rendered from the wire. They are never terminal:
+ // the supervisor continues after a member finishes.
+ onMirroredEvent: (event) => {
+ stall?.arm();
+ if (options.json) jsonEvents.push(event);
+ else renderEvent(event, ctx, options);
+ },
+ },
+ (event) => {
+ stall?.arm();
+ if (options.json) jsonEvents.push(event);
+ else renderEvent(event, ctx, options);
+ if (event.type === 'agent_runtime_end') {
+ outcome = outcomeFromEndEvent(event);
+ if (!options.json) renderEnd(event, outcome);
+ return true;
}
-
- if (msg.type === 'session_complete') {
- printJsonOnce();
- settle(undefined);
+ if (event.type === 'error') {
+ outcome = outcomeFromErrorEvent(event);
+ log.error(`Agent error: ${outcome.error}`);
+ return true;
}
- };
-
- ws.onerror = (err) => {
- fail(new Error(`Agent gateway WebSocket failed: ${String(err)}`));
- };
+ return false;
+ },
+ );
+ const stall =
+ options.onStall &&
+ watchForStall(
+ options.stallTimeoutMs ?? STALL_TIMEOUT,
+ options.onStall,
+ transport.abort,
+ transport.catchUp,
+ );
- ws.onclose = (event) => {
- // Surface the close code + reason β€” `String(event)` is just "[object CloseEvent]".
- const reason = event.reason ? `: ${event.reason}` : '';
- fail(
- new Error(`Agent gateway WebSocket closed before completion (code ${event.code}${reason})`),
- );
- };
- });
+ try {
+ await transport.done;
+ return outcome;
+ } finally {
+ stall?.stop();
+ transport.close();
+ if (options.json) console.log(JSON.stringify(jsonEvents, null, 2));
+ }
}
// ── Render helpers ──────────────────────────────────────
@@ -551,11 +304,6 @@ function renderEvent(event: AgentStreamEvent, ctx: RenderContext, options: Strea
}
}
-function renderOutcome(outcome: AgentRunOutcome): void {
- console.log();
- console.log(describeOutcome(outcome));
-}
-
function renderEnd(event: AgentStreamEvent, outcome: AgentRunOutcome): void {
console.log();
const data = { ...event.data?.finalState, ...event.data };
diff --git a/apps/cli/src/utils/agentStreamTransport.test.ts b/apps/cli/src/utils/agentStreamTransport.test.ts
new file mode 100644
index 00000000000..1eb9d8acb7d
--- /dev/null
+++ b/apps/cli/src/utils/agentStreamTransport.test.ts
@@ -0,0 +1,412 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { streamAgentEvents } from './agentStream';
+import type { AgentHistoryPage } from './agentStreamTransport';
+import { AgentGatewayUnavailableError, AgentJournalUnsupportedError, consumeAgentStream } from './agentStreamTransport';
+
+let sockets: TestSocket[];
+class TestSocket {
+ static OPEN = 1;
+ static CONNECTING = 0;
+ readyState = 0;
+ onopen: (() => void) | null = null;
+ onmessage: ((event: { data: string }) => void) | null = null;
+ onerror: (() => void) | null = null;
+ onclose: ((event: { code: number; reason: string }) => void) | null = null;
+ sent: unknown[] = [];
+ constructor(public url: string) {
+ sockets.push(this);
+ queueMicrotask(() => {
+ this.readyState = 1;
+ this.onopen?.();
+ });
+ }
+ send(data: string) {
+ const message = JSON.parse(data);
+ this.sent.push(message);
+ if (message.type === 'auth') queueMicrotask(() => this.message({ type: 'auth_success' }));
+ }
+ message(message: unknown) {
+ this.onmessage?.({ data: JSON.stringify(message) });
+ }
+ close() {
+ this.readyState = 3;
+ }
+ disconnect(code = 1011) {
+ this.readyState = 3;
+ this.onclose?.({ code, reason: 'disconnected' });
+ }
+}
+
+type JournalEvent = AgentStreamEvent & { id: string };
+const event = (id: number, type: AgentStreamEvent['type'], content?: string): JournalEvent => ({
+ data: type === 'stream_chunk' ? { chunkType: 'text', content } : { reason: 'done' },
+ id: `${id}-0`,
+ operationId: 'op-1',
+ stepIndex: 0,
+ timestamp: id,
+ type,
+});
+
+describe('recoverable WebSocket transport', () => {
+ let journal: JournalEvent[];
+ let readHistory: ReturnType<
+ typeof vi.fn<(cursor: string, signal: AbortSignal) => Promise<AgentHistoryPage>>
+ >;
+ let stdout: ReturnType<typeof vi.spyOn>;
+ let consoleLog: ReturnType<typeof vi.spyOn>;
+ const flush = () => vi.advanceTimersByTimeAsync(0);
+ const options = () => ({
+ gatewayUrl: 'https://gateway.test',
+ operationId: 'op-1',
+ getAuth: async () => ({
+ serverUrl: 'https://server.test',
+ token: 'test',
+ tokenType: 'jwt' as const,
+ }),
+ readHistory,
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ sockets = [];
+ journal = [event(1, 'agent_runtime_init')];
+ readHistory = vi.fn(async (cursor) => {
+ const all = journal.filter(
+ (item) => Number(item.id.split('-')[0]) > Number(cursor.split('-')[0]),
+ );
+ const events = all.slice(0, 2);
+ return {
+ available: true,
+ events,
+ hasMore: all.length > 2,
+ nextCursor: events.at(-1)?.id ?? cursor,
+ };
+ });
+ vi.stubGlobal('WebSocket', TestSocket);
+ stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ consoleLog = vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it('replays every page even with an empty Gateway buffer and prints one complete JSON array', async () => {
+ journal.push(
+ ...Array.from({ length: 1100 }, (_, i) => event(i + 2, 'stream_chunk', String(i))),
+ event(1102, 'agent_runtime_end'),
+ );
+ const done = streamAgentEvents({ ...options(), json: true });
+ await flush();
+ await expect(done).resolves.toMatchObject({ kind: 'completed' });
+ expect(JSON.parse(String(consoleLog.mock.calls[0][0]))).toHaveLength(1102);
+ expect(consoleLog).toHaveBeenCalledTimes(1);
+ expect(readHistory).toHaveBeenCalledWith('1100-0', expect.any(AbortSignal));
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('renders a group member event mirrored onto the supervisor socket, which the journal can never replay', async () => {
+ journal.push(event(2, 'stream_chunk', 'supervisor'));
+ const done = streamAgentEvents({ ...options(), json: true });
+ await flush();
+
+ // Mirrored member events live under the member's operation id, so they are
+ // absent from this operation's history and only exist on the socket.
+ const memberChunk = { ...event(3, 'stream_chunk', 'member'), operationId: 'op-member-2' };
+ sockets[0].message({ event: memberChunk, id: 'gateway-1', type: 'agent_event' });
+ await flush();
+ // A resume replays from the gateway cursor: the same frame must not render twice.
+ sockets[0].message({ event: memberChunk, id: 'gateway-1', type: 'agent_event' });
+ await flush();
+ // A member finishing is not the supervisor finishing.
+ const memberEnd = { ...event(4, 'member_runtime_end'), operationId: 'op-member-2' };
+ sockets[0].message({ event: memberEnd, id: 'gateway-2', type: 'agent_event' });
+ await flush();
+
+ journal.push(event(5, 'agent_runtime_end'));
+ sockets[0].message({ type: 'session_complete' });
+ await flush();
+ await expect(done).resolves.toMatchObject({ kind: 'completed' });
+
+ const printed = JSON.parse(String(consoleLog.mock.calls[0][0])) as AgentStreamEvent[];
+ const mirrored = printed.filter((item) => item.operationId === 'op-member-2');
+ expect(mirrored.map((item) => item.type)).toEqual(['stream_chunk', 'member_runtime_end']);
+ expect(printed.at(-1)?.type).toBe('agent_runtime_end');
+ });
+
+ it('holds a mirrored member frame behind an in-flight journal catch-up so the transcript stays ordered', async () => {
+ let release: (page: AgentHistoryPage) => void = () => {};
+ const pending = new Promise<AgentHistoryPage>((resolve) => {
+ release = resolve;
+ });
+ readHistory = vi.fn(() => pending);
+
+ const printed: AgentStreamEvent[] = [];
+ const stream = consumeAgentStream(
+ { ...options(), onMirroredEvent: (event) => printed.push(event) },
+ (event) => {
+ printed.push(event);
+ return false;
+ },
+ );
+ await flush();
+
+ // The frame lands while the first catch-up read is still in flight.
+ const memberChunk = { ...event(3, 'stream_chunk', 'member'), operationId: 'op-member-2' };
+ sockets[0].message({ event: memberChunk, id: 'gateway-1', type: 'agent_event' });
+ await flush();
+ expect(printed).toHaveLength(0);
+
+ release({
+ available: true,
+ events: [event(2, 'stream_chunk', 'supervisor')],
+ hasMore: false,
+ nextCursor: '2-0',
+ });
+ await flush();
+
+ expect(printed.map((item) => (item.data as { content?: string }).content)).toEqual([
+ 'supervisor',
+ 'member',
+ ]);
+ stream.close();
+ });
+
+ it('drains mirrored member frames queued behind a terminal catch-up instead of dropping them', async () => {
+ let release: (page: AgentHistoryPage) => void = () => {};
+ const pending = new Promise<AgentHistoryPage>((resolve) => {
+ release = resolve;
+ });
+ readHistory = vi.fn(() => pending);
+
+ const printed: AgentStreamEvent[] = [];
+ const stream = consumeAgentStream(
+ { ...options(), onMirroredEvent: (event) => printed.push(event) },
+ (event) => {
+ printed.push(event);
+ return event.type === 'agent_runtime_end';
+ },
+ );
+ await flush();
+
+ // The frame lands while the read that turns out terminal is still in flight,
+ // so it is queued behind that read rather than delivered immediately.
+ const memberChunk = { ...event(3, 'stream_chunk', 'member'), operationId: 'op-member-2' };
+ sockets[0].message({ event: memberChunk, id: 'gateway-1', type: 'agent_event' });
+ await flush();
+ expect(printed).toHaveLength(0);
+
+ release({
+ available: true,
+ events: [event(2, 'stream_chunk', 'supervisor'), event(4, 'agent_runtime_end')],
+ hasMore: false,
+ nextCursor: '4-0',
+ });
+ await flush();
+
+ // Success must not be reported with member output missing from the transcript.
+ await expect(stream.done).resolves.toBeUndefined();
+ expect(printed.map((item) => item.type)).toEqual([
+ 'stream_chunk',
+ 'agent_runtime_end',
+ 'stream_chunk',
+ ]);
+ expect((printed.at(-1)?.data as { content?: string }).content).toBe('member');
+ });
+
+ it('reconnects with backoff and recovers missed output exactly once', async () => {
+ journal.push(event(2, 'stream_chunk', 'before'));
+ const done = streamAgentEvents(options());
+ await flush();
+ sockets[0].disconnect();
+ journal.push(event(3, 'stream_chunk', 'after'));
+ await vi.advanceTimersByTimeAsync(999);
+ expect(sockets).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(sockets).toHaveLength(2);
+ sockets[1].message({ event: journal[1], id: 'gateway-duplicate', type: 'agent_event' });
+ await flush();
+ journal.push(event(4, 'agent_runtime_end'));
+ sockets[1].message({ type: 'session_complete' });
+ await flush();
+ await done;
+ expect(stdout.mock.calls.filter(([text]) => text === 'before')).toHaveLength(1);
+ expect(stdout.mock.calls.filter(([text]) => text === 'after')).toHaveLength(1);
+ expect(readHistory).toHaveBeenCalledWith('2-0', expect.any(AbortSignal));
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('coalesces a burst of chunk notifications into a bounded number of history reads', async () => {
+ const delivered: string[] = [];
+ const readAll = vi.fn(async (cursor: string) => {
+ const events = journal.filter(
+ (item) => Number(item.id.split('-')[0]) > Number(cursor.split('-')[0]),
+ );
+ return {
+ available: true,
+ events,
+ hasMore: false,
+ nextCursor: events.at(-1)?.id ?? cursor,
+ } as AgentHistoryPage;
+ });
+ const stream = consumeAgentStream({ ...options(), readHistory: readAll }, (streamEvent) => {
+ if (streamEvent.type === 'stream_chunk')
+ delivered.push(String(streamEvent.data?.content ?? ''));
+ return false;
+ });
+ await flush();
+ readAll.mockClear();
+
+ // The server buffers chunks in ~300ms windows, so a long reply arrives as a
+ // steady stream of `agent_event` frames rather than a single one.
+ for (let index = 0; index < 12; index++) {
+ journal.push(event(index + 2, 'stream_chunk', String(index)));
+ sockets[0].message({ id: `${index}-gateway`, type: 'agent_event' });
+ await vi.advanceTimersByTimeAsync(20);
+ }
+ await vi.advanceTimersByTimeAsync(600);
+
+ expect(delivered).toEqual(Array.from({ length: 12 }, (_, index) => String(index)));
+ expect(readAll.mock.calls.length).toBeLessThanOrEqual(3);
+ stream.close();
+ });
+
+ it('recovers a lost terminal notification from the journal without treating session_complete as success', async () => {
+ const done = streamAgentEvents({ ...options(), json: true });
+ const settled = vi.fn();
+ done.then(settled, settled);
+ await flush();
+ sockets[0].message({ type: 'session_complete' });
+ await flush();
+ expect(settled).not.toHaveBeenCalled();
+ journal.push(event(2, 'agent_runtime_end'));
+ await vi.advanceTimersByTimeAsync(5000);
+ await done;
+ expect(consoleLog).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries a transient history read without losing cursor or printing partial JSON', async () => {
+ const done = streamAgentEvents({ ...options(), json: true });
+ await flush();
+ readHistory.mockRejectedValueOnce(new Error('temporary outage'));
+ sockets[0].message({ type: 'agent_event' });
+ await flush();
+ expect(consoleLog).not.toHaveBeenCalled();
+ journal.push(event(2, 'agent_runtime_end'));
+ await vi.advanceTimersByTimeAsync(5000);
+ await done;
+ expect(readHistory).toHaveBeenLastCalledWith('1-0', expect.any(AbortSignal));
+ expect(consoleLog).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects an expired/truncated journal rather than claiming completion', async () => {
+ readHistory.mockResolvedValue({
+ available: false,
+ events: [],
+ hasMore: false,
+ nextCursor: '0',
+ });
+ const done = streamAgentEvents({ ...options(), json: true });
+ const failure = expect(done).rejects.toMatchObject({ name: 'AgentStreamHistoryError' });
+ await flush();
+ await failure;
+ expect(consoleLog).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('rejects a server without the journal procedure without retrying it', async () => {
+ readHistory.mockRejectedValue(
+ new AgentJournalUnsupportedError('This server has no agent event journal'),
+ );
+ const done = streamAgentEvents({ ...options(), json: true });
+ const failure = expect(done).rejects.toMatchObject({ name: 'AgentJournalUnsupportedError' });
+ await flush();
+ await failure;
+ expect(readHistory).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('rejects authorization failures immediately, with no reconnect, as a gateway failure', async () => {
+ const consumer = consumeAgentStream(options(), () => false);
+ // The Gateway rejecting a credential the server API accepts is a Gateway-only
+ // failure: the journal and the status endpoint may still be healthy, so the
+ // caller must keep the option of polling instead of reporting `unknown`.
+ const settled = consumer.done.catch((error: unknown) => error);
+ sockets[0].message({ reason: 'foreign operation', type: 'auth_failed' });
+ await flush();
+ const error = await settled;
+ expect(error).toBeInstanceOf(AgentGatewayUnavailableError);
+ expect((error as Error).message).toContain('Gateway auth failed');
+ expect(sockets).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('detects a half-open socket via missed heartbeat acknowledgements', async () => {
+ const consumer = consumeAgentStream(options(), () => false);
+ await flush();
+ await vi.advanceTimersByTimeAsync(61_000);
+ expect(sockets).toHaveLength(2);
+ consumer.close();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('refreshes gateway credentials for each reconnect', async () => {
+ const getAuth = vi
+ .fn()
+ .mockResolvedValueOnce({ serverUrl: 'https://server.test', token: 'first', tokenType: 'jwt' })
+ .mockResolvedValueOnce({
+ serverUrl: 'https://server.test',
+ token: 'refreshed',
+ tokenType: 'jwt',
+ });
+ const done = streamAgentEvents({ ...options(), getAuth });
+ await flush();
+ sockets[0].disconnect();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(sockets[1].sent[0]).toMatchObject({ token: 'refreshed', type: 'auth' });
+ journal.push(event(2, 'agent_runtime_end'));
+ sockets[1].message({ type: 'agent_event' });
+ await flush();
+ await done;
+ expect(getAuth).toHaveBeenCalledTimes(2);
+ });
+
+ it('bounds a stalled history request, aborts it, and recovers on a later tick', async () => {
+ let abortedSignal: AbortSignal | undefined;
+ readHistory.mockImplementationOnce((_cursor, signal) => {
+ abortedSignal = signal;
+ return new Promise(() => {});
+ });
+ const done = streamAgentEvents({ ...options(), json: true });
+ await flush();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(abortedSignal?.aborted).toBe(true);
+ expect(consoleLog).not.toHaveBeenCalled();
+ journal.push(event(2, 'agent_runtime_end'));
+ await vi.advanceTimersByTimeAsync(5000);
+ await done;
+ expect(consoleLog).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('stops reconnecting after the retry budget is exhausted', async () => {
+ vi.stubGlobal(
+ 'WebSocket',
+ class {
+ constructor() {
+ throw new Error('Gateway unavailable');
+ }
+ },
+ );
+ const consumer = consumeAgentStream({ ...options(), maxRetries: 2 }, () => false);
+ // Reconnect exhaustion is a connectivity outage, not a lost history: the
+ // caller must be able to fall back to polling the run status.
+ const settled = consumer.done.catch((error: unknown) => error);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(await settled).toBeInstanceOf(AgentGatewayUnavailableError);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/apps/cli/src/utils/agentStreamTransport.ts b/apps/cli/src/utils/agentStreamTransport.ts
new file mode 100644
index 00000000000..85abd3ea289
--- /dev/null
+++ b/apps/cli/src/utils/agentStreamTransport.ts
@@ -0,0 +1,574 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import urlJoin from 'url-join';
+
+import { log } from './logger';
+
+export interface AgentHistoryPage {
+ available: boolean;
+ events: Array<AgentStreamEvent & { id?: string }>;
+ hasMore: boolean;
+ nextCursor: string;
+}
+
+export interface AgentStreamAuth {
+ /**
+ * LobeHub server URL the gateway calls back to when verifying an apiKey
+ * token (via `/api/v1/users/me`). Ignored for JWT.
+ */
+ serverUrl: string;
+ token: string;
+ /** How the gateway should verify `token`. */
+ tokenType: 'jwt' | 'apiKey';
+}
+
+export interface AgentStreamTransportOptions {
+ gatewayUrl: string;
+ /** Called for every (re)connect so a long run picks up refreshed credentials. */
+ getAuth: () => Promise<AgentStreamAuth>;
+ maxRetries?: number;
+ /**
+ * Stream events the Gateway delivers for another operation on this socket β€” a
+ * group member's events mirrored onto the supervisor's channel.
+ *
+ * Server-side they are appended to the journal under the *member's* operation,
+ * so `readHistory(this.operationId)` can never replay them: this wire is their
+ * only source for a CLI run of a group/supervisor agent. They are therefore
+ * delivered here instead of being reduced to a wake-up, and never as terminal
+ * events β€” a member finishing must not end the supervisor's stream.
+ */
+ onMirroredEvent?: (event: AgentStreamEvent) => void;
+ operationId: string;
+ readHistory: (cursor: string, signal: AbortSignal) => Promise<AgentHistoryPage>;
+}
+
+/** A missing/truncated history is not a successful recovery or a retryable network outage. */
+export class AgentStreamHistoryError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'AgentStreamHistoryError';
+ }
+}
+
+/**
+ * The server has no event journal endpoint: the independently released CLI is
+ * newer than the server it talks to. This is a compatibility gap, not a lost
+ * history, so it must reach the caller untouched β€” the caller degrades to
+ * status polling instead of reporting an unconfirmable outcome.
+ */
+export class AgentJournalUnsupportedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'AgentJournalUnsupportedError';
+ }
+}
+
+/**
+ * The Gateway is unusable for this run β€” it stayed unreachable through the whole
+ * reconnect budget, or it rejected the CLI's credentials. This is a connectivity
+ * outage, not a lost history: the journal may still be intact and the run may
+ * still be executing, so it must reach the caller untouched β€” the caller
+ * degrades to status polling instead of reporting an unconfirmable run.
+ */
+export class AgentGatewayUnavailableError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'AgentGatewayUnavailableError';
+ }
+}
+
+const DEFAULT_MAX_RETRIES = 6;
+const CONNECT_TIMEOUT_MS = 10_000;
+const HEARTBEAT_INTERVAL_MS = 30_000;
+const HISTORY_POLL_INTERVAL_MS = 5000;
+const HISTORY_REQUEST_TIMEOUT_MS = 10_000;
+/**
+ * Chunk notifications are buffered server-side every ~300ms, so one CLI run can
+ * publish roughly three `agent_event` frames per second. Each wake costs an
+ * authenticated round trip (visibility query + Redis XRANGE), so chunk wakes are
+ * coalesced into at most one read per window. Terminal-ish wakes bypass it.
+ */
+const WAKE_COALESCE_WINDOW_MS = 500;
+/** Gateway frame ids remembered so a resume replay cannot re-render a member event. */
+const MIRRORED_ID_MEMORY = 200;
+const FATAL_TRPC_CODES = new Set(['UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND']);
+const REDIS_ID = /^\d+-\d+$/;
+
+const toError = (error: unknown) => (error instanceof Error ? error : new Error(String(error)));
+
+const retryDelay = (attempt: number) => Math.min(1000 * 2 ** (attempt - 1), 15_000);
+
+/** Compare Redis stream ids numerically β€” lexical order breaks once the digit count changes. */
+const isAfter = (id: string, cursor: string) => {
+ const [time, sequence] = id.split('-').map(BigInt);
+ const [lastTime, lastSequence = 0n] = cursor.split('-').map(BigInt);
+ return time > lastTime || (time === lastTime && sequence > lastSequence);
+};
+
+/**
+ * Reads the authoritative server journal forward from an exclusive cursor.
+ * Concurrent wake-ups coalesce into one more pass; transient failures back off
+ * until the next wake-up, fatal ones throw `AgentStreamHistoryError`.
+ */
+class AgentEventJournal {
+ private abort?: AbortController;
+ private cursor = '0';
+ private failures = 0;
+ private nextAttemptAt = 0;
+ private pending = false;
+ private reading = false;
+ private stopped = false;
+
+ constructor(
+ private readonly options: AgentStreamTransportOptions & { maxRetries: number },
+ /** Returns `true` once the event is terminal, which ends the stream. */
+ private readonly onEvent: (event: AgentStreamEvent) => boolean,
+ ) {}
+
+ close() {
+ this.stopped = true;
+ this.abort?.abort();
+ }
+
+ /** Resolves `true` once a terminal event was delivered. */
+ async catchUp(): Promise<boolean> {
+ if (this.stopped || Date.now() < this.nextAttemptAt) return false;
+ if (this.reading) {
+ this.pending = true;
+ return false;
+ }
+ this.reading = true;
+ try {
+ do {
+ this.pending = false;
+ if (await this.readToEnd()) return true;
+ } while (this.pending && !this.stopped);
+ this.failures = 0;
+ this.nextAttemptAt = 0;
+ return false;
+ } catch (error) {
+ if (this.stopped) return false;
+ const failure = toError(error);
+ log.debug(`Agent history recovery failed: ${failure.message}`);
+ // A server without the journal procedure cannot be retried into having it.
+ if (failure instanceof AgentJournalUnsupportedError) throw failure;
+ // tRPC auth/not-found responses must not be retried or masked by completion.
+ const code = (error as { data?: { code?: string } })?.data?.code;
+ if (
+ failure instanceof AgentStreamHistoryError ||
+ FATAL_TRPC_CODES.has(code ?? '') ||
+ ++this.failures > this.options.maxRetries
+ ) {
+ throw new AgentStreamHistoryError(`Complete history recovery failed: ${failure.message}`);
+ }
+ // The periodic poll retries transient failures even if the Gateway never
+ // sends another notification (including a lost terminal).
+ this.nextAttemptAt = Date.now() + retryDelay(this.failures);
+ return false;
+ } finally {
+ this.reading = false;
+ }
+ }
+
+ private async readToEnd(): Promise<boolean> {
+ let hasMore = true;
+ while (hasMore && !this.stopped) {
+ const page = await this.readPage();
+ if (this.stopped) return false;
+ if (!page.available)
+ throw new AgentStreamHistoryError(
+ 'Agent event history expired, was trimmed, or is unavailable; complete recovery cannot be guaranteed',
+ );
+ for (const event of page.events) {
+ if (!event.id || !REDIS_ID.test(event.id) || event.operationId !== this.options.operationId)
+ throw new AgentStreamHistoryError('Invalid agent event history');
+ // A retried page can overlap the previous one.
+ if (!isAfter(event.id, this.cursor)) continue;
+ this.cursor = event.id;
+ if (this.onEvent(event)) return true;
+ }
+ if (page.nextCursor !== this.cursor || (page.hasMore && page.events.length === 0))
+ throw new AgentStreamHistoryError('Agent history cursor did not advance consistently');
+ hasMore = page.hasMore;
+ }
+ return false;
+ }
+
+ private async readPage(): Promise<AgentHistoryPage> {
+ const abort = new AbortController();
+ this.abort = abort;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ this.options.readHistory(this.cursor, abort.signal),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ abort.abort();
+ reject(new Error('Agent history request timed out'));
+ }, HISTORY_REQUEST_TIMEOUT_MS);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ this.abort = undefined;
+ }
+ }
+}
+
+/**
+ * Gateway WebSocket used purely as a wake-up signal: every notification asks
+ * the journal to catch up. Owns auth, heartbeat and bounded reconnects.
+ */
+class GatewayWakeChannel {
+ private gatewayCursor = '';
+ private heartbeat?: ReturnType<typeof setInterval>;
+ private heartbeatPending = false;
+ private connectTimer?: ReturnType<typeof setTimeout>;
+ private mirroredIds = new Set<string>();
+ private reconnectTimer?: ReturnType<typeof setTimeout>;
+ private retries = 0;
+ private stopped = false;
+ private ws?: WebSocket;
+
+ constructor(
+ private readonly options: AgentStreamTransportOptions & { maxRetries: number },
+ /** `immediate` skips the coalescing window (terminal / reconnect wakes). */
+ private readonly onWake: (immediate?: boolean) => void,
+ private readonly onFatal: (error: Error) => void,
+ ) {}
+
+ /** Real progress proves the run is reachable, so the reconnect budget starts over. */
+ resetRetries() {
+ this.retries = 0;
+ }
+
+ connect() {
+ if (this.stopped) return;
+ const url = urlJoin(
+ this.options.gatewayUrl.replace(/^http/, 'ws'),
+ `/ws?operationId=${encodeURIComponent(this.options.operationId)}`,
+ );
+ let socket: WebSocket;
+ try {
+ socket = new WebSocket(url);
+ } catch (error) {
+ this.reconnect(toError(error));
+ return;
+ }
+ this.ws = socket;
+ this.connectTimer = setTimeout(
+ () => this.reconnect(new Error('Agent gateway connection/authentication timed out')),
+ CONNECT_TIMEOUT_MS,
+ );
+ socket.onopen = () => void this.authenticate(socket);
+ socket.onmessage = ({ data }) => {
+ if (this.stopped || socket !== this.ws) return;
+ try {
+ this.handleMessage(socket, JSON.parse(String(data)));
+ } catch (error) {
+ this.onFatal(new Error(`Invalid agent gateway message: ${toError(error).message}`));
+ }
+ };
+ socket.onerror = () => this.reconnect(new Error('Agent gateway WebSocket failed'));
+ socket.onclose = (event) => {
+ const error = new Error(
+ `Agent gateway WebSocket closed before completion (code ${event.code}${event.reason ? `: ${event.reason}` : ''})`,
+ );
+ // 1008 is a policy violation (e.g. a foreign operation): retrying cannot help.
+ if (event.code === 1008) this.onFatal(error);
+ else this.reconnect(error);
+ };
+ }
+
+ close() {
+ this.stopped = true;
+ clearTimeout(this.reconnectTimer);
+ this.closeSocket();
+ }
+
+ private async authenticate(socket: WebSocket) {
+ try {
+ const { serverUrl, token, tokenType } = await this.options.getAuth();
+ if (this.stopped || socket !== this.ws) return;
+ socket.send(JSON.stringify({ serverUrl, token, tokenType, type: 'auth' }));
+ } catch (error) {
+ // A credential that cannot be resolved right now is a Gateway problem,
+ // not an unconfirmable history: the stored access token may still work
+ // for the journal and the status endpoint, so the caller keeps its
+ // polling fallback instead of reporting an `unknown` outcome.
+ this.onFatal(
+ new AgentGatewayUnavailableError(
+ `Agent gateway credentials unavailable: ${toError(error).message}`,
+ ),
+ );
+ }
+ }
+
+ private handleMessage(
+ socket: WebSocket,
+ message: { event?: AgentStreamEvent; id?: string; reason?: string; type: string },
+ ) {
+ switch (message.type) {
+ case 'auth_failed': {
+ // The server API accepted this credential but the Gateway did not β€” e.g.
+ // a self-hosted server paired with the wrong Gateway. Retrying cannot
+ // help, yet the journal and the status endpoint are still reachable, so
+ // this is a Gateway failure rather than an unconfirmable history: the
+ // caller must be able to fall back to polling instead of reporting an
+ // `unknown` run. This usually lands before the first journal read, so
+ // misclassifying it fails a healthy run with exit code 3 and no output.
+ this.onFatal(new AgentGatewayUnavailableError(`Gateway auth failed: ${message.reason}`));
+ return;
+ }
+ case 'auth_success': {
+ clearTimeout(this.connectTimer);
+ socket.send(JSON.stringify({ lastEventId: this.gatewayCursor, type: 'resume' }));
+ this.startHeartbeat(socket);
+ this.onWake(true);
+ return;
+ }
+ case 'heartbeat_ack': {
+ this.heartbeatPending = false;
+ this.retries = 0;
+ return;
+ }
+ case 'agent_event': {
+ if (message.id) this.gatewayCursor = message.id;
+ this.deliverMirrored(message);
+ this.onWake();
+ return;
+ }
+ // Not a success signal: only a terminal event in the journal ends the run.
+ // The terminal is imminent, so this wake skips the coalescing window.
+ case 'session_complete': {
+ this.onWake(true);
+ return;
+ }
+ }
+ }
+
+ /**
+ * A group member's events are delivered on the supervisor's socket, but their
+ * journal entries stay under the member's own operation id β€” so no read of the
+ * supervisor's history can replay them. This wire is their only source, hence
+ * they are handed to the consumer instead of only waking the journal.
+ *
+ * Delivered non-terminal by contract: the server renames a mirrored member
+ * terminal to `member_runtime_end` precisely so the supervisor keeps running.
+ */
+ private deliverMirrored(message: { event?: AgentStreamEvent; id?: string }) {
+ const mirrored = message.event;
+ const deliver = this.options.onMirroredEvent;
+ if (!deliver || !mirrored?.operationId) return;
+ // Legacy gateways omit `operationId`; those events are this op's, and the
+ // journal already covers them.
+ if (mirrored.operationId === this.options.operationId) return;
+ // A reconnect resumes from `gatewayCursor`, so the same mirrored frame can
+ // legitimately arrive twice.
+ if (message.id) {
+ if (this.mirroredIds.has(message.id)) return;
+ if (this.mirroredIds.size >= MIRRORED_ID_MEMORY)
+ this.mirroredIds.delete(this.mirroredIds.values().next().value!);
+ this.mirroredIds.add(message.id);
+ }
+ deliver(mirrored);
+ }
+
+ private startHeartbeat(socket: WebSocket) {
+ clearInterval(this.heartbeat);
+ this.heartbeatPending = false;
+ this.heartbeat = setInterval(() => {
+ if (this.heartbeatPending) {
+ this.reconnect(new Error('Agent gateway heartbeat timed out'));
+ return;
+ }
+ this.heartbeatPending = true;
+ socket.send(JSON.stringify({ type: 'heartbeat' }));
+ }, HEARTBEAT_INTERVAL_MS);
+ this.heartbeat.unref?.();
+ }
+
+ private reconnect(error: Error) {
+ if (this.stopped || this.reconnectTimer) return;
+ this.closeSocket();
+ // Recover the terminal from the server even when the Gateway is down.
+ this.onWake(true);
+ if (++this.retries > this.options.maxRetries) {
+ this.onFatal(
+ new AgentGatewayUnavailableError(
+ `Reconnect attempts exhausted; complete history not confirmed: ${error.message}`,
+ ),
+ );
+ return;
+ }
+ const delay = retryDelay(this.retries);
+ log.debug(
+ `Agent WebSocket reconnect ${this.retries}/${this.options.maxRetries} in ${delay}ms: ${error.message}`,
+ );
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = undefined;
+ this.connect();
+ }, delay);
+ }
+
+ private closeSocket() {
+ clearTimeout(this.connectTimer);
+ clearInterval(this.heartbeat);
+ const ws = this.ws;
+ if (!ws) return;
+ ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) ws.close();
+ this.ws = undefined;
+ }
+}
+
+/**
+ * WS is the wake-up channel; the authenticated server journal is authoritative.
+ * This avoids mixing two unrelated cursor spaces (Gateway ids vs Redis ids),
+ * live/replay races, and dependence on the Gateway's in-memory buffer.
+ *
+ * `done` resolves after the terminal event and rejects with
+ * `AgentStreamHistoryError` when the output may be incomplete, with
+ * `AgentGatewayUnavailableError` when the Gateway never came back (the run may
+ * still be healthy, so the caller can fall back to polling), or with
+ * `AgentJournalUnsupportedError` when the server has no journal to read at all.
+ * `abort` lets the consumer end the stream as incomplete (e.g. a stall check).
+ */
+export const consumeAgentStream = (
+ options: AgentStreamTransportOptions,
+ onEvent: (event: AgentStreamEvent) => boolean,
+): {
+ abort: (error: Error) => void;
+ /** Reads the journal now; resolves `true` once a terminal event was delivered. */
+ catchUp: () => Promise<boolean>;
+ close: () => void;
+ done: Promise<void>;
+} => {
+ const resolved = { ...options, maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES };
+ let stopped = false;
+ let resolveDone: () => void;
+ let rejectDone: (error: Error) => void;
+ const done = new Promise<void>((resolve, reject) => {
+ resolveDone = resolve;
+ rejectDone = reject;
+ });
+
+ const journal = new AgentEventJournal(resolved, (event) => {
+ gateway.resetRetries();
+ return onEvent(event);
+ });
+ // A catch-up pass is started without awaiting it, so a mirrored member frame
+ // arriving mid-read would print ahead of supervisor history the server had
+ // already published β€” an out-of-order transcript, most likely on resume, when
+ // buffered member frames land while the first read is still pending. Hold
+ // mirrored deliveries behind every in-flight pass, keeping their own order.
+ let catchUpDepth = 0;
+ const queuedMirrored: AgentStreamEvent[] = [];
+ const emitMirrored = (event: AgentStreamEvent) => {
+ try {
+ resolved.onMirroredEvent?.(event);
+ } catch (error) {
+ fail(toError(error));
+ }
+ };
+ const deliverMirrored = (event: AgentStreamEvent) => {
+ if (stopped) return;
+ // Queued rather than chained on the pass promise: a terminal pass closes the
+ // transport from inside that same promise, so a chained continuation would
+ // observe `stopped` and drop member output.
+ if (catchUpDepth > 0) {
+ queuedMirrored.push(event);
+ return;
+ }
+ emitMirrored(event);
+ };
+ const flushMirrored = () => {
+ while (queuedMirrored.length > 0 && !stopped) emitMirrored(queuedMirrored.shift()!);
+ };
+
+ const runCatchUp = (): Promise<boolean> => {
+ const pass = (async () => {
+ catchUpDepth += 1;
+ try {
+ const terminal = await journal.catchUp();
+ if (terminal) {
+ // Mirrored frames queued behind this read belong to the transcript the
+ // run is about to report as complete: drain them before `finish()`
+ // flips `stopped`, or a fast group run silently loses member output.
+ flushMirrored();
+ finish();
+ }
+ return terminal;
+ } catch (error) {
+ fail(error as Error);
+ return false;
+ } finally {
+ catchUpDepth -= 1;
+ // Only the last pass may drain: a pass that returns immediately because
+ // the journal is already reading must not release frames queued behind
+ // the read that is actually in flight.
+ if (catchUpDepth === 0) flushMirrored();
+ }
+ })();
+ return pass;
+ };
+ // Chunk wakes are coalesced: the first one reads immediately and opens a
+ // window, further chunks inside it collapse into a single trailing read.
+ // Terminal and reconnect wakes read immediately and reset the window.
+ let wakePending = false;
+ let wakeWindow: ReturnType<typeof setTimeout> | undefined;
+ const wake = (immediate = false) => {
+ if (stopped) return;
+ if (immediate) {
+ clearTimeout(wakeWindow);
+ wakeWindow = undefined;
+ wakePending = false;
+ void runCatchUp();
+ return;
+ }
+ if (wakeWindow) {
+ wakePending = true;
+ return;
+ }
+ void runCatchUp();
+ wakeWindow = setTimeout(() => {
+ wakeWindow = undefined;
+ if (!wakePending) return;
+ wakePending = false;
+ wake();
+ }, WAKE_COALESCE_WINDOW_MS);
+ };
+ const gateway = new GatewayWakeChannel(
+ { ...resolved, onMirroredEvent: resolved.onMirroredEvent ? deliverMirrored : undefined },
+ wake,
+ (error) => fail(error),
+ );
+ const poll = setInterval(() => void runCatchUp(), HISTORY_POLL_INTERVAL_MS);
+
+ const close = () => {
+ if (stopped) return;
+ stopped = true;
+ clearInterval(poll);
+ clearTimeout(wakeWindow);
+ wakeWindow = undefined;
+ journal.close();
+ gateway.close();
+ };
+ const finish = () => {
+ close();
+ resolveDone();
+ };
+ const fail = (error: Error) => {
+ if (stopped) return;
+ close();
+ rejectDone(
+ error instanceof AgentStreamHistoryError ||
+ error instanceof AgentJournalUnsupportedError ||
+ error instanceof AgentGatewayUnavailableError
+ ? error
+ : new AgentStreamHistoryError(error.message),
+ );
+ };
+
+ gateway.connect();
+ return { abort: fail, catchUp: runCatchUp, close, done };
+};
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.delegation.test.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.delegation.test.ts
new file mode 100644
index 00000000000..eb169b5c8aa
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.delegation.test.ts
@@ -0,0 +1,80 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GatewayStreamNotifier } from './GatewayStreamNotifier';
+import { createMockInner } from './testUtils';
+
+const mockFetch = vi.fn().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
+vi.stubGlobal('fetch', mockFetch);
+
+describe('GatewayStreamNotifier read and lifecycle delegation', () => {
+ let inner: ReturnType<typeof createMockInner>;
+ let notifier: GatewayStreamNotifier;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ inner = createMockInner();
+ notifier = new GatewayStreamNotifier(inner, 'https://gateway.test.com', 'test-token');
+ });
+
+ // ─── Read/subscribe methods: must delegate directly to inner ───
+
+ describe('subscribeStreamEvents', () => {
+ it('delegates directly to inner', async () => {
+ const onEvents = vi.fn();
+ const signal = new AbortController().signal;
+
+ await notifier.subscribeStreamEvents('op-1', '0', onEvents, signal);
+
+ expect(inner.calls.subscribeStreamEvents).toHaveLength(1);
+ expect(inner.calls.subscribeStreamEvents[0]).toEqual(['op-1', '0', onEvents, signal]);
+ });
+
+ it('does not call gateway', async () => {
+ await notifier.subscribeStreamEvents('op-1', '0', vi.fn());
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('getStreamHistory', () => {
+ it('delegates directly to inner', async () => {
+ await notifier.getStreamHistory('op-1', 50);
+
+ expect(inner.calls.getStreamHistory).toHaveLength(1);
+ expect(inner.calls.getStreamHistory[0]).toEqual(['op-1', 50]);
+ });
+ });
+
+ describe('getStreamHistoryPage', () => {
+ it('delegates the exclusive history cursor to inner', async () => {
+ const result = await notifier.getStreamHistoryPage('op-1', '123-4', 200);
+
+ expect(inner.calls.getStreamHistoryPage).toEqual([['op-1', '123-4', 200]]);
+ expect(result).toBe('getStreamHistoryPage-result');
+ });
+ });
+
+ describe('cleanupOperation', () => {
+ it('delegates directly to inner', async () => {
+ await notifier.cleanupOperation('op-1');
+
+ expect(inner.calls.cleanupOperation).toHaveLength(1);
+ });
+ });
+
+ describe('getActiveOperationsCount', () => {
+ it('delegates directly to inner', async () => {
+ await notifier.getActiveOperationsCount();
+
+ expect(inner.calls.getActiveOperationsCount).toHaveLength(1);
+ });
+ });
+
+ describe('disconnect', () => {
+ it('delegates directly to inner', async () => {
+ await notifier.disconnect();
+
+ expect(inner.calls.disconnect).toHaveLength(1);
+ });
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index e1470fdfdff..ce58e6b768b 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -3,7 +3,6 @@ import type {
LlmExecuteData,
ToolExecuteData,
} from '@lobechat/agent-gateway-client';
-import { projectToolEndResult } from '@lobechat/tool-view-model';
import type { ChatMessageError } from '@lobechat/types';
import debug from 'debug';
import urlJoin from 'url-join';
@@ -11,6 +10,7 @@ import urlJoin from 'url-join';
import { sanitizeVisitorError } from '@/database/models/message';
import { shouldRecordGatewayError } from './gatewayErrorRecord';
+import { projectGatewayEventData, toMirroredEvent } from './gatewayEventProjection';
import {
buildPublicEndEventData,
buildPublicInitEventData,
@@ -33,76 +33,6 @@ import type {
const log = debug('lobe-server:agent-runtime:gateway-notifier');
-/**
- * The only `stream_end` fields anything on this wire reads.
- *
- * `finalContent` is the one the gateway client applies (a reasoning-only answer
- * arrives as chunks and gets promoted into it, so the bubble would be empty
- * without it). `stepLabel` is a short display label carried alongside.
- *
- * Everything else the event publishes β€” `reasoning`, `toolsCalling`, `usage`,
- * `grounding`, `imageList` β€” already reached this client token by token as
- * `stream_chunk`, and lands again, canonically, with the message. No gateway
- * consumer reads them here: the store's `stream_end` case touches
- * `finalContent` alone, and the CLI's renders nothing from the payload. On a
- * sampled run they were 12 kB of a 14 kB event.
- *
- * An allowlist rather than a denylist, so a new field on the publish site has
- * to be looked at before it rides along.
- */
-const STREAM_END_WIRE_FIELDS = ['finalContent', 'stepLabel'] as const;
-
-const projectStreamEndData = (data: unknown): unknown => {
- if (!data || typeof data !== 'object' || Array.isArray(data)) return data;
-
- const record = data as Record<string, unknown>;
- const projected: Record<string, unknown> = {};
- for (const field of STREAM_END_WIRE_FIELDS) {
- if (field in record) projected[field] = record[field];
- }
-
- return projected;
-};
-
-/**
- * Reduce an event to what the gateway wire actually needs.
- *
- * Both cuts here rest on the same fact: this socket is not how a result reaches
- * the screen. The message is, through a read path that already projects it, so
- * an event repeating the payload is a second copy of it. `tool_end` carries a
- * tool's body and state (see `projectToolEndResult`); `stream_end` carries the
- * assistant's reasoning and tool calls, which also arrived as chunks.
- *
- * This is the transport seam on purpose. The shared stream-manager chokepoint
- * would also catch the Responses API and the CLI's `--verbose`, both of which
- * print what is dropped here.
- */
-const projectGatewayEventData = (data: unknown, eventType: unknown): unknown => {
- if (eventType === 'tool_end') return projectToolEndResult(data);
- if (eventType === 'stream_end') return projectStreamEndData(data);
-
- return data;
-};
-
-/**
- * Shape an event for delivery on ANOTHER op's channel (a group member's events
- * mirrored onto the supervisor's socket).
- *
- * The gateway DO ends its session on any `agent_runtime_end` it receives,
- * whichever op the event names β€” so a member's terminal, mirrored verbatim,
- * closed the supervisor's session and every later supervisor step (the resume
- * after the member barrier, its final reply) was never streamed. The mirrored
- * copy is renamed to the non-terminal `member_runtime_end`: the client's member
- * handler still retires that member's column on it, while the DO, which only
- * reacts to `agent_runtime_end`, keeps the supervisor session open. The
- * member's own channel still receives the real terminal.
- *
- * Only applied when the mirror target's client declared it handles the new
- * event (`acceptsMemberRuntimeEnd`) β€” see `GatewayStreamNotifier.mirrorPush`.
- */
-export const toMirroredEvent = (event: Record<string, unknown>): Record<string, unknown> =>
- event.type === 'agent_runtime_end' ? { ...event, type: 'member_runtime_end' } : event;
-
const POST_TIMEOUT = 5000; // 5s per request
const MAX_INFLIGHT = 20; // bounded concurrency
@@ -631,6 +561,10 @@ export class GatewayStreamNotifier implements IStreamEventManager {
return this.inner.getStreamHistory(operationId, count);
}
+ async getStreamHistoryPage(operationId: string, cursor?: string, limit?: number) {
+ return this.inner.getStreamHistoryPage(operationId, cursor, limit);
+ }
+
async cleanupOperation(operationId: string): Promise<void> {
return this.inner.cleanupOperation(operationId);
}
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
index fdbdc817e2f..8ca3dfbc638 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
@@ -23,6 +23,9 @@ const getDefaultReasonDetail = (finalState: any, reason?: string): string => {
type EventCallback = (events: StreamEvent[]) => void;
+/** Matches Redis's two-hour inactivity TTL; streams are not trimmed by count. */
+const STREAM_RETENTION_MS = 2 * 3600 * 1000;
+
/**
* In-Memory Stream Event Manager
* In-memory implementation for testing and local development environments
@@ -31,6 +34,16 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
private streams: Map<string, StreamEvent[]> = new Map();
private subscribers: Map<string, EventCallback[]> = new Map();
private eventIdCounter = 0;
+ private lastPublishedAt = new Map<string, number>();
+
+ private evictExpiredStreams(): void {
+ const now = Date.now();
+ for (const [operationId, publishedAt] of this.lastPublishedAt) {
+ if (now - publishedAt <= STREAM_RETENTION_MS) continue;
+ this.streams.delete(operationId);
+ this.lastPublishedAt.delete(operationId);
+ }
+ }
private generateEventId(): string {
this.eventIdCounter++;
@@ -41,6 +54,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
operationId: string,
event: Omit<StreamEvent, 'operationId' | 'timestamp'>,
): Promise<string> {
+ this.evictExpiredStreams();
const eventId = this.generateEventId();
const eventData: StreamEvent = {
@@ -64,10 +78,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
stream.push(eventData);
- // Limit stream length to prevent memory overflow
- if (stream.length > 1000) {
- stream.shift();
- }
+ this.lastPublishedAt.set(operationId, Date.now());
log('Published event %s for operation %s:%d', eventData.type, operationId, eventData.stepIndex);
@@ -142,6 +153,22 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
return stream.slice(-count).reverse();
}
+ async getStreamHistoryPage(operationId: string, cursor = '0', limit = 200) {
+ this.evictExpiredStreams();
+ const stream = this.streams.get(operationId);
+ const index = cursor === '0' ? -1 : (stream?.findIndex((event) => event.id === cursor) ?? -1);
+ if (!stream || (cursor !== '0' && index < 0) || stream[0]?.type !== 'agent_runtime_init') {
+ return { available: false, events: [], hasMore: false, nextCursor: cursor };
+ }
+ const events = stream.slice(index + 1, index + 1 + limit);
+ return {
+ available: true,
+ events,
+ hasMore: stream.length > index + 1 + limit,
+ nextCursor: events.at(-1)?.id ?? cursor,
+ };
+ }
+
/**
* Single bounded read β€” the long-poll primitive (see `IStreamEventManager`).
* The in-memory manager is non-blocking: it returns immediately with whatever
@@ -167,6 +194,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
}
async cleanupOperation(operationId: string): Promise<void> {
+ this.lastPublishedAt.delete(operationId);
this.streams.delete(operationId);
this.subscribers.delete(operationId);
log('Cleaned up operation %s', operationId);
@@ -244,6 +272,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
* Clear all data (for testing)
*/
clear(): void {
+ this.lastPublishedAt.clear();
this.streams.clear();
this.subscribers.clear();
this.eventIdCounter = 0;
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
index 0c73414a50c..ee4afe9d549 100644
--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
@@ -129,6 +129,13 @@ export interface StreamEvent {
type: AgentStreamEventType;
}
+export interface StreamHistoryPage {
+ available: boolean;
+ events: StreamEvent[];
+ hasMore: boolean;
+ nextCursor: string;
+}
+
export interface StreamChunkData {
chunkType:
| 'text'
@@ -155,6 +162,23 @@ export interface StreamChunkData {
toolsCalling?: ChatToolPayload[];
}
+/** Decode one Redis stream entry (`[id, [field, value, ...]]`) into a `StreamEvent`. */
+const parseStreamEntry = (id: string, fields: string[]): StreamEvent => {
+ const eventData: any = {};
+ for (let i = 0; i < fields.length; i += 2) {
+ const key = fields[i];
+ const value = fields[i + 1];
+ if (key === 'data') {
+ eventData[key] = JSON.parse(value);
+ } else if (key === 'stepIndex' || key === 'timestamp') {
+ eventData[key] = parseInt(value);
+ } else {
+ eventData[key] = value;
+ }
+ }
+ return { ...eventData, id } as StreamEvent;
+};
+
export class StreamEventManager {
private redis: Redis;
private readonly STREAM_PREFIX = 'agent_runtime_stream';
@@ -216,9 +240,8 @@ export class StreamEventManager {
const xaddStart = Date.now();
const eventId = await this.redis.xadd(
streamKey,
- 'MAXLEN',
- '~',
- '1000', // Limit stream length to prevent memory overflow
+ // Retain every event until the stream's inactivity TTL expires.
+ // Count trimming makes a reconnect silently lose earlier output.
'*', // Auto-generate ID
'type',
eventData.type,
@@ -350,26 +373,7 @@ export class StreamEventManager {
const events: StreamEvent[] = [];
for (const [id, fields] of messages) {
- const eventData: any = {};
-
- // Parse Redis Stream fields
- for (let i = 0; i < fields.length; i += 2) {
- const key = fields[i];
- const value = fields[i + 1];
-
- if (key === 'data') {
- eventData[key] = JSON.parse(value);
- } else if (key === 'stepIndex' || key === 'timestamp') {
- eventData[key] = parseInt(value);
- } else {
- eventData[key] = value;
- }
- }
-
- events.push({
- ...eventData,
- id, // Redis Stream event ID
- } as StreamEvent);
+ events.push(parseStreamEntry(id, fields));
currentLastId = id;
}
@@ -452,19 +456,7 @@ export class StreamEventManager {
let currentLastId = fromId;
for (const [id, fields] of messages) {
- const eventData: any = {};
- for (let i = 0; i < fields.length; i += 2) {
- const key = fields[i];
- const value = fields[i + 1];
- if (key === 'data') {
- eventData[key] = JSON.parse(value);
- } else if (key === 'stepIndex' || key === 'timestamp') {
- eventData[key] = parseInt(value);
- } else {
- eventData[key] = value;
- }
- }
- events.push({ ...eventData, id } as StreamEvent);
+ events.push(parseStreamEntry(id, fields));
currentLastId = id;
}
@@ -480,30 +472,43 @@ export class StreamEventManager {
try {
const results = await this.redis.xrevrange(streamKey, '+', '-', 'COUNT', count);
- return results.map(([id, fields]) => {
- const eventData: any = { id };
-
- for (let i = 0; i < fields.length; i += 2) {
- const key = fields[i];
- const value = fields[i + 1];
-
- if (key === 'data') {
- eventData[key] = JSON.parse(value);
- } else if (key === 'stepIndex' || key === 'timestamp') {
- eventData[key] = parseInt(value);
- } else {
- eventData[key] = value;
- }
- }
-
- return eventData as StreamEvent;
- });
+ return results.map(([id, fields]) => parseStreamEntry(id, fields));
} catch (error) {
console.error('[StreamEventManager] Failed to get stream history:', error);
return [];
}
}
+ /** Forward, exclusive-cursor replay; never substitute a truncated suffix for full history. */
+ async getStreamHistoryPage(
+ operationId: string,
+ cursor = '0',
+ limit = 200,
+ ): Promise<StreamHistoryPage> {
+ const key = `${this.STREAM_PREFIX}:${operationId}`;
+ const unavailable = { available: false, events: [], hasMore: false, nextCursor: cursor };
+ if (cursor !== '0') {
+ const previous = await this.redis.xrange(key, cursor, cursor, 'COUNT', 1);
+ if (previous.length === 0) return unavailable;
+ }
+ const rows = await this.redis.xrange(
+ key,
+ cursor === '0' ? '-' : `(${cursor}`,
+ '+',
+ 'COUNT',
+ limit + 1,
+ );
+ const events = rows.slice(0, limit).map(([id, fields]) => parseStreamEntry(id, fields));
+ // Legacy streams may already have been trimmed before this deployment.
+ if (cursor === '0' && events[0]?.type !== 'agent_runtime_init') return unavailable;
+ return {
+ available: true,
+ events,
+ hasMore: rows.length > limit,
+ nextCursor: events.at(-1)?.id ?? cursor,
+ };
+ }
+
/**
* Clean up stream data for operation
*/
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 1bbe4ac6c61..ff80fd91177 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -3,38 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { GatewayStreamNotifier } from '../GatewayStreamNotifier';
import { FULL_STRIP_REDACTION, sanitizeGatewayEventData } from '../gatewayVisitorRedaction';
import type { StreamChunkData } from '../StreamEventManager';
-import type { IStreamEventManager, PublishAgentRuntimeEndParams } from '../types';
+import { createMockInner } from '../testUtils';
+import type { PublishAgentRuntimeEndParams } from '../types';
// Mock global fetch
const mockFetch = vi.fn().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
vi.stubGlobal('fetch', mockFetch);
-function createMockInner(): IStreamEventManager & { calls: Record<string, any[][]> } {
- const calls: Record<string, any[][]> = {};
-
- const track = (name: string) => {
- calls[name] = [];
- return (...args: any[]) => {
- calls[name].push(args);
- return Promise.resolve(`${name}-result`);
- };
- };
-
- return {
- calls,
- cleanupOperation: track('cleanupOperation') as any,
- disconnect: track('disconnect') as any,
- getActiveOperationsCount: track('getActiveOperationsCount') as any,
- getStreamHistory: track('getStreamHistory') as any,
- publishAgentRuntimeEnd: track('publishAgentRuntimeEnd') as any,
- publishAgentRuntimeInit: track('publishAgentRuntimeInit') as any,
- publishStreamChunk: track('publishStreamChunk') as any,
- publishStreamEvent: track('publishStreamEvent') as any,
- readEventsOnce: track('readEventsOnce') as any,
- subscribeStreamEvents: track('subscribeStreamEvents') as any,
- };
-}
-
describe('GatewayStreamNotifier', () => {
let inner: ReturnType<typeof createMockInner>;
let notifier: GatewayStreamNotifier;
@@ -828,59 +803,6 @@ describe('GatewayStreamNotifier', () => {
});
});
- // ─── Read/subscribe methods: must delegate directly to inner ───
-
- describe('subscribeStreamEvents', () => {
- it('delegates directly to inner', async () => {
- const onEvents = vi.fn();
- const signal = new AbortController().signal;
-
- await notifier.subscribeStreamEvents('op-1', '0', onEvents, signal);
-
- expect(inner.calls.subscribeStreamEvents).toHaveLength(1);
- expect(inner.calls.subscribeStreamEvents[0]).toEqual(['op-1', '0', onEvents, signal]);
- });
-
- it('does not call gateway', async () => {
- await notifier.subscribeStreamEvents('op-1', '0', vi.fn());
-
- expect(mockFetch).not.toHaveBeenCalled();
- });
- });
-
- describe('getStreamHistory', () => {
- it('delegates directly to inner', async () => {
- await notifier.getStreamHistory('op-1', 50);
-
- expect(inner.calls.getStreamHistory).toHaveLength(1);
- expect(inner.calls.getStreamHistory[0]).toEqual(['op-1', 50]);
- });
- });
-
- describe('cleanupOperation', () => {
- it('delegates directly to inner', async () => {
- await notifier.cleanupOperation('op-1');
-
- expect(inner.calls.cleanupOperation).toHaveLength(1);
- });
- });
-
- describe('getActiveOperationsCount', () => {
- it('delegates directly to inner', async () => {
- await notifier.getActiveOperationsCount();
-
- expect(inner.calls.getActiveOperationsCount).toHaveLength(1);
- });
- });
-
- describe('disconnect', () => {
- it('delegates directly to inner', async () => {
- await notifier.disconnect();
-
- expect(inner.calls.disconnect).toHaveLength(1);
- });
- });
-
// ─── Gateway failure resilience ───
describe('gateway failure does not affect inner', () => {
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
index ac3dc4012e3..2622bfe176b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
@@ -96,6 +96,39 @@ describe('InMemoryStreamEventManager', () => {
});
});
+ it('retains and paginates the complete history beyond the old 1000-event cap', async () => {
+ await manager.publishAgentRuntimeInit('op-1', {});
+ for (let n = 0; n < 1200; n++)
+ await manager.publishStreamEvent('op-1', { data: { n }, stepIndex: 0, type: 'stream_chunk' });
+ expect(manager.getAllEvents('op-1')).toHaveLength(1201);
+ let cursor = '0';
+ const ids: string[] = [];
+ let hasMore = true;
+ while (hasMore) {
+ const page = await manager.getStreamHistoryPage('op-1', cursor, 200);
+ expect(page.available).toBe(true);
+ ids.push(...page.events.map((event) => event.id!));
+ cursor = page.nextCursor;
+ hasMore = page.hasMore;
+ }
+ expect(ids).toHaveLength(1201);
+ expect(new Set(ids).size).toBe(1201);
+ expect((await manager.getStreamHistoryPage('op-1', cursor)).events).toEqual([]);
+ expect((await manager.getStreamHistoryPage('op-1', 'missing')).available).toBe(false);
+ });
+
+ it('reports history unavailable after the two-hour retention window', async () => {
+ const now = vi.spyOn(Date, 'now');
+ try {
+ now.mockReturnValue(1000);
+ await manager.publishAgentRuntimeInit('op-1', {});
+ now.mockReturnValue(1000 + 2 * 3600 * 1000 + 1);
+ expect((await manager.getStreamHistoryPage('op-1')).available).toBe(false);
+ } finally {
+ now.mockRestore();
+ }
+ });
+
describe('subscribe', () => {
it('should return an unsubscribe function', async () => {
const callback = vi.fn();
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
index 893618509e1..1af6903bd6b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
@@ -27,6 +27,7 @@ const mockRedis = {
xadd: vi.fn(),
xread: vi.fn(),
xrevrange: vi.fn(),
+ xrange: vi.fn(),
};
vi.mock('../redis', () => ({
@@ -61,9 +62,6 @@ describe('StreamEventManager', () => {
expect(result).toBe('event-id-123');
expect(mockRedis.xadd).toHaveBeenCalledWith(
`agent_runtime_stream:${operationId}`,
- 'MAXLEN',
- '~',
- '1000',
'*',
'type',
'agent_runtime_init',
@@ -79,6 +77,50 @@ describe('StreamEventManager', () => {
});
});
+ describe('getStreamHistoryPage', () => {
+ const row = (id: string, type: string) => [
+ id,
+ ['type', type, 'stepIndex', '0', 'operationId', 'op-1', 'data', '{}', 'timestamp', '1'],
+ ];
+
+ it('returns forward pages with an exclusive cursor and typed event fields', async () => {
+ mockRedis.xrange.mockResolvedValueOnce([
+ row('1-0', 'agent_runtime_init'),
+ row('2-0', 'stream_chunk'),
+ row('3-0', 'stream_chunk'),
+ ]);
+ const page = await streamManager.getStreamHistoryPage('op-1', '0', 2);
+ expect(page).toMatchObject({ available: true, hasMore: true, nextCursor: '2-0' });
+ expect(page.events.map((event) => event.id)).toEqual(['1-0', '2-0']);
+ expect(page.events[0]).toMatchObject({ data: {}, stepIndex: 0, timestamp: 1 });
+ mockRedis.xrange
+ .mockResolvedValueOnce([row('2-0', 'stream_chunk')])
+ .mockResolvedValueOnce([row('3-0', 'stream_chunk')]);
+ expect((await streamManager.getStreamHistoryPage('op-1', '2-0', 2)).events[0].id).toBe('3-0');
+ expect(mockRedis.xrange).toHaveBeenLastCalledWith(
+ 'agent_runtime_stream:op-1',
+ '(2-0',
+ '+',
+ 'COUNT',
+ 3,
+ );
+ });
+
+ it('fails closed for a legacy truncated prefix, an expired stream, or a missing cursor', async () => {
+ mockRedis.xrange.mockResolvedValueOnce([row('100-0', 'stream_chunk')]);
+ expect((await streamManager.getStreamHistoryPage('op-1')).available).toBe(false);
+ mockRedis.xrange.mockResolvedValueOnce([]);
+ expect((await streamManager.getStreamHistoryPage('op-1')).available).toBe(false);
+ mockRedis.xrange.mockResolvedValueOnce([]);
+ expect((await streamManager.getStreamHistoryPage('op-1', '1-0')).available).toBe(false);
+ });
+
+ it('propagates Redis errors instead of reporting an empty successful history', async () => {
+ mockRedis.xrange.mockRejectedValueOnce(new Error('Redis unavailable'));
+ await expect(streamManager.getStreamHistoryPage('op-1')).rejects.toThrow('Redis unavailable');
+ });
+ });
+
describe('publishAgentRuntimeEnd', () => {
it('should publish agent runtime end event with correct data', async () => {
const operationId = 'test-operation-id';
@@ -100,9 +142,6 @@ describe('StreamEventManager', () => {
expect(result).toBe('event-id-456');
expect(mockRedis.xadd).toHaveBeenCalledWith(
`agent_runtime_stream:${operationId}`,
- 'MAXLEN',
- '~',
- '1000',
'*',
'type',
'agent_runtime_end',
@@ -192,9 +231,6 @@ describe('StreamEventManager', () => {
expect.any(String),
expect.any(String),
expect.any(String),
- expect.any(String),
- expect.any(String),
- expect.any(String),
operationId,
'data',
JSON.stringify({
@@ -237,9 +273,6 @@ describe('StreamEventManager', () => {
expect.any(String),
expect.any(String),
expect.any(String),
- expect.any(String),
- expect.any(String),
- expect.any(String),
operationId,
'data',
JSON.stringify({
diff --git a/apps/server/src/modules/AgentRuntime/gatewayEventProjection.ts b/apps/server/src/modules/AgentRuntime/gatewayEventProjection.ts
new file mode 100644
index 00000000000..80da4fc77ea
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/gatewayEventProjection.ts
@@ -0,0 +1,71 @@
+import { projectToolEndResult } from '@lobechat/tool-view-model';
+
+/**
+ * The only `stream_end` fields anything on this wire reads.
+ *
+ * `finalContent` is the one the gateway client applies (a reasoning-only answer
+ * arrives as chunks and gets promoted into it, so the bubble would be empty
+ * without it). `stepLabel` is a short display label carried alongside.
+ *
+ * Everything else the event publishes β€” `reasoning`, `toolsCalling`, `usage`,
+ * `grounding`, `imageList` β€” already reached this client token by token as
+ * `stream_chunk`, and lands again, canonically, with the message. No gateway
+ * consumer reads them here: the store's `stream_end` case touches
+ * `finalContent` alone, and the CLI's renders nothing from the payload. On a
+ * sampled run they were 12 kB of a 14 kB event.
+ *
+ * An allowlist rather than a denylist, so a new field on the publish site has
+ * to be looked at before it rides along.
+ */
+const STREAM_END_WIRE_FIELDS = ['finalContent', 'stepLabel'] as const;
+
+const projectStreamEndData = (data: unknown): unknown => {
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return data;
+
+ const record = data as Record<string, unknown>;
+ const projected: Record<string, unknown> = {};
+ for (const field of STREAM_END_WIRE_FIELDS) {
+ if (field in record) projected[field] = record[field];
+ }
+
+ return projected;
+};
+
+/**
+ * Reduce an event to what the gateway wire actually needs.
+ *
+ * Both cuts here rest on the same fact: this socket is not how a result reaches
+ * the screen. The message is, through a read path that already projects it, so
+ * an event repeating the payload is a second copy of it. `tool_end` carries a
+ * tool's body and state (see `projectToolEndResult`); `stream_end` carries the
+ * assistant's reasoning and tool calls, which also arrived as chunks.
+ *
+ * This is the transport seam on purpose. The shared stream-manager chokepoint
+ * would also catch the Responses API and the CLI's `--verbose`, both of which
+ * print what is dropped here.
+ */
+export const projectGatewayEventData = (data: unknown, eventType: unknown): unknown => {
+ if (eventType === 'tool_end') return projectToolEndResult(data);
+ if (eventType === 'stream_end') return projectStreamEndData(data);
+
+ return data;
+};
+
+/**
+ * Shape an event for delivery on ANOTHER op's channel (a group member's events
+ * mirrored onto the supervisor's socket).
+ *
+ * The gateway DO ends its session on any `agent_runtime_end` it receives,
+ * whichever op the event names β€” so a member's terminal, mirrored verbatim,
+ * closed the supervisor's session and every later supervisor step (the resume
+ * after the member barrier, its final reply) was never streamed. The mirrored
+ * copy is renamed to the non-terminal `member_runtime_end`: the client's member
+ * handler still retires that member's column on it, while the DO, which only
+ * reacts to `agent_runtime_end`, keeps the supervisor session open. The
+ * member's own channel still receives the real terminal.
+ *
+ * Only applied when the mirror target's client declared it handles the new
+ * event (`acceptsMemberRuntimeEnd`) β€” see `GatewayStreamNotifier.mirrorPush`.
+ */
+export const toMirroredEvent = (event: Record<string, unknown>): Record<string, unknown> =>
+ event.type === 'agent_runtime_end' ? { ...event, type: 'member_runtime_end' } : event;
diff --git a/apps/server/src/modules/AgentRuntime/testUtils.ts b/apps/server/src/modules/AgentRuntime/testUtils.ts
new file mode 100644
index 00000000000..122e146c5e5
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/testUtils.ts
@@ -0,0 +1,29 @@
+import type { IStreamEventManager } from './types';
+
+/** An `IStreamEventManager` that records each call and resolves `<method>-result`. */
+export function createMockInner(): IStreamEventManager & { calls: Record<string, any[][]> } {
+ const calls: Record<string, any[][]> = {};
+
+ const track = (name: string) => {
+ calls[name] = [];
+ return (...args: any[]) => {
+ calls[name].push(args);
+ return Promise.resolve(`${name}-result`);
+ };
+ };
+
+ return {
+ calls,
+ cleanupOperation: track('cleanupOperation') as any,
+ disconnect: track('disconnect') as any,
+ getActiveOperationsCount: track('getActiveOperationsCount') as any,
+ getStreamHistory: track('getStreamHistory') as any,
+ getStreamHistoryPage: track('getStreamHistoryPage') as any,
+ publishAgentRuntimeEnd: track('publishAgentRuntimeEnd') as any,
+ publishAgentRuntimeInit: track('publishAgentRuntimeInit') as any,
+ publishStreamChunk: track('publishStreamChunk') as any,
+ publishStreamEvent: track('publishStreamEvent') as any,
+ readEventsOnce: track('readEventsOnce') as any,
+ subscribeStreamEvents: track('subscribeStreamEvents') as any,
+ };
+}
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index fa84d527eb7..60dc2bf1018 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -7,7 +7,11 @@ import { type AgentState } from '@lobechat/agent-runtime';
import { type UIChatMessage } from '@lobechat/types';
import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';
-import { type StreamChunkData, type StreamEvent } from './StreamEventManager';
+import {
+ type StreamChunkData,
+ type StreamEvent,
+ type StreamHistoryPage,
+} from './StreamEventManager';
export interface PublishAgentRuntimeEndParams {
finalState: any;
@@ -221,6 +225,12 @@ export interface IStreamEventManager {
*/
getStreamHistory: (operationId: string, count?: number) => Promise<StreamEvent[]>;
+ getStreamHistoryPage: (
+ operationId: string,
+ cursor?: string,
+ limit?: number,
+ ) => Promise<StreamHistoryPage>;
+
/**
* Optional: open a one-shot relay channel on the gateway, owned by `userId`.
* Present only with a gateway, like {@link sendLlmExecute}.
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.ts
index 2143d110ef7..7590f416324 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.operationReadGuard.test.ts
@@ -8,6 +8,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiAgentRouter } from '../aiAgent';
import { cleanupTestUser, createTestUser } from './integration/setup';
+const { mockHistoryPage, mockRuntimeMetadata } = vi.hoisted(() => ({
+ mockHistoryPage: vi.fn(),
+ mockRuntimeMetadata: vi.fn(),
+}));
+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ createStreamEventManager: () => ({ getStreamHistoryPage: mockHistoryPage }),
+ createAgentStateManager: () => ({ getOperationMetadata: mockRuntimeMetadata }),
+}));
+
let testDB: LobeChatDatabase;
vi.mock('@/database/core/db-adaptor', () => ({
getServerDB: vi.fn(function () {
@@ -65,6 +75,10 @@ describe('aiAgentRouter operation read guard', () => {
userId: ownerId,
});
+ mockHistoryPage
+ .mockReset()
+ .mockResolvedValue({ available: true, events: [], hasMore: false, nextCursor: '0' });
+ mockRuntimeMetadata.mockReset().mockResolvedValue(null);
mockGetOperationStatus.mockReset().mockResolvedValue({ metadata: { agentConfig: {} } });
mockGetPendingInterventions.mockReset().mockResolvedValue({ pendingInterventions: [] });
});
@@ -154,4 +168,72 @@ describe('aiAgentRouter operation read guard', () => {
});
});
});
+
+ describe('getOperationStreamHistory', () => {
+ it('returns a bounded page only to an authorized operation owner', async () => {
+ await callerFor(ownerId).getOperationStreamHistory({
+ operationId,
+ cursor: '12-0',
+ limit: 20,
+ });
+ expect(mockHistoryPage).toHaveBeenCalledWith(operationId, '12-0', 20);
+ await expect(
+ callerFor(visitorId).getOperationStreamHistory({ operationId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockHistoryPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses runtime ownership after a non-fatal initial database insert failure', async () => {
+ await serverDB.delete(agentOperations).where(eq(agentOperations.id, operationId));
+ mockRuntimeMetadata.mockResolvedValue({ userId: ownerId });
+ await callerFor(ownerId).getOperationStreamHistory({ operationId });
+ expect(mockHistoryPage).toHaveBeenCalledWith(operationId, '0', 200);
+ await expect(
+ callerFor(visitorId).getOperationStreamHistory({ operationId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockHistoryPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('never exposes a share run through the runtime fallback', async () => {
+ await serverDB.delete(agentOperations).where(eq(agentOperations.id, operationId));
+ mockRuntimeMetadata.mockResolvedValue({ userId: ownerId, streamOwnerUserId: visitorId });
+ await expect(
+ callerFor(ownerId).getOperationStreamHistory({ operationId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(
+ callerFor(visitorId).getOperationStreamHistory({ operationId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockHistoryPage).not.toHaveBeenCalled();
+ });
+
+ it('does not bypass a persisted visitor-topic exclusion with owner metadata', async () => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ senderId: visitorId, title: 'visitor', userId: ownerId })
+ .returning();
+ await serverDB
+ .update(agentOperations)
+ .set({ topicId: topic.id })
+ .where(eq(agentOperations.id, operationId));
+ mockRuntimeMetadata.mockResolvedValue({ userId: ownerId });
+ await expect(
+ callerFor(ownerId).getOperationStreamHistory({ operationId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockHistoryPage).not.toHaveBeenCalled();
+ expect(mockRuntimeMetadata).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unknown operation and invalid cursor/limit without reading events', async () => {
+ await expect(
+ callerFor(ownerId).getOperationStreamHistory({ operationId: 'missing' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(
+ callerFor(ownerId).getOperationStreamHistory({ operationId, cursor: '$' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ await expect(
+ callerFor(ownerId).getOperationStreamHistory({ operationId, limit: 201 }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mockHistoryPage).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/_helpers/operationReadGuard.ts b/apps/server/src/routers/lambda/_helpers/operationReadGuard.ts
new file mode 100644
index 00000000000..bc682fcafd8
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/operationReadGuard.ts
@@ -0,0 +1,108 @@
+import { TRPCError } from '@trpc/server';
+import { and, eq } from 'drizzle-orm';
+
+import { agentOperations } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { notShareVisitorTopicRef } from '@/database/utils/shareVisitor';
+import { createAgentStateManager } from '@/server/modules/AgentRuntime/factory';
+
+import { assertCanUseWorkspaceAgent } from './workspaceAgentGuard';
+
+interface OperationReadParams {
+ db: LobeChatDatabase;
+ operationId: string;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+const operationNotFound = () =>
+ new TRPCError({ code: 'NOT_FOUND', message: 'Operation not found' });
+
+/**
+ * Ownership guard for operation-keyed READ endpoints (`getOperationStatus`,
+ * `getPendingInterventions`). The runtime coordinator keys operations purely
+ * by id and returns the raw operation metadata β€” including the executing
+ * user's full `agentConfig` and `modelRuntimeConfig` β€” so the id itself must
+ * not act as a bearer token.
+ *
+ * Historically that was inert: an operation id was only ever known to the
+ * user who started it. Agent Share breaks the assumption on purpose β€” a share
+ * run executes under the CREATOR's identity while the VISITOR receives the
+ * `operationId` (to attach to the Gateway stream, which redacts creator
+ * details). Without this guard the visitor could replay that id here and read
+ * the unredacted creator config the stream path deliberately hides.
+ *
+ * Visible to: the operation's owner, or (workspace runs) a member with `use`
+ * access to the operation's agent in the SAME workspace as the caller.
+ * Everything else β€” share visitors, AND the creator looking at a visitor's
+ * run β€” resolves as NOT_FOUND so the endpoint does not confirm which ids
+ * exist.
+ */
+export const assertOperationVisibleToCaller = async (params: OperationReadParams) => {
+ if (!(await isPersistedOperationVisible(params))) throw operationNotFound();
+};
+
+/**
+ * Guard for the operation's stream event journal. Same visibility as
+ * {@link assertOperationVisibleToCaller}, plus one fallback: the initial
+ * operation insert is deliberately non-fatal, so a live run can exist only in
+ * runtime metadata. Its owner may still read the journal β€” but only for a
+ * genuinely absent row, never for a persisted visitor-topic operation the
+ * visibility filter hid, and never for a Share run (`streamOwnerUserId`).
+ */
+export const assertOperationStreamReadable = async (params: OperationReadParams) => {
+ const visible = await isPersistedOperationVisible(params);
+ if (visible) return;
+ if (visible === undefined && (await isUnpersistedRuntimeOwner(params))) return;
+ throw operationNotFound();
+};
+
+/**
+ * `true`/`false` for a visible/hidden persisted row; `undefined` when the
+ * visibility filter found no row at all.
+ */
+const isPersistedOperationVisible = async ({
+ db,
+ operationId,
+ userId,
+ workspaceId,
+}: OperationReadParams): Promise<boolean | undefined> => {
+ // Share-visitor runs are ALSO excluded (`notShareVisitorTopicRef`): they
+ // execute under the creator's userId, so the owner shortcut below would
+ // otherwise hand the creator the visitor's run metadata, history and
+ // stream events β€” the same exclusion `findOwnOperationById` applies to
+ // the trace reads.
+ const [row] = await db
+ .select({
+ agentId: agentOperations.agentId,
+ userId: agentOperations.userId,
+ workspaceId: agentOperations.workspaceId,
+ })
+ .from(agentOperations)
+ .where(
+ and(eq(agentOperations.id, operationId), notShareVisitorTopicRef(agentOperations.topicId)),
+ )
+ .limit(1);
+
+ if (!row) return undefined;
+ if (row.userId === userId) return true;
+
+ if (!row.workspaceId || !workspaceId || row.workspaceId !== workspaceId || !row.agentId) {
+ return false;
+ }
+
+ await assertCanUseWorkspaceAgent({ agentId: row.agentId, db, userId, workspaceId });
+ return true;
+};
+
+const isUnpersistedRuntimeOwner = async ({ db, operationId, userId }: OperationReadParams) => {
+ const [persisted] = await db
+ .select({ id: agentOperations.id })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId))
+ .limit(1);
+ if (persisted) return false;
+
+ const metadata = await createAgentStateManager().getOperationMetadata(operationId);
+ return metadata?.userId === userId && !metadata.streamOwnerUserId;
+};
diff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts
index 430a147b261..3cf5ba1ba08 100644
--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts
@@ -37,6 +37,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query', middleware
['getAgentInterventionReviewBySource', 'mutation', 11],
['getHeteroInterventionReview', 'mutation', 11],
['getOperationStatus', 'query', 12],
+ ['getOperationStreamHistory', 'query', 11],
['getPendingInterventions', 'query', 12],
['getServerDefaultHeterogeneousCapability', 'query', 10],
['getSubAgentTaskStatus', 'query', 12],
diff --git a/apps/server/src/routers/lambda/aiAgent/operationStatus.ts b/apps/server/src/routers/lambda/aiAgent/operationStatus.ts
index ebd288c6fd6..44fd3770974 100644
--- a/apps/server/src/routers/lambda/aiAgent/operationStatus.ts
+++ b/apps/server/src/routers/lambda/aiAgent/operationStatus.ts
@@ -3,77 +3,20 @@ import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';
import { ThreadStatus } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
-import { and, eq } from 'drizzle-orm';
import { z } from 'zod';
-import { agentOperations } from '@/database/schemas';
-import type { LobeChatDatabase } from '@/database/type';
-import { notShareVisitorTopicRef } from '@/database/utils/shareVisitor';
import { router } from '@/libs/trpc/lambda';
-import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import {
+ assertOperationStreamReadable,
+ assertOperationVisibleToCaller,
+} from '@/server/routers/lambda/_helpers/operationReadGuard';
-import { aiAgentProcedure } from './procedures';
+import { aiAgentBaseProcedure, aiAgentProcedure } from './procedures';
import { createUiMessageFileUrlResolver } from './utils';
const log = debug('lobe-server:ai-agent-router');
-/**
- * Ownership guard for operation-keyed READ endpoints (`getOperationStatus`,
- * `getPendingInterventions`). The runtime coordinator keys operations purely
- * by id and returns the raw operation metadata β€” including the executing
- * user's full `agentConfig` and `modelRuntimeConfig` β€” so the id itself must
- * not act as a bearer token.
- *
- * Historically that was inert: an operation id was only ever known to the
- * user who started it. Agent Share breaks the assumption on purpose β€” a share
- * run executes under the CREATOR's identity while the VISITOR receives the
- * `operationId` (to attach to the Gateway stream, which redacts creator
- * details). Without this guard the visitor could replay that id here and read
- * the unredacted creator config the stream path deliberately hides.
- *
- * Visible to: the operation's owner, or (workspace runs) a member with `use`
- * access to the operation's agent in the SAME workspace as the caller.
- * Everything else β€” share visitors, AND the creator looking at a visitor's
- * run β€” resolves as NOT_FOUND so the endpoint does not confirm which ids
- * exist.
- */
-const assertOperationVisibleToCaller = async (params: {
- db: LobeChatDatabase;
- operationId: string;
- userId: string;
- workspaceId?: string | null;
-}) => {
- const { db, operationId, userId, workspaceId } = params;
-
- // Share-visitor runs are ALSO excluded (`notShareVisitorTopicRef`): they
- // execute under the creator's userId, so the owner shortcut below would
- // otherwise hand the creator the visitor's run metadata, history and
- // stream events β€” the same exclusion `findOwnOperationById` applies to
- // the trace reads.
- const [row] = await db
- .select({
- agentId: agentOperations.agentId,
- userId: agentOperations.userId,
- workspaceId: agentOperations.workspaceId,
- })
- .from(agentOperations)
- .where(
- and(eq(agentOperations.id, operationId), notShareVisitorTopicRef(agentOperations.topicId)),
- )
- .limit(1);
-
- const notFound = () => new TRPCError({ code: 'NOT_FOUND', message: 'Operation not found' });
-
- if (!row) throw notFound();
- if (row.userId === userId) return;
-
- if (!row.workspaceId || !workspaceId || row.workspaceId !== workspaceId || !row.agentId) {
- throw notFound();
- }
-
- await assertCanUseWorkspaceAgent({ agentId: row.agentId, db, userId, workspaceId });
-};
-
const extractTaskErrorMessage = (error: unknown): string | undefined => {
if (!error || typeof error !== 'object') return undefined;
@@ -137,7 +80,38 @@ const GetPendingInterventionsSchema = z
message: 'Either operationId or userId must be provided',
});
+const GetOperationStreamHistorySchema = z.object({
+ /** Exclusive Redis stream id; `0` reads from the start. */
+ cursor: z
+ .string()
+ .regex(/^(0|\d+-\d+)$/)
+ .default('0'),
+ limit: z.number().int().min(1).max(200).default(200),
+ operationId: z.string().min(1),
+});
+
export const operationStatusRouter = router({
+ /**
+ * Forward page of the operation's retained event journal. The CLI treats it
+ * as the authoritative event source and the Gateway WebSocket as a wake-up.
+ */
+ getOperationStreamHistory: aiAgentBaseProcedure
+ .input(GetOperationStreamHistorySchema)
+ .query(async ({ input, ctx }) => {
+ await assertOperationStreamReadable({
+ db: ctx.serverDB,
+ operationId: input.operationId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ return createStreamEventManager().getStreamHistoryPage(
+ input.operationId,
+ input.cursor,
+ input.limit,
+ );
+ }),
+
getOperationStatus: aiAgentProcedure
.input(GetOperationStatusSchema)
.query(async ({ input, ctx }) => {
diff --git a/packages/builtin-skills/src/lobehub/references/generate.ts b/packages/builtin-skills/src/lobehub/references/generate.ts
index f6c0df88f05..32a7ace49b4 100644
--- a/packages/builtin-skills/src/lobehub/references/generate.ts
+++ b/packages/builtin-skills/src/lobehub/references/generate.ts
@@ -4,7 +4,7 @@ Generate text, images, videos, and audio. Alias: \`lh generate\`.
## Subcommands
-- \`lh gen text <prompt> [-m <model>] [-p <provider>] [--stream] [--temperature <t>]\` - Generate text
+- \`lh gen text <prompt> [-m <model>] [-p <provider>] [--temperature <t>]\` - Generate text
- \`lh gen image <prompt> [-m <model>] [-n <count>] [--width <w>] [--height <h>]\` - Generate image
- \`lh gen video <prompt> -m <model> -p <provider> [--aspect-ratio <r>] [--duration <d>] [--resolution <res>]\` - Generate video
- \`lh gen tts <text> [-m <model>] [-p <provider>] [-o <output>] [--voice <v>] [--speed <s>]\` - Text-to-speech using the selected provider's saved configuration
@@ -16,7 +16,7 @@ Generate text, images, videos, and audio. Alias: \`lh generate\`.
## Tips
- Image/video generation is async; use \`status\` or \`download\` to get results
-- \`--stream\` for text generation outputs tokens as they arrive
+- Text generation returns the complete response, without incremental streaming
- \`--pipe\` for text generation outputs only the raw text (no formatting)
## Finding Available Video / Image Models