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.

♻️ refactor: add WebSocket gateway support to CLI agent run (#13608)

Arvin Xu1a58d530fbd8
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index a3811e87c24..60fbf26c616 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -5,7 +5,12 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { getAgentStreamAuthInfo } from '../api/http';
-import { replayAgentEvents, streamAgentEvents } from '../utils/agentStream';
+import { resolveAgentGatewayUrl } from '../settings';
+import {
+ replayAgentEvents,
+ streamAgentEvents,
+ streamAgentEventsViaWebSocket,
+} from '../utils/agentStream';
import { resolveLocalDeviceId } from '../utils/device';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
import { log, setVerbose } from '../utils/logger';
@@ -256,6 +261,7 @@ export function registerAgentCommand(program: Command) {
.option('--json', 'Output full JSON event stream')
.option('-v, --verbose', 'Show detailed tool call info')
.option('--replay <file>', 'Replay events from a saved JSON file (offline)')
+ .option('--sse', 'Force SSE stream instead of WebSocket gateway')
.action(
async (options: {
agentId?: string;
@@ -265,6 +271,7 @@ export function registerAgentCommand(program: Command) {
prompt?: string;
replay?: string;
slug?: string;
+ sse?: boolean;
topicId?: string;
verbose?: boolean;
}) => {
@@ -347,14 +354,26 @@ export function registerAgentCommand(program: Command) {
log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
}
- // 2. Connect to SSE stream
+ // 2. Connect to stream (WebSocket via Gateway, or fallback to SSE)
const { serverUrl, headers } = await getAgentStreamAuthInfo();
- const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
-
- await streamAgentEvents(streamUrl, headers, {
- json: options.json,
- verbose: options.verbose,
- });
+ const agentGatewayUrl = options.sse ? undefined : resolveAgentGatewayUrl();
+
+ if (agentGatewayUrl) {
+ const token = headers['Oidc-Auth'] || headers['X-API-Key'] || '';
+ await streamAgentEventsViaWebSocket({
+ gatewayUrl: agentGatewayUrl,
+ json: options.json,
+ operationId,
+ token,
+ verbose: options.verbose,
+ });
+ } else {
+ const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;
+ await streamAgentEvents(streamUrl, headers, {
+ json: options.json,
+ verbose: options.verbose,
+ });
+ }
},
);
diff --git a/apps/cli/src/constants/urls.ts b/apps/cli/src/constants/urls.ts
index f543f4a9230..f97718219d4 100644
--- a/apps/cli/src/constants/urls.ts
+++ b/apps/cli/src/constants/urls.ts
@@ -1,2 +1,3 @@
+export const OFFICIAL_AGENT_GATEWAY_URL = 'https://agent-gateway.lobehub.com';
export const OFFICIAL_SERVER_URL = 'https://app.lobehub.com';
export const OFFICIAL_GATEWAY_URL = 'https://device-gateway.lobehub.com';
diff --git a/apps/cli/src/settings/index.ts b/apps/cli/src/settings/index.ts
index 3cd78f4f90c..24c3f86040f 100644
--- a/apps/cli/src/settings/index.ts
+++ b/apps/cli/src/settings/index.ts
@@ -2,10 +2,11 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { OFFICIAL_SERVER_URL } from '../constants/urls';
+import { OFFICIAL_AGENT_GATEWAY_URL, OFFICIAL_SERVER_URL } from '../constants/urls';
import { log } from '../utils/logger';
export interface StoredSettings {
+ agentGatewayUrl?: string;
gatewayUrl?: string;
serverUrl?: string;
}
@@ -25,15 +26,24 @@ export function resolveServerUrl(): string {
return envServerUrl || settingsServerUrl || OFFICIAL_SERVER_URL;
}
+export function resolveAgentGatewayUrl(): string | undefined {
+ const envUrl = normalizeUrl(process.env.AGENT_GATEWAY_URL);
+ const settingsUrl = normalizeUrl(loadSettings()?.agentGatewayUrl);
+
+ return envUrl || settingsUrl || OFFICIAL_AGENT_GATEWAY_URL;
+}
+
export function saveSettings(settings: StoredSettings): void {
- const serverUrl = normalizeUrl(settings.serverUrl);
+ const agentGatewayUrl = normalizeUrl(settings.agentGatewayUrl);
const gatewayUrl = normalizeUrl(settings.gatewayUrl);
+ const serverUrl = normalizeUrl(settings.serverUrl);
const normalized: StoredSettings = {
+ agentGatewayUrl: agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL ? undefined : agentGatewayUrl,
gatewayUrl,
serverUrl: serverUrl === OFFICIAL_SERVER_URL ? undefined : serverUrl,
};
- if (!normalized.serverUrl && !normalized.gatewayUrl) {
+ if (!normalized.serverUrl && !normalized.gatewayUrl && !normalized.agentGatewayUrl) {
try {
fs.unlinkSync(SETTINGS_FILE);
} catch {}
@@ -50,14 +60,16 @@ export function loadSettings(): StoredSettings | null {
try {
const data = fs.readFileSync(SETTINGS_FILE, 'utf8');
const parsed = JSON.parse(data) as StoredSettings;
+ const agentGatewayUrl = normalizeUrl(parsed.agentGatewayUrl);
const gatewayUrl = normalizeUrl(parsed.gatewayUrl);
const serverUrl = normalizeUrl(parsed.serverUrl);
const normalized: StoredSettings = {
+ agentGatewayUrl: agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL ? undefined : agentGatewayUrl,
gatewayUrl,
serverUrl: serverUrl === OFFICIAL_SERVER_URL ? undefined : serverUrl,
};
- if (!normalized.serverUrl && !normalized.gatewayUrl) return null;
+ if (!normalized.serverUrl && !normalized.gatewayUrl && !normalized.agentGatewayUrl) return null;
return normalized;
} catch {
diff --git a/apps/cli/src/utils/agentStream.test.ts b/apps/cli/src/utils/agentStream.test.ts
index 0964ae7a809..f5596ddfb46 100644
--- a/apps/cli/src/utils/agentStream.test.ts
+++ b/apps/cli/src/utils/agentStream.test.ts
@@ -1,9 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { streamAgentEvents } from './agentStream';
+import { streamAgentEvents, streamAgentEventsViaWebSocket } from './agentStream';
vi.mock('./logger', () => ({
log: {
+ debug: vi.fn(),
error: vi.fn(),
heartbeat: vi.fn(),
info: vi.fn(),
@@ -193,3 +194,391 @@ describe('streamAgentEvents', () => {
exitSpy.mockRestore();
});
});
+
+// ── WebSocket stream tests ──────────────────────────────
+
+let capturedWs: MockWebSocket | undefined;
+
+class MockWebSocket {
+ static OPEN = 1;
+ static CONNECTING = 0;
+ static CLOSED = 3;
+
+ readyState = MockWebSocket.CONNECTING;
+ onopen: ((ev: any) => void) | null = null;
+ onmessage: ((ev: any) => void) | null = null;
+ onerror: ((ev: any) => void) | null = null;
+ onclose: ((ev: any) => void) | null = null;
+
+ sent: string[] = [];
+ private autoAuthSuccess = true;
+
+ constructor(
+ public url: string,
+ autoAuth = true,
+ ) {
+ this.autoAuthSuccess = autoAuth;
+ capturedWs = this; // eslint-disable-line @typescript-eslint/no-this-alias
+ // Trigger onopen on next microtask (after handlers are assigned)
+ queueMicrotask(() => {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.({ type: 'open' });
+ });
+ }
+
+ send(data: string) {
+ this.sent.push(data);
+ const msg = JSON.parse(data);
+
+ if (msg.type === 'auth' && this.autoAuthSuccess) {
+ queueMicrotask(() => {
+ this.onmessage?.({ data: JSON.stringify({ type: 'auth_success' }) });
+ });
+ }
+ }
+
+ close() {
+ this.readyState = MockWebSocket.CLOSED;
+ // Async like real WebSocket β€” fires after current microtask
+ queueMicrotask(() => this.onclose?.({ code: 1000, reason: '' }));
+ }
+
+ simulateMessage(msg: Record<string, unknown>) {
+ this.onmessage?.({ data: JSON.stringify(msg) });
+ }
+}
+
+describe('streamAgentEventsViaWebSocket', () => {
+ let stdoutSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ const originalWebSocket = globalThis.WebSocket;
+
+ beforeEach(() => {
+ capturedWs = undefined;
+ stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ (globalThis as any).WebSocket = MockWebSocket;
+ });
+
+ afterEach(() => {
+ stdoutSpy.mockRestore();
+ consoleSpy.mockRestore();
+ globalThis.WebSocket = originalWebSocket;
+ });
+
+ /** 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({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 'test-token',
+ });
+
+ await flush();
+
+ const ws = capturedWs!;
+ expect(ws.sent.map((s) => JSON.parse(s))).toEqual([
+ { token: 'test-token', type: 'auth' },
+ { lastEventId: '', type: 'resume' },
+ ]);
+
+ ws.simulateMessage({ id: '1', type: 'session_complete' });
+ await promise;
+ });
+
+ it('should render agent_event messages using existing renderEvent', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ 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',
+ });
+
+ await promise;
+ expect(stdoutSpy).toHaveBeenCalledWith('Hello WS!');
+ });
+
+ it('should output JSON when json option is set', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ 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',
+ });
+
+ await promise;
+
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"agent_runtime_init"'));
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"agent_runtime_end"'));
+ });
+
+ it('should reject on auth failure', async () => {
+ // Override mock to return auth_failed instead of auth_success
+ (globalThis as any).WebSocket = class extends MockWebSocket {
+ constructor(url: string) {
+ super(url, false); // disable auto auth_success
+ capturedWs = this; // eslint-disable-line @typescript-eslint/no-this-alias
+ }
+
+ override send(data: string) {
+ this.sent.push(data);
+ const msg = JSON.parse(data);
+ if (msg.type === 'auth') {
+ queueMicrotask(() => {
+ this.onmessage?.({
+ data: JSON.stringify({ reason: 'invalid token', type: 'auth_failed' }),
+ });
+ });
+ }
+ }
+ };
+
+ await expect(
+ streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 'bad-token',
+ }),
+ ).rejects.toThrow('Gateway auth failed');
+ });
+
+ it('should resolve on session_complete', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 'test-token',
+ });
+
+ await flush();
+ capturedWs!.simulateMessage({ id: '1', summary: 'All done', type: 'session_complete' });
+
+ await expect(promise).resolves.toBeUndefined();
+ });
+
+ it('should ignore heartbeat_ack messages', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ gatewayUrl: 'https://gw.test.com',
+ operationId: 'op-1',
+ token: 'test-token',
+ });
+
+ await flush();
+ const ws = capturedWs!;
+
+ ws.simulateMessage({ type: 'heartbeat_ack' });
+ expect(stdoutSpy).not.toHaveBeenCalled();
+
+ ws.simulateMessage({ id: '1', type: 'session_complete' });
+ await promise;
+ });
+
+ it('should construct correct WebSocket URL from HTTPS gateway URL', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ 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' });
+ await promise;
+ });
+
+ it('should render a multi-step agent run with tool calls', async () => {
+ const promise = streamAgentEventsViaWebSocket({
+ 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',
+ });
+
+ // 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',
+ },
+ id: '9',
+ type: 'agent_event',
+ });
+ 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',
+ });
+
+ await promise;
+
+ // Verify reasoning was rendered (dim)
+ expect(stdoutSpy).toHaveBeenCalledWith(expect.stringContaining('Let me search...'));
+ // Verify text chunks
+ expect(stdoutSpy).toHaveBeenCalledWith('Searching for news.');
+ expect(stdoutSpy).toHaveBeenCalledWith('Here are the results.');
+ // Verify tool call was logged
+ expect(log.toolCall).toHaveBeenCalledWith('search', 'tc-1', undefined);
+ // Verify tool result was logged
+ expect(log.toolResult).toHaveBeenCalled();
+ // Verify finish line
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Agent finished'));
+ });
+});
diff --git a/apps/cli/src/utils/agentStream.ts b/apps/cli/src/utils/agentStream.ts
index 1fe6f47a3f2..22aa4a9353f 100644
--- a/apps/cli/src/utils/agentStream.ts
+++ b/apps/cli/src/utils/agentStream.ts
@@ -1,4 +1,5 @@
import pc from 'picocolors';
+import urlJoin from 'url-join';
import { log } from './logger';
@@ -16,6 +17,12 @@ interface StreamOptions {
verbose?: boolean;
}
+interface WebSocketStreamOptions extends StreamOptions {
+ gatewayUrl: string;
+ operationId: string;
+ token: string;
+}
+
/**
* Connect to the agent SSE stream and render events to the terminal.
* Resolves when the stream ends (agent_runtime_end or connection close).
@@ -152,6 +159,126 @@ export function replayAgentEvents(events: AgentStreamEvent[], options: StreamOpt
}
}
+const HEARTBEAT_INTERVAL = 30_000;
+
+/**
+ * Connect to the Agent Gateway via WebSocket and render events to the terminal.
+ * Resolves when the session completes or the connection closes.
+ */
+export async function streamAgentEventsViaWebSocket(
+ options: WebSocketStreamOptions,
+): Promise<void> {
+ const { gatewayUrl, operationId, token, ...streamOpts } = options;
+ const wsUrl = urlJoin(
+ gatewayUrl.replace(/^http/, 'ws'),
+ `/ws?operationId=${encodeURIComponent(operationId)}`,
+ );
+
+ log.debug(`Connecting to gateway: ${wsUrl}`);
+
+ return new Promise<void>((resolve, reject) => {
+ const ws = new WebSocket(wsUrl);
+ const jsonEvents: AgentStreamEvent[] = [];
+ const ctx = createRenderContext();
+ let lastEventId = '';
+ let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
+ let jsonPrinted = false;
+
+ const cleanup = () => {
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
+ ws.close();
+ }
+ };
+
+ ws.onopen = () => {
+ ws.send(JSON.stringify({ token, type: 'auth' }));
+ };
+
+ ws.onmessage = (event) => {
+ const msg = JSON.parse(event.data as string);
+
+ 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);
+ return;
+ }
+
+ if (msg.type === 'auth_failed') {
+ cleanup();
+ reject(new Error(`Gateway auth failed: ${msg.reason}`));
+ return;
+ }
+
+ 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 (streamOpts.json && !jsonPrinted) {
+ jsonPrinted = true;
+ console.log(JSON.stringify(jsonEvents, null, 2));
+ } else if (!streamOpts.json) {
+ renderEnd(agentEvent);
+ }
+ cleanup();
+ resolve();
+ return;
+ }
+
+ if (agentEvent.type === 'error') {
+ if (streamOpts.json && !jsonPrinted) {
+ jsonPrinted = true;
+ console.log(JSON.stringify(jsonEvents, null, 2));
+ }
+ log.error(
+ `Agent error: ${agentEvent.data?.message || agentEvent.data?.error || 'Unknown error'}`,
+ );
+ cleanup();
+ process.exit(1);
+ }
+ }
+
+ if (msg.type === 'session_complete') {
+ if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
+ jsonPrinted = true;
+ console.log(JSON.stringify(jsonEvents, null, 2));
+ }
+ cleanup();
+ resolve();
+ }
+ };
+
+ ws.onerror = (err) => {
+ cleanup();
+ reject(err);
+ };
+
+ ws.onclose = () => {
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
+ if (streamOpts.json && jsonEvents.length > 0 && !jsonPrinted) {
+ jsonPrinted = true;
+ console.log(JSON.stringify(jsonEvents, null, 2));
+ }
+ resolve();
+ };
+ });
+}
+
// ── Render helpers ──────────────────────────────────────
interface RenderContext {