π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(cli): follow agent runs over the multiplexed gateway socket (/v2/ws) (#22048)
Arvin Xu77754caddd14
diff --git a/apps/cli/src/commands/agent/followRun.test.ts b/apps/cli/src/commands/agent/followRun.test.tsindex 80d4e547b19..3e6ed25559c 100644--- a/apps/cli/src/commands/agent/followRun.test.ts+++ b/apps/cli/src/commands/agent/followRun.test.ts@@ -1,24 +1,39 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { AgentGatewayUnavailableError, AgentStreamHistoryError } from '../../utils/agentStreamTransport';+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(),- };-});+const { getTrpcClient, globalConfigQuery, historyQuery, streamAgentEvents, userTokenQuery } =+ vi.hoisted(() => {+ const globalConfigQuery = vi.fn();+ const historyQuery = vi.fn();+ const userTokenQuery = vi.fn();+ return {+ getTrpcClient: vi.fn(async () => ({+ aiAgent: {+ getOperationStreamHistory: { query: historyQuery },+ issueGatewayUserToken: { query: userTokenQuery },+ },+ config: { getGlobalConfig: { query: globalConfigQuery } },+ })),+ globalConfigQuery,+ historyQuery,+ streamAgentEvents: vi.fn(),+ userTokenQuery,+ };+ });vi.mock('../../api/client', () => ({ getTrpcClient }));vi.mock('../../api/http', () => ({ getAgentStreamAuthInfo: vi.fn() }));-vi.mock('../../settings', () => ({ resolveAgentGatewayUrl: () => 'https://gateway.test' }));+vi.mock('../../settings', () => ({+ normalizeUrl: (url?: string) => (url ? url.replace(/\/$/, '') : undefined),+ resolveAgentGatewayUrl: () => 'https://gateway.test',+}));vi.mock('../../utils/agentStream', () => ({ streamAgentEvents }));-vi.mock('../../utils/logger', () => ({ log: { error: vi.fn() } }));+vi.mock('../../utils/logger', () => ({ log: { debug: vi.fn(), error: vi.fn() } }));describe('followAgentRun', () => {beforeEach(() => {@@ -29,6 +44,53 @@ describe('followAgentRun', () => {hasMore: false,nextCursor: '0',});+ globalConfigQuery.mockResolvedValue({+ serverConfig: { agentGatewayProtocol: 1, agentGatewayUrl: 'https://gateway.test' },+ });+ streamAgentEvents.mockResolvedValue({ kind: 'completed', status: 'done' });+ });++ describe('gateway protocol', () => {+ const streamedWith = () => streamAgentEvents.mock.calls[0][0];++ it('follows over /v2/ws, minting a user token per dial, when the server Gateway serves protocol 2', async () => {+ globalConfigQuery.mockResolvedValue({+ serverConfig: { agentGatewayProtocol: 2, agentGatewayUrl: 'https://gateway.test/' },+ });+ userTokenQuery+ .mockResolvedValueOnce({ token: 'jwt-1' })+ .mockResolvedValueOnce({ token: 'jwt-2' });++ await followAgentRun('op-1');++ const { getGatewayUserToken } = streamedWith();+ await expect(getGatewayUserToken()).resolves.toBe('jwt-1');+ await expect(getGatewayUserToken()).resolves.toBe('jwt-2');+ });++ it('stays on /ws for a protocol-1 (self-hosted) Gateway', async () => {+ await followAgentRun('op-1');++ expect(streamedWith().getGatewayUserToken).toBeUndefined();+ });++ it('stays on /ws when the CLI points at a different Gateway than the server advertises', async () => {+ globalConfigQuery.mockResolvedValue({+ serverConfig: { agentGatewayProtocol: 2, agentGatewayUrl: 'https://other-gateway.test' },+ });++ await followAgentRun('op-1');++ expect(streamedWith().getGatewayUserToken).toBeUndefined();+ });++ it('stays on /ws when the capability lookup fails', async () => {+ globalConfigQuery.mockRejectedValue(new Error('fetch failed'));++ await followAgentRun('op-1');++ expect(streamedWith().getGatewayUserToken).toBeUndefined();+ });});it('reads history pages through the credential-refreshing tRPC client', async () => {diff --git a/apps/cli/src/commands/agent/followRun.ts b/apps/cli/src/commands/agent/followRun.tsindex 6d51d4f7bb3..4a849a1ff6a 100644--- a/apps/cli/src/commands/agent/followRun.ts+++ b/apps/cli/src/commands/agent/followRun.ts@@ -9,6 +9,7 @@ import {AgentStreamHistoryError,} from '../../utils/agentStreamTransport';import { log } from '../../utils/logger';+import { supportsGatewayProtocolV2 } from './gatewayProtocol';interface FollowAgentRunOptions {json?: boolean;@@ -41,20 +42,27 @@ export const followAgentRun = async (const gatewayUrl = resolveAgentGatewayUrl();if (!gatewayUrl) throw new Error('Agent gateway URL is not configured');+ // Protocol 2 when the server's Gateway has it: one per-user socket, minted+ // per dial. Followed without `clientProtocol: 2` on purpose β the CLI renders+ // the journal's message snapshots, not the web's message patches.+ const getGatewayUserToken = (await supportsGatewayProtocolV2(await getTrpcClient(), gatewayUrl))+ ? async () => (await (await getTrpcClient()).aiAgent.issueGatewayUserToken.query()).token+ : undefined;+try {const outcome = await streamAgentEvents({...options,gatewayUrl,getAuth: () => resolveAgentStreamAuthInfo(),+ getGatewayUserToken,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 },- );+ 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.diff --git a/apps/cli/src/commands/agent/gatewayProtocol.ts b/apps/cli/src/commands/agent/gatewayProtocol.tsnew file mode 100644index 00000000000..3673f4b0851--- /dev/null+++ b/apps/cli/src/commands/agent/gatewayProtocol.ts@@ -0,0 +1,35 @@+import type { TrpcClient } from '../../api/client';+import { normalizeUrl } from '../../settings';+import { formatError } from '../../utils/error';+import { log } from '../../utils/logger';++/** Bounds the capability lookup so it never holds up following the run. */+const LOOKUP_TIMEOUT_MS = 5000;++/**+ * Whether the multiplexed `/v2/ws` socket can be dialed on `gatewayUrl`.+ *+ * The server publishes which protocol its Gateway serves+ * (`serverConfig.agentGatewayProtocol`); a self-hosted Gateway only has `/ws`,+ * and there is no negotiation on the socket. The answer only describes the+ * server's own Gateway, so a CLI pointed at a different one stays on `/ws`.+ * Anything short of a clear "2" β an older server, a failed lookup β is+ * protocol 1, which every Gateway serves.+ */+export const supportsGatewayProtocolV2 = async (+ client: TrpcClient,+ gatewayUrl: string,+): Promise<boolean> => {+ try {+ const config = await client.config.getGlobalConfig.query(undefined, {+ signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),+ });+ const { agentGatewayProtocol, agentGatewayUrl } = config.serverConfig;+ if (agentGatewayProtocol !== 2) return false;++ return !agentGatewayUrl || normalizeUrl(agentGatewayUrl) === normalizeUrl(gatewayUrl);+ } catch (error) {+ log.debug(`Agent gateway protocol lookup failed, using /ws: ${formatError(error)}`);+ return false;+ }+};diff --git a/apps/cli/src/utils/agentStreamTransport.mux.test.ts b/apps/cli/src/utils/agentStreamTransport.mux.test.tsnew file mode 100644index 00000000000..c5f20672613--- /dev/null+++ b/apps/cli/src/utils/agentStreamTransport.mux.test.ts@@ -0,0 +1,334 @@+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, consumeAgentStream } from './agentStreamTransport';++/**+ * Speaks both Gateway protocols: `/v2/ws` behaves like the per-user hub+ * (`ready`, then `subscribe` β `resume_complete`), `/ws` like the per-operation+ * socket (`auth` β `auth_success`). `failDial` makes `/v2/ws` close before+ * `ready`, the way a Gateway without it answers.+ */+let sockets: TestSocket[];+let failDial: number | undefined;+/** `/v2/ws` opens but the hub never sends `ready`, like a half-open proxy. */+let silentReady: boolean;+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: Array<Record<string, any>> = [];+ constructor(public url: string) {+ sockets.push(this);+ queueMicrotask(() => {+ if (this.isMux && failDial !== undefined) {+ this.disconnect(failDial);+ return;+ }+ this.readyState = 1;+ this.onopen?.();+ if (this.isMux && !silentReady)+ this.message({ connectionId: 'conn-1', protocol: 2, type: 'ready', userId: 'user-1' });+ });+ }+ get isMux() {+ return this.url.includes('/v2/ws');+ }+ send(data: string) {+ const message = JSON.parse(data);+ this.sent.push(message);+ if (message.type === 'auth') queueMicrotask(() => this.message({ type: 'auth_success' }));+ if (message.type === 'subscribe')+ queueMicrotask(() =>+ this.message({+ gap: false,+ operationId: message.operationId,+ status: 'running',+ type: 'resume_complete',+ }),+ );+ }+ message(message: unknown) {+ this.onmessage?.({ data: JSON.stringify(message) });+ }+ close() {+ this.readyState = 3;+ }+ disconnect(code = 1011) {+ this.readyState = 3;+ this.onclose?.({ code, reason: 'disconnected' });+ }+}++const muxSockets = () => sockets.filter((socket) => socket.isMux);+const v1Sockets = () => sockets.filter((socket) => !socket.isMux);++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,+});++/** A hub frame for this run; the hub omits `event.operationId` when it repeats the envelope. */+const frame = (seq: number, agentEvent: Partial<AgentStreamEvent>) => ({+ event: agentEvent,+ id: String(seq),+ operationId: 'op-1',+ type: 'agent_event',+});++describe('protocol v2 (/v2/ws) wake channel', () => {+ let journal: JournalEvent[];+ let readHistory: ReturnType<+ typeof vi.fn<(cursor: string, signal: AbortSignal) => Promise<AgentHistoryPage>>+ >;+ let getGatewayUserToken: ReturnType<typeof vi.fn<() => Promise<string>>>;+ let consoleLog: ReturnType<typeof vi.spyOn>;+ const flush = () => vi.advanceTimersByTimeAsync(0);+ const options = () => ({+ gatewayUrl: 'https://gateway.test',+ getAuth: async () => ({+ serverUrl: 'https://server.test',+ token: 'cli-credential',+ tokenType: 'apiKey' as const,+ }),+ getGatewayUserToken,+ operationId: 'op-1',+ readHistory,+ });++ beforeEach(() => {+ vi.useFakeTimers();+ sockets = [];+ failDial = undefined;+ silentReady = false;+ journal = [event(1, 'agent_runtime_init')];+ readHistory = vi.fn(async (cursor) => {+ 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 };+ });+ getGatewayUserToken = vi.fn(async () => 'user-jwt');+ vi.stubGlobal('WebSocket', TestSocket);+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ consoleLog = vi.spyOn(console, 'log').mockImplementation(() => {});+ });+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it('follows the run over one subscription on /v2/ws with a minted user token, never dialing /ws', async () => {+ const done = streamAgentEvents({ ...options(), json: true });+ await flush();++ expect(muxSockets()).toHaveLength(1);+ expect(muxSockets()[0].url).toMatch(/^wss:\/\/gateway\.test\/v2\/ws\?token=user-jwt&clientId=/);+ // Not an executor and no cursor on a fresh run.+ expect(muxSockets()[0].sent).toContainEqual({ operationId: 'op-1', type: 'subscribe' });++ journal.push(event(2, 'stream_chunk', 'hello'));+ muxSockets()[0].message(frame(1, { data: { content: 'hello' }, type: 'stream_chunk' }));+ await flush();+ journal.push(event(3, 'agent_runtime_end'));+ muxSockets()[0].message(frame(2, { data: { reason: 'done' }, type: 'agent_runtime_end' }));+ await flush();++ await expect(done).resolves.toMatchObject({ kind: 'completed' });+ const printed = JSON.parse(String(consoleLog.mock.calls[0][0])) as AgentStreamEvent[];+ expect(printed.map((item) => item.type)).toEqual([+ 'agent_runtime_init',+ 'stream_chunk',+ 'agent_runtime_end',+ ]);+ expect(v1Sockets()).toHaveLength(0);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('renders group member events mirrored onto the supervisor subscription, and a member end is not terminal', async () => {+ const done = streamAgentEvents({ ...options(), json: true });+ await flush();++ const memberChunk = { ...event(3, 'stream_chunk', 'member'), operationId: 'op-member-2' };+ muxSockets()[0].message(frame(1, memberChunk));+ await flush();+ // A replay of the same hub frame after a resubscribe must not render twice.+ muxSockets()[0].message(frame(1, memberChunk));+ await flush();+ const memberEnd = { ...event(4, 'member_runtime_end'), operationId: 'op-member-2' };+ muxSockets()[0].message(frame(2, memberEnd));+ await flush();++ journal.push(event(5, 'agent_runtime_end'));+ muxSockets()[0].message({ id: '3', operationId: 'op-1', type: 'session_complete' });+ await flush();++ await expect(done).resolves.toMatchObject({ kind: 'completed' });+ const printed = JSON.parse(String(consoleLog.mock.calls[0][0])) as AgentStreamEvent[];+ expect(+ printed.filter((item) => item.operationId === 'op-member-2').map((item) => item.type),+ ).toEqual(['stream_chunk', 'member_runtime_end']);+ expect(printed.at(-1)?.type).toBe('agent_runtime_end');+ });++ it('resubscribes from the last hub event after a dropped socket and recovers missed output exactly once', async () => {+ const seen: AgentStreamEvent[] = [];+ const transport = consumeAgentStream(options(), (item) => {+ seen.push(item);+ return item.type === 'agent_runtime_end';+ });+ await flush();++ journal.push(event(2, 'stream_chunk', 'a'));+ muxSockets()[0].message(frame(7, { type: 'stream_chunk' }));+ await flush();+ muxSockets()[0].disconnect();+ journal.push(event(3, 'stream_chunk', 'b'), event(4, 'agent_runtime_end'));+ await vi.advanceTimersByTimeAsync(1000);++ await expect(transport.done).resolves.toBeUndefined();+ expect(muxSockets()).toHaveLength(2);+ expect(muxSockets()[1].sent).toContainEqual({+ lastEventId: '7',+ operationId: 'op-1',+ type: 'subscribe',+ });+ expect(getGatewayUserToken).toHaveBeenCalledTimes(2);+ expect(seen.map((item) => item.id)).toEqual(['1-0', '2-0', '3-0', '4-0']);+ });++ it('moves to /ws at once when the server refuses to mint a user token (restricted API key)', async () => {+ getGatewayUserToken.mockRejectedValue(+ Object.assign(new Error('FORBIDDEN'), { data: { code: 'FORBIDDEN' } }),+ );+ const transport = consumeAgentStream(options(), (item) => item.type === 'agent_runtime_end');+ await flush();+ await flush();++ expect(muxSockets()).toHaveLength(0);+ expect(v1Sockets()).toHaveLength(1);+ expect(v1Sockets()[0].url).toBe('wss://gateway.test/ws?operationId=op-1');+ expect(v1Sockets()[0].sent[0]).toEqual({+ serverUrl: 'https://server.test',+ token: 'cli-credential',+ tokenType: 'apiKey',+ type: 'auth',+ });++ journal.push(event(2, 'agent_runtime_end'));+ v1Sockets()[0].message({ type: 'session_complete' });+ await flush();+ await expect(transport.done).resolves.toBeUndefined();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('moves to /ws when /v2/ws never reaches ready (a Gateway without protocol 2)', async () => {+ failDial = 1006;+ const transport = consumeAgentStream(options(), (item) => item.type === 'agent_runtime_end');+ await vi.advanceTimersByTimeAsync(10_000);++ expect(muxSockets()).toHaveLength(3);+ expect(v1Sockets()).toHaveLength(1);+ // Nothing was received on /v2/ws, so /ws resumes from the start.+ expect(v1Sockets()[0].sent).toContainEqual({ lastEventId: '', type: 'resume' });++ journal.push(event(2, 'agent_runtime_end'));+ v1Sockets()[0].message({ type: 'session_complete' });+ await flush();+ await expect(transport.done).resolves.toBeUndefined();+ });++ it('hands a run over to /ws from the last hub event once the hub keeps refusing the token', async () => {+ const transport = consumeAgentStream(options(), (item) => item.type === 'agent_runtime_end');+ await flush();+ muxSockets()[0].message(frame(9, { type: 'stream_chunk' }));+ await flush();++ // From here on every dial is refused with 4401: three in a row exhaust the+ // mux's auth budget even though the socket worked before.+ failDial = 4401;+ muxSockets()[0].disconnect(4401);+ await vi.advanceTimersByTimeAsync(1000);++ expect(muxSockets()).toHaveLength(3);+ expect(v1Sockets()).toHaveLength(1);+ expect(v1Sockets()[0].sent).toContainEqual({ lastEventId: '9', type: 'resume' });++ journal.push(event(2, 'agent_runtime_end'));+ v1Sockets()[0].message({ type: 'session_complete' });+ await flush();+ await expect(transport.done).resolves.toBeUndefined();+ });++ it('rejects as a gateway failure when the hub refuses this operation to the user', async () => {+ const transport = consumeAgentStream(options(), () => false);+ const rejected = expect(transport.done).rejects.toBeInstanceOf(AgentGatewayUnavailableError);+ await flush();++ muxSockets()[0].message({ operationId: 'op-1', reason: 'forbidden', type: 'subscribe_failed' });+ await flush();++ await rejected;+ expect(v1Sockets()).toHaveLength(0);+ });++ it('stops after the retry budget once a working /v2/ws stays away, so the caller can poll', async () => {+ const transport = consumeAgentStream({ ...options(), maxRetries: 2 }, () => false);+ const rejected = expect(transport.done).rejects.toThrow(/Reconnect attempts exhausted/);+ await flush();++ // The socket worked, so later failed dials are an outage, not missing support.+ failDial = 1006;+ muxSockets()[0].disconnect();+ await vi.advanceTimersByTimeAsync(60_000);++ await rejected;+ await expect(transport.done).rejects.toBeInstanceOf(AgentGatewayUnavailableError);+ expect(v1Sockets()).toHaveLength(0);+ });++ it('moves to /ws when /v2/ws opens but never sends ready, instead of waiting forever', async () => {+ silentReady = true;+ const transport = consumeAgentStream(options(), (item) => item.type === 'agent_runtime_end');++ // Three dials, each abandoned after the 10s connect deadline, plus backoff.+ await vi.advanceTimersByTimeAsync(40_000);++ expect(muxSockets()).toHaveLength(3);+ expect(muxSockets().every((socket) => socket.readyState === 3)).toBe(true);+ expect(v1Sockets()).toHaveLength(1);++ journal.push(event(2, 'agent_runtime_end'));+ v1Sockets()[0].message({ type: 'session_complete' });+ await flush();+ await expect(transport.done).resolves.toBeUndefined();+ });++ it('leaves no reconnect timer behind once the retry budget ends the stream', async () => {+ // A reconnect delay that a zero-time flush cannot fire.+ vi.spyOn(Math, 'random').mockReturnValue(0.99);+ const transport = consumeAgentStream({ ...options(), maxRetries: 0 }, () => false);+ const rejected = expect(transport.done).rejects.toBeInstanceOf(AgentGatewayUnavailableError);+ await flush();++ muxSockets()[0].disconnect();+ await flush();++ await rejected;+ // A live timer here would keep `lh agent run` alive after it fell back to polling.+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/apps/cli/src/utils/agentStreamTransport.ts b/apps/cli/src/utils/agentStreamTransport.tsindex 85abd3ea289..c88cc9c86fa 100644--- a/apps/cli/src/utils/agentStreamTransport.ts+++ b/apps/cli/src/utils/agentStreamTransport.ts@@ -1,4 +1,5 @@-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { AgentStreamEvent, OperationSubscription } from '@lobechat/agent-gateway-client';+import { GatewayMuxClient } from '@lobechat/agent-gateway-client';import urlJoin from 'url-join';import { log } from './logger';@@ -25,6 +26,13 @@ export interface AgentStreamTransportOptions {gatewayUrl: string;/** Called for every (re)connect so a long run picks up refreshed credentials. */getAuth: () => Promise<AgentStreamAuth>;+ /**+ * Mints a user JWT for the multiplexed `/v2/ws` socket, called before every+ * dial. Pass it only when the server advertises protocol 2 for this Gateway;+ * without it the run is followed over the per-operation `/ws` socket, which+ * is all a self-hosted Gateway serves.+ */+ getGatewayUserToken?: () => Promise<string>;maxRetries?: number;/*** Stream events the Gateway delivers for another operation on this socket β a@@ -90,6 +98,12 @@ const HISTORY_REQUEST_TIMEOUT_MS = 10_000;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;+/**+ * Dials of `/v2/ws` that never reach `ready` before the run moves to `/ws`. A+ * deployment advertising protocol 2 in front of a Gateway without it (404) or a+ * hub that keeps refusing the token gets the same bounded probe the web uses.+ */+const MUX_MAX_DIAL_FAILURES = 3;const FATAL_TRPC_CODES = new Set(['UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND']);const REDIS_ID = /^\d+-\d+$/;@@ -214,12 +228,40 @@ class AgentEventJournal {}}+/** Wake-up source for the journal: either Gateway protocol, same contract. */+interface WakeChannel {+ close: () => void;+ connect: () => void;+ /** Real progress proves the run is reachable, so the reconnect budget starts over. */+ resetRetries: () => void;+}++type WakeChannelOptions = AgentStreamTransportOptions & { maxRetries: number };+/**- * Gateway WebSocket used purely as a wake-up signal: every notification asks- * the journal to catch up. Owns auth, heartbeat and bounded reconnects.+ * Whether a frame is a group member's event mirrored onto this operation's+ * channel. A member's events ride the supervisor's channel, 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.*/-class GatewayWakeChannel {- private gatewayCursor = '';+const isMirroredEvent = (+ operationId: string,+ event?: AgentStreamEvent,+): event is AgentStreamEvent =>+ // Legacy gateways omit `operationId`; those events are this op's, and the+ // journal already covers them.+ !!event?.operationId && event.operationId !== operationId;++/**+ * Per-operation Gateway WebSocket (`/ws`, protocol 1) used purely as a wake-up+ * signal: every notification asks the journal to catch up. Owns auth,+ * heartbeat and bounded reconnects.+ */+class GatewayWakeChannel implements WakeChannel {private heartbeat?: ReturnType<typeof setInterval>;private heartbeatPending = false;private connectTimer?: ReturnType<typeof setTimeout>;@@ -230,13 +272,18 @@ class GatewayWakeChannel {private ws?: WebSocket;constructor(- private readonly options: AgentStreamTransportOptions & { maxRetries: number },+ private readonly options: WakeChannelOptions,/** `immediate` skips the coalescing window (terminal / reconnect wakes). */private readonly onWake: (immediate?: boolean) => void,private readonly onFatal: (error: Error) => void,+ /**+ * Gateway event id to resume after. Both protocols number an operation's+ * events from the same sequence, so a run handed over from `/v2/ws` resumes+ * where it left off instead of replaying mirrored member frames.+ */+ private gatewayCursor = '',) {}- /** Real progress proves the run is reachable, so the reconnect budget starts over. */resetRetries() {this.retries = 0;}@@ -320,6 +367,7 @@ class GatewayWakeChannel {return;}case 'auth_success': {+ log.debug('Agent gateway: following the run over /ws');clearTimeout(this.connectTimer);socket.send(JSON.stringify({ lastEventId: this.gatewayCursor, type: 'resume' }));this.startHeartbeat(socket);@@ -346,22 +394,11 @@ class GatewayWakeChannel {}}- /**- * 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.- */+ /** See {@link isMirroredEvent}. */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;+ if (!deliver || !isMirroredEvent(this.options.operationId, mirrored)) return;// A reconnect resumes from `gatewayCursor`, so the same mirrored frame can// legitimately arrive twice.if (message.id) {@@ -421,6 +458,143 @@ class GatewayWakeChannel {}}+/** A tRPC refusal that no retry can turn into a token (restricted key, old server). */+const isPermanentMintFailure = (error: unknown) =>+ FATAL_TRPC_CODES.has((error as { data?: { code?: string } })?.data?.code ?? '');++/**+ * The run's subscription on the per-user multiplexed socket (`/v2/ws`,+ * protocol 2), again used purely as a wake-up signal.+ *+ * Owns the CLI's retry budget on top of the mux's own backoff: the mux retries+ * a lost socket forever once it has worked, but a run whose Gateway stays away+ * must reach the caller as `AgentGatewayUnavailableError` so it can poll.+ *+ * When protocol 2 turns out to be unusable here β the dials never reach+ * `ready`, the hub keeps refusing the token, or the token cannot be minted at+ * all β the run moves to `/ws`, which authenticates on its own and resumes+ * from the same event id.+ */+class MuxWakeChannel implements WakeChannel {+ private fallback?: WakeChannel;+ private mux?: GatewayMuxClient;+ private offs: Array<() => void> = [];+ private retries = 0;+ private stopped = false;+ private subscription?: OperationSubscription;++ constructor(+ private readonly options: WakeChannelOptions,+ private readonly getToken: () => Promise<string>,+ private readonly onWake: (immediate?: boolean) => void,+ private readonly onFatal: (error: Error) => void,+ private readonly createFallback: (gatewayCursor: string) => WakeChannel,+ ) {}++ resetRetries() {+ this.retries = 0;+ this.fallback?.resetRetries();+ }++ connect() {+ if (this.stopped) return;+ const mux = new GatewayMuxClient({+ // Same per-attempt bound as `/ws`: a token mint that hangs or a socket+ // that never gets `ready` is a failed dial, retried and counted toward+ // the fallback β mirrored member events only ever arrive on this wire.+ connectTimeoutMs: CONNECT_TIMEOUT_MS,+ gatewayUrl: this.options.gatewayUrl,+ getToken: this.mintToken,+ maxDialFailures: MUX_MAX_DIAL_FAILURES,+ });+ this.mux = mux;+ this.offs.push(mux.on('unavailable', (reason) => this.fallBack(reason)));++ // Not an executor: the CLI runs no client-side tools for this operation.+ const subscription = mux.subscribe(this.options.operationId);+ this.subscription = subscription;+ this.offs.push(+ // Sent on every (re)subscribe; the hub replays newer events right after.+ subscription.on('connected', () => {+ log.debug('Agent gateway: following the run over /v2/ws');+ this.onWake(true);+ }),+ subscription.on('agent_event', (event) => {+ if (this.options.onMirroredEvent && isMirroredEvent(this.options.operationId, event))+ this.options.onMirroredEvent(event);+ this.onWake();+ }),+ // Not a success signal: only a terminal event in the journal ends the run.+ subscription.on('session_complete', () => this.onWake(true)),+ subscription.on('reconnecting', (delay) => this.reconnecting(delay)),+ // The hub refused this operation to this user: retrying cannot help, but+ // the journal and the status endpoint may still answer.+ subscription.on('auth_failed', (reason) =>+ this.onFatal(new AgentGatewayUnavailableError(`Gateway auth failed: ${reason}`)),+ ),+ );+ }++ close() {+ this.stopped = true;+ this.closeMux();+ this.fallback?.close();+ }++ private mintToken = async () => {+ try {+ return await this.getToken();+ } catch (error) {+ // No retry turns this into a token; `/ws` authenticates with the CLI's+ // own credential instead. Deferred: the mux is still inside its dial.+ if (isPermanentMintFailure(error))+ queueMicrotask(() => this.fallBack(`gateway token refused: ${toError(error).message}`));+ throw error;+ }+ };++ private reconnecting(delay: number) {+ if (this.stopped) return;+ // Recover the terminal from the server even when the Gateway is down.+ this.onWake(true);+ if (++this.retries > this.options.maxRetries) {+ // Deferred: the mux announces `reconnecting` before it arms the timer,+ // so shutting it down from inside the notification would leave that+ // timer live and hold the process open after the caller moved to polling.+ queueMicrotask(() =>+ this.onFatal(+ new AgentGatewayUnavailableError(+ 'Reconnect attempts exhausted; complete history not confirmed: agent gateway (/v2/ws) unreachable',+ ),+ ),+ );+ return;+ }+ log.debug(+ `Agent gateway (/v2/ws) reconnect ${this.retries}/${this.options.maxRetries} in ${delay}ms`,+ );+ }++ private fallBack(reason: string) {+ if (this.stopped || this.fallback) return;+ log.debug(`Agent gateway protocol v2 unavailable (${reason}); following the run over /ws`);+ const gatewayCursor = this.subscription?.lastEventId ?? '';+ this.closeMux();+ this.retries = 0;+ this.fallback = this.createFallback(gatewayCursor);+ this.fallback.connect();+ }++ private closeMux() {+ for (const off of this.offs) off();+ this.offs = [];+ this.subscription?.unsubscribe();+ this.subscription = undefined;+ this.mux?.disconnect();+ this.mux = 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),@@ -537,11 +711,22 @@ export const consumeAgentStream = (wake();}, WAKE_COALESCE_WINDOW_MS);};- const gateway = new GatewayWakeChannel(- { ...resolved, onMirroredEvent: resolved.onMirroredEvent ? deliverMirrored : undefined },- wake,- (error) => fail(error),- );+ const channelOptions: WakeChannelOptions = {+ ...resolved,+ onMirroredEvent: resolved.onMirroredEvent ? deliverMirrored : undefined,+ };+ const onFatal = (error: Error) => fail(error);+ const createV1Channel = (gatewayCursor?: string) =>+ new GatewayWakeChannel(channelOptions, wake, onFatal, gatewayCursor);+ const gateway: WakeChannel = resolved.getGatewayUserToken+ ? new MuxWakeChannel(+ channelOptions,+ resolved.getGatewayUserToken,+ wake,+ onFatal,+ createV1Channel,+ )+ : createV1Channel();const poll = setInterval(() => void runCatchUp(), HISTORY_POLL_INTERVAL_MS);const close = () => {diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.connectTimeout.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.connectTimeout.test.tsnew file mode 100644index 00000000000..d16116768be--- /dev/null+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.connectTimeout.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { GatewayMuxClient } from './GatewayMuxClient';+import type { GatewayMuxClientOptions } from './types';++/** Opens on the next tick and then stays silent: the hub never sends `ready`. */+class SilentSocket {+ static CONNECTING = 0;+ static OPEN = 1;+ static CLOSING = 2;+ static CLOSED = 3;++ readyState = SilentSocket.CONNECTING;+ onopen: ((ev: unknown) => void) | null = null;+ onmessage: ((ev: unknown) => void) | null = null;+ onclose: ((ev: unknown) => void) | null = null;+ onerror: ((ev: unknown) => void) | null = null;+ closed = false;++ constructor(public url: string) {+ sockets.push(this);+ setTimeout(() => {+ this.readyState = SilentSocket.OPEN;+ this.onopen?.({});+ }, 0);+ }++ send(): void {}++ close(): void {+ this.closed = true;+ this.readyState = SilentSocket.CLOSED;+ this.onclose?.({ code: 1000, reason: '' });+ }+}++let sockets: SilentSocket[];+let muxes: GatewayMuxClient[];++const createMux = (overrides?: Partial<GatewayMuxClientOptions>) => {+ const mux = new GatewayMuxClient({+ clientId: 'cid',+ gatewayUrl: 'https://gateway.test.com',+ getToken: async () => 'tok',+ ...overrides,+ });+ muxes.push(mux);+ mux.on('error', () => {});+ return mux;+};++beforeEach(() => {+ sockets = [];+ muxes = [];+ vi.stubGlobal('WebSocket', SilentSocket);+ vi.useFakeTimers();+ vi.spyOn(Math, 'random').mockReturnValue(0.5);+});++afterEach(() => {+ for (const mux of muxes) mux.disconnect();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('GatewayMuxClient connectTimeoutMs', () => {+ it('abandons a socket that opens but never gets ready and dials again', async () => {+ const mux = createMux({ connectTimeoutMs: 5000 });+ mux.subscribe('op-1');+ await vi.advanceTimersByTimeAsync(1);+ expect(sockets).toHaveLength(1);++ await vi.advanceTimersByTimeAsync(5000);+ expect(sockets[0].closed).toBe(true);++ // First backoff: 0.5 * 1000ms cap.+ await vi.advanceTimersByTimeAsync(501);+ expect(sockets).toHaveLength(2);+ });++ it('counts a getToken that never settles as a failed dial toward unavailable', async () => {+ const mux = createMux({+ connectTimeoutMs: 5000,+ getToken: () => new Promise<string>(() => {}),+ maxDialFailures: 1,+ });+ const onUnavailable = vi.fn();+ mux.on('unavailable', onUnavailable);+ mux.subscribe('op-1');++ await vi.advanceTimersByTimeAsync(5000);++ expect(onUnavailable).toHaveBeenCalledOnce();+ expect(sockets).toHaveLength(0);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('falls back after maxDialFailures attempts that each time out waiting for ready', async () => {+ const mux = createMux({ connectTimeoutMs: 5000 });+ const onUnavailable = vi.fn();+ mux.on('unavailable', onUnavailable);+ mux.subscribe('op-1');++ await vi.advanceTimersByTimeAsync(30_000);++ expect(sockets).toHaveLength(3);+ expect(onUnavailable).toHaveBeenCalledOnce();+ });++ it('keeps waiting for ready without the option (the web default)', async () => {+ const mux = createMux();+ mux.subscribe('op-1');++ await vi.advanceTimersByTimeAsync(60_000);++ expect(sockets).toHaveLength(1);+ expect(sockets[0].closed).toBe(false);+ });+});diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.tsindex a2237591979..ac7fad0dba1 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts@@ -362,6 +362,7 @@ export class GatewayMuxClient {private connectGeneration = 0;private connectInFlight = false;private connectWaiters: Array<{ reject: (error: Error) => void; resolve: () => void }> = [];+ private connectDeadlineTimer: ReturnType<typeof setTimeout> | null = null;private heartbeatTimer: ReturnType<typeof setInterval> | null = null;private missedHeartbeats = 0;@@ -389,6 +390,7 @@ export class GatewayMuxClient {private readonly getToken: () => Promise<string>;private readonly clientId: string;private readonly autoReconnect: boolean;+ private readonly connectTimeoutMs?: number;private readonly heartbeatIntervalMs: number;private readonly keepAlive: boolean;private readonly maxDialFailures: number;@@ -398,6 +400,7 @@ export class GatewayMuxClient {this.getToken = options.getToken;this.clientId = options.clientId ?? randomClientId();this.autoReconnect = options.autoReconnect ?? true;+ this.connectTimeoutMs = options.connectTimeoutMs;this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL;this.keepAlive = options.keepAlive ?? false;this.maxDialFailures = options.maxDialFailures ?? MAX_CONSECUTIVE_DIAL_FAILURES;@@ -602,6 +605,7 @@ export class GatewayMuxClient {// serve v2" case the budget exists for. Left set from the previous socket,// those attempts would never count and the page would retry forever.this.currentDialReachedReady = false;+ this.armConnectDeadline(generation);let token: string;try {@@ -632,6 +636,37 @@ export class GatewayMuxClient {}}+ /** See `GatewayMuxClientOptions.connectTimeoutMs`. */+ private armConnectDeadline(generation: number): void {+ this.clearConnectDeadline();+ if (!this.connectTimeoutMs) return;+ this.connectDeadlineTimer = setTimeout(() => {+ this.connectDeadlineTimer = null;+ if (generation !== this.connectGeneration || this.currentDialReachedReady) return;+ const awaitingToken = this.connectInFlight;+ // Supersede the attempt: a token that still arrives is dropped.+ this.connectGeneration++;+ this.connectInFlight = false;+ this.closeWebSocket();+ this.listeners.emit(+ 'error',+ new Error(+ awaitingToken+ ? 'Timed out obtaining gateway token'+ : 'Timed out waiting for the gateway to get ready',+ ),+ );+ this.handleConnectionLost(undefined, awaitingToken);+ }, this.connectTimeoutMs);+ }++ private clearConnectDeadline(): void {+ if (this.connectDeadlineTimer) {+ clearTimeout(this.connectDeadlineTimer);+ this.connectDeadlineTimer = null;+ }+ }+private buildWsUrl(token: string): string {const query = `token=${encodeURIComponent(token)}&clientId=${encodeURIComponent(this.clientId)}`;// If the URL already has a ws/wss protocol, use it directly@@ -657,6 +692,7 @@ export class GatewayMuxClient {switch (message.type) {case 'ready': {+ this.clearConnectDeadline();this.reconnectAttempt = 0;this.consecutiveAuthFailures = 0;this.consecutiveDialFailures = 0;@@ -745,6 +781,7 @@ export class GatewayMuxClient {};private handleConnectionLost(delayOverride?: number, tokenFailed = false): void {+ this.clearConnectDeadline();// Once v2 has worked, failed network dials indicate an outage, not missing// protocol support. Keep backing off so a Gateway restart can recover.// Token minting still has a finite budget: the API may have been removed,@@ -986,6 +1023,7 @@ export class GatewayMuxClient {}private cleanup(): void {+ this.clearConnectDeadline();this.clearIdleClose();this.stopHeartbeat();this.clearReconnectTimer();diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.tsindex 8279e9561aa..19d30f19097 100644--- a/packages/agent-gateway-client/src/mux/types.ts+++ b/packages/agent-gateway-client/src/mux/types.ts@@ -231,6 +231,14 @@ export interface GatewayMuxClientOptions {autoReconnect?: boolean;/** Stable id for this tab; the hub tags the connection with it. Random when omitted. */clientId?: string;+ /**+ * Deadline for one dial, from minting the token to the hub's `ready`+ * (default: none). An attempt that misses it β a `getToken` that never+ * settles, a socket that opens but never gets `ready` β is abandoned and+ * handled like a lost connection: it counts toward `maxDialFailures` while+ * protocol v2 has not worked yet, and is redialed with backoff.+ */+ connectTimeoutMs?: number;/** Gateway URL base (e.g. https://gateway.lobehub.com); the client appends `/v2/ws`. */gatewayUrl: string;/** Called before EVERY connect attempt; must return a fresh user JWT. */