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.

πŸ”¨ chore: add GatewayStreamNotifier for Agent Gateway WebSocket push (#13603)

Arvin Xu6c9cbb07eeaa
diff --git a/src/envs/app.ts b/src/envs/app.ts
index de5a7f6afff..74b8cf8b13d 100644
--- a/src/envs/app.ts
+++ b/src/envs/app.ts
@@ -75,6 +75,8 @@ export const getAppConfig = () => {
*/
MARKET_TRUSTED_CLIENT_ID: z.string().optional(),
+ AGENT_GATEWAY_SERVICE_TOKEN: z.string().optional(),
+ AGENT_GATEWAY_URL: z.string().url(),
/**
* Enable Queue-based Agent Runtime
* When true, use QStash for async agent execution (production)
@@ -118,6 +120,8 @@ export const getAppConfig = () => {
MARKET_TRUSTED_CLIENT_SECRET: process.env.MARKET_TRUSTED_CLIENT_SECRET,
MARKET_TRUSTED_CLIENT_ID: process.env.MARKET_TRUSTED_CLIENT_ID,
+ AGENT_GATEWAY_SERVICE_TOKEN: process.env.AGENT_GATEWAY_SERVICE_TOKEN,
+ AGENT_GATEWAY_URL: process.env.AGENT_GATEWAY_URL || 'https://agent-gateway.lobehub.com',
enableQueueAgentRuntime: process.env.AGENT_RUNTIME_MODE === 'queue',
TELEMETRY_DISABLED: process.env.TELEMETRY_DISABLED === '1',
},
diff --git a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts b/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts
new file mode 100644
index 00000000000..4dbcd96fe51
--- /dev/null
+++ b/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -0,0 +1,174 @@
+import debug from 'debug';
+import urlJoin from 'url-join';
+
+import type { StreamChunkData, StreamEvent } from './StreamEventManager';
+import type { IStreamEventManager } from './types';
+
+const log = debug('lobe-server:agent-runtime:gateway-notifier');
+
+const POST_TIMEOUT = 5000; // 5s per request
+const MAX_INFLIGHT = 20; // bounded concurrency
+
+/**
+ * Decorator that wraps an IStreamEventManager and additionally
+ * pushes events to the Agent Gateway via HTTP (fire-and-forget).
+ *
+ * Redis SSE remains the primary event storage / subscription mechanism.
+ * The Gateway is an additional push channel for WebSocket delivery.
+ */
+export class GatewayStreamNotifier implements IStreamEventManager {
+ private inflight = 0;
+
+ constructor(
+ private inner: IStreamEventManager,
+ private gatewayUrl: string,
+ private serviceToken: string,
+ ) {
+ log('Gateway notifier initialized: %s', gatewayUrl);
+ }
+
+ // ─── Publish methods: delegate to inner + notify gateway ───
+
+ async publishStreamEvent(
+ operationId: string,
+ event: Omit<StreamEvent, 'operationId' | 'timestamp'>,
+ ): Promise<string> {
+ const result = await this.inner.publishStreamEvent(operationId, event);
+ this.pushEvent(operationId, { ...event, operationId, timestamp: Date.now() });
+ return result;
+ }
+
+ async publishStreamChunk(
+ operationId: string,
+ stepIndex: number,
+ chunkData: StreamChunkData,
+ ): Promise<string> {
+ const result = await this.inner.publishStreamChunk(operationId, stepIndex, chunkData);
+ this.pushEvent(operationId, {
+ data: chunkData,
+ operationId,
+ stepIndex,
+ timestamp: Date.now(),
+ type: 'stream_chunk',
+ });
+ return result;
+ }
+
+ async publishAgentRuntimeInit(operationId: string, initialState: any): Promise<string> {
+ const result = await this.inner.publishAgentRuntimeInit(operationId, initialState);
+
+ this.httpPost('/api/operations/init', {
+ operationId,
+ userId: initialState?.userId || 'unknown',
+ });
+
+ this.pushEvent(operationId, {
+ data: initialState,
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'agent_runtime_init',
+ });
+
+ return result;
+ }
+
+ async publishAgentRuntimeEnd(
+ operationId: string,
+ stepIndex: number,
+ finalState: any,
+ reason?: string,
+ reasonDetail?: string,
+ ): Promise<string> {
+ const result = await this.inner.publishAgentRuntimeEnd(
+ operationId,
+ stepIndex,
+ finalState,
+ reason,
+ reasonDetail,
+ );
+
+ this.pushEvent(operationId, {
+ data: { finalState, reason, reasonDetail },
+ operationId,
+ stepIndex,
+ timestamp: Date.now(),
+ type: 'agent_runtime_end',
+ });
+
+ const status =
+ reason === 'error' ? 'error' : reason === 'interrupted' ? 'interrupted' : 'completed';
+ this.httpPost('/api/operations/update-status', {
+ operationId,
+ status,
+ summary: reasonDetail,
+ });
+
+ return result;
+ }
+
+ // ─── Read / subscribe methods: delegate directly to inner ───
+
+ async subscribeStreamEvents(
+ operationId: string,
+ lastEventId: string,
+ onEvents: (events: StreamEvent[]) => void,
+ signal?: AbortSignal,
+ ): Promise<void> {
+ return this.inner.subscribeStreamEvents(operationId, lastEventId, onEvents, signal);
+ }
+
+ async getStreamHistory(operationId: string, count?: number): Promise<StreamEvent[]> {
+ return this.inner.getStreamHistory(operationId, count);
+ }
+
+ async cleanupOperation(operationId: string): Promise<void> {
+ return this.inner.cleanupOperation(operationId);
+ }
+
+ async getActiveOperationsCount(): Promise<number> {
+ return this.inner.getActiveOperationsCount();
+ }
+
+ async disconnect(): Promise<void> {
+ return this.inner.disconnect();
+ }
+
+ // ─── Gateway HTTP helpers ───
+
+ private pushEvent(operationId: string, event: Record<string, unknown>) {
+ this.httpPost('/api/operations/push-event', { event, operationId }).catch(() => {});
+ }
+
+ private async httpPost(path: string, body: Record<string, unknown>): Promise<void> {
+ if (this.inflight >= MAX_INFLIGHT) {
+ log('Gateway %s dropped: max inflight (%d) reached', path, MAX_INFLIGHT);
+ return;
+ }
+
+ this.inflight++;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), POST_TIMEOUT);
+
+ try {
+ const res = await fetch(urlJoin(this.gatewayUrl, path), {
+ body: JSON.stringify(body),
+ headers: {
+ 'Authorization': `Bearer ${this.serviceToken}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ signal: controller.signal,
+ });
+
+ if (!res.ok) {
+ log('Gateway %s returned %d: %s', path, res.status, await res.text());
+ }
+ } catch (error) {
+ log('Gateway %s failed: %O', path, error);
+ } finally {
+ clearTimeout(timer);
+ this.inflight--;
+ }
+ }
+}
diff --git a/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
new file mode 100644
index 00000000000..bd3c6e8a7cd
--- /dev/null
+++ b/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -0,0 +1,320 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GatewayStreamNotifier } from '../GatewayStreamNotifier';
+import type { StreamChunkData } from '../StreamEventManager';
+import type { IStreamEventManager } 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,
+ subscribeStreamEvents: track('subscribeStreamEvents') as any,
+ };
+}
+
+describe('GatewayStreamNotifier', () => {
+ let inner: ReturnType<typeof createMockInner>;
+ let notifier: GatewayStreamNotifier;
+ const gatewayUrl = 'https://gateway.test.com';
+ const serviceToken = 'test-token';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ inner = createMockInner();
+ notifier = new GatewayStreamNotifier(inner, gatewayUrl, serviceToken);
+ });
+
+ // ─── Publish methods: must always call inner first ───
+
+ describe('publishStreamEvent', () => {
+ it('delegates to inner and returns its result', async () => {
+ const event = { data: { foo: 'bar' }, stepIndex: 0, type: 'step_start' as const };
+
+ const result = await notifier.publishStreamEvent('op-1', event);
+
+ expect(result).toBe('publishStreamEvent-result');
+ expect(inner.calls.publishStreamEvent).toHaveLength(1);
+ expect(inner.calls.publishStreamEvent[0]).toEqual(['op-1', event]);
+ });
+
+ it('pushes event to gateway via HTTP', async () => {
+ await notifier.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'step_start' as const,
+ });
+
+ // Wait for fire-and-forget
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ `${gatewayUrl}/api/operations/push-event`,
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: `Bearer ${serviceToken}`,
+ }),
+ method: 'POST',
+ }),
+ );
+ });
+
+ it('still returns inner result even if gateway fails', async () => {
+ mockFetch.mockRejectedValueOnce(new Error('network error'));
+
+ const result = await notifier.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'step_start' as const,
+ });
+
+ expect(result).toBe('publishStreamEvent-result');
+ expect(inner.calls.publishStreamEvent).toHaveLength(1);
+ });
+ });
+
+ describe('publishStreamChunk', () => {
+ it('delegates to inner and returns its result', async () => {
+ const chunkData: StreamChunkData = { chunkType: 'text', content: 'hello' };
+
+ const result = await notifier.publishStreamChunk('op-1', 0, chunkData);
+
+ expect(result).toBe('publishStreamChunk-result');
+ expect(inner.calls.publishStreamChunk).toHaveLength(1);
+ expect(inner.calls.publishStreamChunk[0]).toEqual(['op-1', 0, chunkData]);
+ });
+ });
+
+ describe('publishAgentRuntimeInit', () => {
+ it('delegates to inner and returns its result', async () => {
+ const initialState = { userId: 'user-1' };
+
+ const result = await notifier.publishAgentRuntimeInit('op-1', initialState);
+
+ expect(result).toBe('publishAgentRuntimeInit-result');
+ expect(inner.calls.publishAgentRuntimeInit).toHaveLength(1);
+ expect(inner.calls.publishAgentRuntimeInit[0]).toEqual(['op-1', initialState]);
+ });
+
+ it('calls gateway init and push-event endpoints', async () => {
+ await notifier.publishAgentRuntimeInit('op-1', { userId: 'user-1' });
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const urls = mockFetch.mock.calls.map((c: any[]) => c[0]);
+ expect(urls).toContain(`${gatewayUrl}/api/operations/init`);
+ expect(urls).toContain(`${gatewayUrl}/api/operations/push-event`);
+ });
+ });
+
+ describe('publishAgentRuntimeEnd', () => {
+ it('delegates to inner and returns its result', async () => {
+ const finalState = { status: 'done' };
+
+ const result = await notifier.publishAgentRuntimeEnd('op-1', 2, finalState, 'completed');
+
+ expect(result).toBe('publishAgentRuntimeEnd-result');
+ expect(inner.calls.publishAgentRuntimeEnd).toHaveLength(1);
+ expect(inner.calls.publishAgentRuntimeEnd[0]).toEqual([
+ 'op-1',
+ 2,
+ finalState,
+ 'completed',
+ undefined,
+ ]);
+ });
+
+ it('calls gateway push-event and update-status endpoints', async () => {
+ await notifier.publishAgentRuntimeEnd('op-1', 2, {}, 'completed', 'All done');
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const urls = mockFetch.mock.calls.map((c: any[]) => c[0]);
+ expect(urls).toContain(`${gatewayUrl}/api/operations/push-event`);
+ expect(urls).toContain(`${gatewayUrl}/api/operations/update-status`);
+ });
+
+ it('maps error reason to error status', async () => {
+ await notifier.publishAgentRuntimeEnd('op-1', 0, {}, 'error', 'Something broke');
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const statusCall = mockFetch.mock.calls.find(
+ (c: any[]) => c[0] === `${gatewayUrl}/api/operations/update-status`,
+ );
+ expect(statusCall).toBeDefined();
+ const body = JSON.parse(statusCall![1].body);
+ expect(body.status).toBe('error');
+ });
+ });
+
+ // ─── 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', () => {
+ it('publishStreamEvent succeeds when gateway is unreachable', async () => {
+ mockFetch.mockRejectedValue(new Error('connection refused'));
+
+ const result = await notifier.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'step_start' as const,
+ });
+
+ expect(result).toBe('publishStreamEvent-result');
+ expect(inner.calls.publishStreamEvent).toHaveLength(1);
+ });
+
+ it('publishAgentRuntimeInit succeeds when gateway returns 500', async () => {
+ mockFetch.mockResolvedValue({ ok: false, status: 500, text: () => 'Internal Error' });
+
+ const result = await notifier.publishAgentRuntimeInit('op-1', { userId: 'u1' });
+
+ expect(result).toBe('publishAgentRuntimeInit-result');
+ expect(inner.calls.publishAgentRuntimeInit).toHaveLength(1);
+ });
+
+ it('publishAgentRuntimeEnd succeeds when gateway times out', async () => {
+ mockFetch.mockImplementation(
+ () => new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 10)),
+ );
+
+ const result = await notifier.publishAgentRuntimeEnd('op-1', 0, {}, 'completed');
+
+ expect(result).toBe('publishAgentRuntimeEnd-result');
+ expect(inner.calls.publishAgentRuntimeEnd).toHaveLength(1);
+ });
+ });
+
+ // ─── Timeout and concurrency ───
+
+ describe('timeout and concurrency control', () => {
+ it('passes AbortSignal to fetch', async () => {
+ await notifier.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'step_start' as const,
+ });
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const fetchCall = mockFetch.mock.calls[0];
+ expect(fetchCall[1].signal).toBeInstanceOf(AbortSignal);
+ });
+
+ it('drops requests when max inflight is reached', async () => {
+ // Hold all fetches pending
+ const resolvers: Array<() => void> = [];
+ mockFetch.mockImplementation(
+ () =>
+ new Promise<{ ok: boolean }>((resolve) => {
+ resolvers.push(() => resolve({ ok: true }));
+ }),
+ );
+
+ // Fire 25 events (max inflight is 20)
+ for (let i = 0; i < 25; i++) {
+ notifier.publishStreamEvent(`op-${i}`, {
+ data: {},
+ stepIndex: 0,
+ type: 'step_start' as const,
+ });
+ }
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Only 20 should have actually called fetch
+ expect(mockFetch).toHaveBeenCalledTimes(20);
+
+ // Release all pending
+ for (const r of resolvers) r();
+ });
+
+ it('uses url-join for URL construction', async () => {
+ await notifier.publishStreamEvent('op-1', {
+ data: {},
+ stepIndex: 0,
+ type: 'step_start' as const,
+ });
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const url = mockFetch.mock.calls[0][0];
+ expect(url).toBe(`${gatewayUrl}/api/operations/push-event`);
+ // No double slashes
+ expect(url).not.toContain('//api');
+ });
+ });
+});
diff --git a/src/server/modules/AgentRuntime/__tests__/factory.test.ts b/src/server/modules/AgentRuntime/__tests__/factory.test.ts
index d650484f726..2ddc1205089 100644
--- a/src/server/modules/AgentRuntime/__tests__/factory.test.ts
+++ b/src/server/modules/AgentRuntime/__tests__/factory.test.ts
@@ -4,6 +4,7 @@ import { createAgentStateManager, createStreamEventManager, isRedisAvailable } f
const {
MockAgentStateManager,
+ MockGatewayStreamNotifier,
MockStreamEventManager,
mockAppEnv,
mockGetAgentRuntimeRedisClient,
@@ -11,8 +12,16 @@ const {
mockInMemoryStreamEventManager,
} = vi.hoisted(() => ({
MockAgentStateManager: vi.fn(() => ({ kind: 'redis-state-manager' })),
+ MockGatewayStreamNotifier: vi.fn((inner: any, url: string, token: string) => ({
+ inner,
+ kind: 'gateway-stream-notifier',
+ token,
+ url,
+ })),
MockStreamEventManager: vi.fn(() => ({ kind: 'redis-stream-event-manager' })),
mockAppEnv: {
+ AGENT_GATEWAY_SERVICE_TOKEN: undefined as string | undefined,
+ AGENT_GATEWAY_URL: 'https://agent-gateway.lobehub.com',
enableQueueAgentRuntime: false,
},
mockGetAgentRuntimeRedisClient: vi.fn(),
@@ -44,6 +53,10 @@ vi.mock('../StreamEventManager', () => ({
StreamEventManager: MockStreamEventManager,
}));
+vi.mock('../GatewayStreamNotifier', () => ({
+ GatewayStreamNotifier: MockGatewayStreamNotifier,
+}));
+
describe('AgentRuntime factory', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -89,6 +102,11 @@ describe('AgentRuntime factory', () => {
});
describe('createStreamEventManager', () => {
+ beforeEach(() => {
+ mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = undefined;
+ mockAppEnv.AGENT_GATEWAY_URL = 'https://agent-gateway.lobehub.com';
+ });
+
it('prefers Redis-backed streams when Redis is available in local mode', () => {
mockGetAgentRuntimeRedisClient.mockReturnValue({ ping: vi.fn() });
@@ -108,5 +126,46 @@ describe('AgentRuntime factory', () => {
'Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.',
);
});
+
+ it('wraps with GatewayStreamNotifier when AGENT_GATEWAY_SERVICE_TOKEN is set', () => {
+ mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'my-token';
+ mockGetAgentRuntimeRedisClient.mockReturnValue({ ping: vi.fn() });
+
+ const result = createStreamEventManager() as any;
+
+ expect(result.kind).toBe('gateway-stream-notifier');
+ expect(result.inner).toEqual({ kind: 'redis-stream-event-manager' });
+ expect(result.token).toBe('my-token');
+ expect(result.url).toBe('https://agent-gateway.lobehub.com');
+ });
+
+ it('uses custom AGENT_GATEWAY_URL when set', () => {
+ mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'my-token';
+ mockAppEnv.AGENT_GATEWAY_URL = 'https://custom-gateway.example.com';
+ mockGetAgentRuntimeRedisClient.mockReturnValue({ ping: vi.fn() });
+
+ const result = createStreamEventManager() as any;
+
+ expect(result.kind).toBe('gateway-stream-notifier');
+ expect(result.url).toBe('https://custom-gateway.example.com');
+ });
+
+ it('wraps in-memory manager with gateway when no Redis', () => {
+ mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'my-token';
+
+ const result = createStreamEventManager() as any;
+
+ expect(result.kind).toBe('gateway-stream-notifier');
+ expect(result.inner).toBe(mockInMemoryStreamEventManager);
+ });
+
+ it('does not wrap when AGENT_GATEWAY_SERVICE_TOKEN is not set', () => {
+ mockGetAgentRuntimeRedisClient.mockReturnValue({ ping: vi.fn() });
+
+ const result = createStreamEventManager() as any;
+
+ expect(result.kind).toBe('redis-stream-event-manager');
+ expect(MockGatewayStreamNotifier).not.toHaveBeenCalled();
+ });
});
});
diff --git a/src/server/modules/AgentRuntime/factory.ts b/src/server/modules/AgentRuntime/factory.ts
index 8eaf2181749..4d72c504acf 100644
--- a/src/server/modules/AgentRuntime/factory.ts
+++ b/src/server/modules/AgentRuntime/factory.ts
@@ -3,6 +3,7 @@ import debug from 'debug';
import { appEnv } from '@/envs/app';
import { AgentStateManager } from './AgentStateManager';
+import { GatewayStreamNotifier } from './GatewayStreamNotifier';
import { inMemoryAgentStateManager } from './InMemoryAgentStateManager';
import { inMemoryStreamEventManager } from './InMemoryStreamEventManager';
import { getAgentRuntimeRedisClient } from './redis';
@@ -54,17 +55,31 @@ export const createAgentStateManager = (): IAgentStateManager => {
* - If Redis is unavailable and enableQueueAgentRuntime=true: throw
*/
export const createStreamEventManager = (): IStreamEventManager => {
+ let manager: IStreamEventManager;
+
// Prefer Redis whenever it is available so the runtime worker and SSE route
// can communicate through the same stream bus even in local mode.
if (isRedisAvailable()) {
log('Redis available, using StreamEventManager');
- return new StreamEventManager();
+ manager = new StreamEventManager();
+ } else if (!isQueueModeEnabled()) {
+ log('Redis unavailable and queue mode disabled, using InMemoryStreamEventManager');
+ manager = inMemoryStreamEventManager;
+ } else {
+ throw new Error(
+ 'Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.',
+ );
}
- if (!isQueueModeEnabled()) {
- log('Redis unavailable and queue mode disabled, using InMemoryStreamEventManager');
- return inMemoryStreamEventManager;
+ // Wrap with Gateway notifier when configured
+ if (appEnv.AGENT_GATEWAY_SERVICE_TOKEN) {
+ log('Wrapping with GatewayStreamNotifier (%s)', appEnv.AGENT_GATEWAY_URL);
+ return new GatewayStreamNotifier(
+ manager,
+ appEnv.AGENT_GATEWAY_URL,
+ appEnv.AGENT_GATEWAY_SERVICE_TOKEN,
+ );
}
- throw new Error('Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.');
+ return manager;
};
diff --git a/src/server/modules/AgentRuntime/index.ts b/src/server/modules/AgentRuntime/index.ts
index ec48f564bec..78ce27f2fe2 100644
--- a/src/server/modules/AgentRuntime/index.ts
+++ b/src/server/modules/AgentRuntime/index.ts
@@ -2,6 +2,7 @@ export type { AgentRuntimeCoordinatorOptions } from './AgentRuntimeCoordinator';
export { AgentRuntimeCoordinator } from './AgentRuntimeCoordinator';
export { AgentStateManager } from './AgentStateManager';
export { createAgentStateManager, createStreamEventManager, isRedisAvailable } from './factory';
+export { GatewayStreamNotifier } from './GatewayStreamNotifier';
export { InMemoryAgentStateManager } from './InMemoryAgentStateManager';
export { InMemoryStreamEventManager } from './InMemoryStreamEventManager';
export { createRuntimeExecutors } from './RuntimeExecutors';