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.

✨ feat(agent-runtime): send relayed LLM attempts through the gateway's llm routes (#20334)

Arvin Xu3d8bd203a039
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 880b4bd2f66..565031ef696 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -1,4 +1,8 @@
-import type { ToolExecuteData } from '@lobechat/agent-gateway-client';
+import type {
+ LlmCancelData,
+ LlmExecuteData,
+ ToolExecuteData,
+} from '@lobechat/agent-gateway-client';
import { projectToolEndResult } from '@lobechat/tool-view-model';
import type { ChatMessageError } from '@lobechat/types';
import debug from 'debug';
@@ -21,7 +25,11 @@ import {
type StreamChunkData,
type StreamEvent,
} from './StreamEventManager';
-import type { IStreamEventManager, PublishAgentRuntimeEndParams } from './types';
+import type {
+ IStreamEventManager,
+ LlmExecuteDispatchResult,
+ PublishAgentRuntimeEndParams,
+} from './types';
const log = debug('lobe-server:agent-runtime:gateway-notifier');
@@ -170,6 +178,12 @@ export interface GatewayStreamNotifierOptions {
export class GatewayStreamNotifier implements IStreamEventManager {
private inflight = 0;
+ /**
+ * The gateway answered 404 for the LLM relay routes (self-hosted Go gateway,
+ * an older Worker deployment): relay events go out as plain stream events.
+ */
+ private llmRelayRoutesMissing = false;
+
/**
* Gateway pushes issued for an operation that have not settled yet, and the
* last ordering barrier among them.
@@ -489,6 +503,84 @@ export class GatewayStreamNotifier implements IStreamEventManager {
await this.httpPostAwait('/api/operations/tool-execute', { data, operationId });
}
+ /**
+ * Hand one relayed LLM attempt to the user's device. The gateway delivers it
+ * to the client that started the run (when connected) and keeps it
+ * replayable until it is cancelled, closed or past its deadline.
+ *
+ * A gateway without the route (the self-hosted Go gateway, an older Worker
+ * deployment) answers 404: the event then goes out as a plain stream event,
+ * which those gateways broadcast to every subscriber β€” the backend's
+ * per-call lease still keeps a single writer. Rejects on any other failure.
+ */
+ async sendLlmExecute(
+ operationId: string,
+ data: LlmExecuteData,
+ ): Promise<LlmExecuteDispatchResult> {
+ log('sendLlmExecute operation=%s callId=%s', operationId, data.callId);
+ if (!this.llmRelayRoutesMissing) {
+ const res = await this.httpPostResponse('/api/operations/llm-execute', { data, operationId });
+ if (res.ok) {
+ let delivered: number | undefined;
+ try {
+ delivered = (JSON.parse(res.body) as { delivered?: number }).delivered;
+ } catch {
+ // An older body shape; delivery is only diagnostics.
+ }
+ return { delivered, routed: true };
+ }
+ if (res.status !== 404) {
+ throw new Error(`Gateway /api/operations/llm-execute returned ${res.status}: ${res.body}`);
+ }
+ this.llmRelayRoutesMissing = true;
+ }
+
+ await this.publishStreamEvent(operationId, {
+ data,
+ stepIndex: data.stepIndex,
+ type: 'llm_execute',
+ });
+ return { routed: false };
+ }
+
+ /** Stop a relayed LLM attempt on every client (see {@link sendLlmExecute} for the fallback). */
+ async sendLlmCancel(operationId: string, data: LlmCancelData & { stepIndex: number }) {
+ log('sendLlmCancel operation=%s callId=%s', operationId, data.callId);
+ const { stepIndex, ...cancel } = data;
+ if (!this.llmRelayRoutesMissing) {
+ const res = await this.httpPostResponse('/api/operations/llm-cancel', {
+ data: cancel,
+ operationId,
+ });
+ if (res.ok) return;
+ if (res.status !== 404) {
+ throw new Error(`Gateway /api/operations/llm-cancel returned ${res.status}`);
+ }
+ this.llmRelayRoutesMissing = true;
+ }
+
+ await this.publishStreamEvent(operationId, { data: cancel, stepIndex, type: 'llm_cancel' });
+ }
+
+ /**
+ * The attempt is over: the gateway stops replaying its `llm_execute`.
+ * Best effort β€” the gateway also drops it at the attempt's deadline.
+ */
+ async closeLlmCall(operationId: string, callId: string): Promise<void> {
+ if (this.llmRelayRoutesMissing) return;
+ try {
+ const res = await this.httpPostResponse('/api/operations/llm-close', { callId, operationId });
+ if (res.ok) return;
+ if (res.status === 404) {
+ this.llmRelayRoutesMissing = true;
+ return;
+ }
+ log('closeLlmCall for %s (%s): gateway returned %d', operationId, callId, res.status);
+ } catch (error) {
+ log('closeLlmCall failed for %s (%s): %O', operationId, callId, error);
+ }
+ }
+
// ─── Read / subscribe methods: delegate directly to inner ───
async subscribeStreamEvents(
@@ -756,6 +848,22 @@ export class GatewayStreamNotifier implements IStreamEventManager {
* to know whether the gateway accepted the request.
*/
private async httpPostAwait(path: string, body: Record<string, unknown>): Promise<void> {
+ const res = await this.httpPostResponse(path, body);
+ if (!res.ok) {
+ throw new Error(`Gateway ${path} returned ${res.status}: ${res.body}`);
+ }
+ }
+
+ /**
+ * POST and hand back the status and body, whatever the status. The body is
+ * read under the same timeout as the request, so a gateway that sends
+ * headers and then stalls cannot hang the caller. Rejects on network errors
+ * and timeout.
+ */
+ private async httpPostResponse(
+ path: string,
+ body: Record<string, unknown>,
+ ): Promise<{ body: string; ok: boolean; status: number }> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), POST_TIMEOUT);
@@ -769,11 +877,11 @@ export class GatewayStreamNotifier implements IStreamEventManager {
method: 'POST',
signal: controller.signal,
});
-
- if (!res.ok) {
- const text = await res.text().catch(() => '');
- throw new Error(`Gateway ${path} returned ${res.status}: ${text}`);
- }
+ const text = await res.text().catch((error) => {
+ if (controller.signal.aborted) throw error;
+ return '';
+ });
+ return { body: text, ok: res.ok, status: res.status };
} finally {
clearTimeout(timer);
}
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 5d06c2810e9..b59edff7b35 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -1036,6 +1036,149 @@ describe('GatewayStreamNotifier', () => {
});
});
+ describe('LLM relay routes', () => {
+ const executeData = {
+ attempt: 0,
+ callId: 'op-1:2:0',
+ deadlines: { claimMs: 15_000, firstChunkMs: 120_000, idleMs: 60_000, totalMs: 540_000 },
+ leaseToken: 'lease',
+ model: 'llama3',
+ operationId: 'op-1',
+ preferredClientId: 'tab-a',
+ provider: 'ollama',
+ runtimeProvider: 'ollama',
+ stepIndex: 2,
+ };
+
+ const callsTo = (path: string) =>
+ mockFetch.mock.calls.filter((c: any[]) => String(c[0]).endsWith(path));
+
+ beforeEach(() => {
+ mockFetch.mockReset();
+ mockFetch.mockResolvedValue({
+ ok: true,
+ status: 200,
+ text: () => Promise.resolve('{"delivered":1,"success":true}'),
+ });
+ });
+
+ it('sends llm_execute to the routed endpoint, not as a broadcast stream event', async () => {
+ const result = await notifier.sendLlmExecute('op-1', executeData);
+
+ expect(result).toEqual({ delivered: 1, routed: true });
+ const [call] = callsTo('/api/operations/llm-execute');
+ expect(call[0]).toBe(`${gatewayUrl}/api/operations/llm-execute`);
+ expect(call[1].headers.Authorization).toBe(`Bearer ${serviceToken}`);
+ expect(JSON.parse(call[1].body)).toEqual({ data: executeData, operationId: 'op-1' });
+ expect(callsTo('/api/operations/push-event')).toHaveLength(0);
+ });
+
+ it('cancels and closes a call through their routes', async () => {
+ await notifier.sendLlmCancel('op-1', {
+ callId: 'op-1:2:0',
+ reason: 'interrupted',
+ stepIndex: 2,
+ });
+ await notifier.closeLlmCall('op-1', 'op-1:2:0');
+
+ expect(JSON.parse(callsTo('/api/operations/llm-cancel')[0][1].body)).toEqual({
+ data: { callId: 'op-1:2:0', reason: 'interrupted' },
+ operationId: 'op-1',
+ });
+ expect(JSON.parse(callsTo('/api/operations/llm-close')[0][1].body)).toEqual({
+ callId: 'op-1:2:0',
+ operationId: 'op-1',
+ });
+ });
+
+ it('falls back to a plain stream event on a gateway without the routes (404), and remembers it', async () => {
+ mockFetch.mockImplementation((url: string) =>
+ Promise.resolve(
+ url.includes('/llm-')
+ ? { ok: false, status: 404, text: () => Promise.resolve('404 page not found') }
+ : { ok: true, status: 200, text: () => Promise.resolve('') },
+ ),
+ );
+
+ expect(await notifier.sendLlmExecute('op-1', executeData)).toEqual({ routed: false });
+ await notifier.sendLlmCancel('op-1', { callId: 'op-1:2:0', reason: 'timeout', stepIndex: 2 });
+ await notifier.closeLlmCall('op-1', 'op-1:2:0');
+ await vi.waitFor(() => expect(callsTo('/api/operations/push-event')).toHaveLength(2));
+
+ const pushed = callsTo('/api/operations/push-event').map(
+ (c: any[]) => JSON.parse(c[1].body).event,
+ );
+ expect(pushed.map((e: any) => e.type)).toEqual(['llm_execute', 'llm_cancel']);
+ expect(pushed[0]).toMatchObject({ data: executeData, operationId: 'op-1', stepIndex: 2 });
+ expect(pushed[1].data).toEqual({ callId: 'op-1:2:0', reason: 'timeout' });
+ // Only the first relay call probed the route; cancel and close did not.
+ expect(callsTo('/api/operations/llm-execute')).toHaveLength(1);
+ expect(callsTo('/api/operations/llm-cancel')).toHaveLength(0);
+ expect(callsTo('/api/operations/llm-close')).toHaveLength(0);
+ });
+
+ it('stops probing the relay routes once a close returns 404', async () => {
+ mockFetch.mockImplementation((url: string) =>
+ Promise.resolve(
+ url.includes('/llm-close')
+ ? { ok: false, status: 404, text: () => Promise.resolve('404 page not found') }
+ : { ok: true, status: 200, text: () => Promise.resolve('') },
+ ),
+ );
+
+ await notifier.closeLlmCall('op-1', 'op-1:2:0');
+ await notifier.closeLlmCall('op-1', 'op-1:2:1');
+
+ expect(callsTo('/api/operations/llm-close')).toHaveLength(1);
+ expect(await notifier.sendLlmExecute('op-1', executeData)).toEqual({ routed: false });
+ });
+
+ it('times out a gateway that sends headers and then stalls the body', async () => {
+ vi.useFakeTimers();
+ try {
+ // Headers arrive; the body never does until the request is aborted.
+ mockFetch.mockImplementation((_url: string, init: RequestInit) =>
+ Promise.resolve({
+ ok: true,
+ status: 200,
+ text: () =>
+ new Promise((_resolve, reject) => {
+ init.signal!.addEventListener('abort', () => reject(new Error('aborted')));
+ }),
+ }),
+ );
+
+ const execute = notifier.sendLlmExecute('op-1', executeData);
+ const tool = notifier.sendToolExecute('op-1', {
+ apiName: 'readFile',
+ arguments: '{}',
+ executionTimeoutMs: 30_000,
+ identifier: 'local-system',
+ toolCallId: 'call-1',
+ });
+ const settled = Promise.allSettled([execute, tool]);
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ const [executeResult, toolResult] = await settled;
+ expect(executeResult).toMatchObject({ reason: expect.any(Error), status: 'rejected' });
+ expect(toolResult).toMatchObject({ reason: expect.any(Error), status: 'rejected' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('rejects when the gateway refuses the dispatch for another reason', async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 409,
+ text: () => Promise.resolve('{"delivered":0,"error":"OPERATION_ENDED"}'),
+ });
+
+ await expect(notifier.sendLlmExecute('op-1', executeData)).rejects.toThrow(/409/);
+ expect(callsTo('/api/operations/push-event')).toHaveLength(0);
+ });
+ });
+
// ─── Single-connection multiplexing: mirror member events to supervisor op ───
describe('mirrorToOperationId (single-connection multiplexing)', () => {
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
index 92572515f7b..bc9f05491ae 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
@@ -165,7 +165,19 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
stepIndex: params.stepIndex,
};
- await params.streamManager.publishStreamEvent(params.operationId, {
+ const { streamManager } = params;
+ if (streamManager.sendLlmExecute) {
+ const { delivered, routed } = await streamManager.sendLlmExecute(params.operationId, data);
+ log(
+ '[%s] llm_execute dispatched (routed=%s, delivered=%s)',
+ params.callId,
+ routed,
+ delivered,
+ );
+ return;
+ }
+
+ await streamManager.publishStreamEvent(params.operationId, {
data,
stepIndex: params.stepIndex,
type: 'llm_execute',
@@ -312,7 +324,15 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
this.deadlines.totalMs + LLM_RELAY_KEY_GRACE_MS,
);
const data: LlmCancelData = { callId, reason };
- await streamManager.publishStreamEvent(operationId, { data, stepIndex, type: 'llm_cancel' });
+ if (streamManager.sendLlmCancel) {
+ await streamManager.sendLlmCancel(operationId, { ...data, stepIndex });
+ } else {
+ await streamManager.publishStreamEvent(operationId, {
+ data,
+ stepIndex,
+ type: 'llm_cancel',
+ });
+ }
} catch (error) {
log('[%s] failed to cancel the relayed attempt: %O', callId, error);
}
@@ -320,7 +340,7 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
/** Close the call: late uploads find no open call and get `410`. */
private async cleanup(reader?: RelayBatchReader) {
- const { callId, redis } = this.params;
+ const { callId, operationId, redis, streamManager } = this.params;
try {
await redis
.multi()
@@ -331,6 +351,12 @@ export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleCha
log('[%s] failed to clean up relay keys: %O', callId, error);
}
reader?.close();
+ // Stop the gateway replaying the attempt to clients that subscribe later.
+ // Best-effort and bounded by the attempt deadline anyway, so a stalled
+ // gateway must not hold up settling the stream.
+ void Promise.resolve(streamManager.closeLlmCall?.(operationId, callId)).catch((error) =>
+ log('[%s] failed to close the call on the gateway: %O', callId, error),
+ );
}
private createDiagnostics(options: ChatMethodOptions): ProviderResponseDiagnostics {
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
index 4dfbb337455..a920a8c1408 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
@@ -365,6 +365,107 @@ describe('RelayModelRuntime + llm-relay handlers', () => {
});
});
+describe('RelayModelRuntime over a gateway with relay routes', () => {
+ beforeEach(() => {
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+ redis = new FakeRedis();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ /** A gateway notifier: `llm_execute` / `llm_cancel` go through their own routes. */
+ const createGatewayManager = () => {
+ const executes: LlmExecuteData[] = [];
+ const manager = {
+ closeLlmCall: vi.fn(async () => {}),
+ publishStreamEvent: vi.fn(async () => 'event-id'),
+ sendLlmCancel: vi.fn(async () => {}),
+ sendLlmExecute: vi.fn(async (_operationId: string, data: LlmExecuteData) => {
+ executes.push(data);
+ return { delivered: 1, routed: true };
+ }),
+ };
+ return { executes, manager };
+ };
+
+ it('dispatches through the routed path and closes the call when the attempt is done', async () => {
+ const { executes, manager } = createGatewayManager();
+ const done = createRuntime(manager)
+ .chat(payload, {})
+ .then((response) => consumeStreamUntilDone(response));
+
+ await vi.waitFor(() => expect(executes).toHaveLength(1));
+ expect(manager.sendLlmExecute).toHaveBeenCalledWith(
+ 'op_1',
+ expect.objectContaining({ callId: CALL_ID, preferredClientId: 'tab-a', stepIndex: 0 }),
+ );
+ // Nothing goes out as a broadcast stream event.
+ expect(manager.publishStreamEvent).not.toHaveBeenCalled();
+
+ await post(executes[0].leaseToken, {
+ chunks: [{ data: 'Hi', type: 'text' }],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 1,
+ });
+ await done;
+
+ expect(manager.closeLlmCall).toHaveBeenCalledWith('op_1', CALL_ID);
+ expect(manager.sendLlmCancel).not.toHaveBeenCalled();
+ });
+
+ it('settles the stream without waiting on a stalled gateway close', async () => {
+ const { executes, manager } = createGatewayManager();
+ manager.closeLlmCall.mockImplementation(() => new Promise<void>(() => {}));
+ const done = createRuntime(manager)
+ .chat(payload, {})
+ .then((response) => consumeStreamUntilDone(response));
+
+ await vi.waitFor(() => expect(executes).toHaveLength(1));
+ await post(executes[0].leaseToken, {
+ chunks: [{ data: 'Hi', type: 'text' }],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 1,
+ });
+
+ await expect(done).resolves.toBeUndefined();
+ expect(manager.closeLlmCall).toHaveBeenCalledWith('op_1', CALL_ID);
+ });
+
+ it('cancels through the routed path on stop, then closes the call', async () => {
+ const { executes, manager } = createGatewayManager();
+ const controller = new AbortController();
+ const response = await createRuntime(manager).chat(payload, { signal: controller.signal });
+ const consumed = consumeStreamUntilDone(response);
+ await vi.waitFor(() => expect(executes).toHaveLength(1));
+ await post(executes[0].leaseToken, { chunks: [], clientId: 'tab-a', seq: 1 });
+
+ controller.abort();
+
+ await expect(consumed).rejects.toMatchObject({ name: 'AbortError' });
+ expect(manager.sendLlmCancel).toHaveBeenCalledWith('op_1', {
+ callId: CALL_ID,
+ reason: 'interrupted',
+ stepIndex: 0,
+ });
+ expect(manager.closeLlmCall).toHaveBeenCalledWith('op_1', CALL_ID);
+ expect(manager.publishStreamEvent).not.toHaveBeenCalled();
+ });
+
+ it('fails as ClientLlmExecutorUnavailable when the gateway refuses the dispatch', async () => {
+ const { manager } = createGatewayManager();
+ manager.sendLlmExecute.mockRejectedValueOnce(new Error('Gateway returned 409'));
+
+ await expect(createRuntime(manager).chat(payload, {})).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ });
+ expect(redis.peek(llmRelayKeys.payload(CALL_ID))).toBeUndefined();
+ });
+});
+
describe('llm-relay upload handler', () => {
beforeEach(() => {
vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index d9079f852cf..4b6a4f759ba 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -1,4 +1,8 @@
-import type { ToolExecuteData } from '@lobechat/agent-gateway-client';
+import type {
+ LlmCancelData,
+ LlmExecuteData,
+ ToolExecuteData,
+} from '@lobechat/agent-gateway-client';
import { type AgentState } from '@lobechat/agent-runtime';
import { type UIChatMessage } from '@lobechat/types';
@@ -176,12 +180,22 @@ export interface IAgentStateManager {
* Stream Event Manager Interface
* Abstract interface for stream event publishing, supports Redis and in-memory implementations
*/
+export interface LlmExecuteDispatchResult {
+ /** Clients the gateway reached right away; a late subscriber still gets it from replay. */
+ delivered?: number;
+ /** False when the gateway lacks the relay routes and the event was broadcast instead. */
+ routed: boolean;
+}
+
export interface IStreamEventManager {
/**
* Clean up stream data for operation
*/
cleanupOperation: (operationId: string) => Promise<void>;
+ /** Optional: the relayed attempt is over; the gateway stops replaying it. */
+ closeLlmCall?: (operationId: string, callId: string) => Promise<void>;
+
/**
* Close connections
*/
@@ -254,6 +268,19 @@ export interface IStreamEventManager {
blockMs?: number,
) => Promise<{ events: StreamEvent[]; lastEventId: string }>;
+ /** Optional: stop a relayed LLM attempt on every client (`llm_cancel`). */
+ sendLlmCancel?: (
+ operationId: string,
+ data: LlmCancelData & { stepIndex: number },
+ ) => Promise<void>;
+
+ /**
+ * Optional: hand a relayed LLM attempt (`llm_execute`) to the user's device
+ * through the Agent Gateway, routed to the client that started the run.
+ * Absent on managers without a gateway; callers publish a stream event then.
+ */
+ sendLlmExecute?: (operationId: string, data: LlmExecuteData) => Promise<LlmExecuteDispatchResult>;
+
/**
* Optional: dispatch a tool execution request to the client via Agent Gateway.
* Rejects if the gateway is unavailable β€” callers decide their fallback path.