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): relay device-only LLM calls to the client — server half (behind agent_llm_relay) (#20332)

Arvin Xu2d0ba6ccc535
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index 4fe7fc223e8..fbd5b90ace3 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -23,6 +23,7 @@ import {
import { parseAgentConfig } from './parseDefaultAgent';
import { parseFilesConfig } from './parseFilesConfig';
import { getPublicMemoryExtractionConfig } from './parseMemoryExtractionConfig';
+import { getServerFetchOnClientOverride } from './serverFetchOnClient';
/**
* Get Better-Auth SSO providers list
@@ -76,11 +77,11 @@ export const getServerGlobalConfig = async () => {
withDeploymentName: true,
},
lmstudio: {
- fetchOnClient: isDesktop ? false : undefined,
+ fetchOnClient: getServerFetchOnClientOverride('lmstudio'),
},
ollama: {
enabled: isDesktop ? true : undefined,
- fetchOnClient: isDesktop ? false : !process.env.OLLAMA_PROXY_URL,
+ fetchOnClient: getServerFetchOnClientOverride('ollama'),
},
ollamacloud: {
enabledKey: 'ENABLED_OLLAMA_CLOUD',
@@ -96,7 +97,7 @@ export const getServerGlobalConfig = async () => {
modelListKey: 'TENCENT_CLOUD_MODEL_LIST',
},
unsloth: {
- fetchOnClient: isDesktop ? false : undefined,
+ fetchOnClient: getServerFetchOnClientOverride('unsloth'),
},
volcengine: {
withDeploymentName: true,
diff --git a/apps/server/src/globalConfig/serverFetchOnClient.test.ts b/apps/server/src/globalConfig/serverFetchOnClient.test.ts
new file mode 100644
index 00000000000..8451ff66394
--- /dev/null
+++ b/apps/server/src/globalConfig/serverFetchOnClient.test.ts
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getServerFetchOnClientOverride } from './serverFetchOnClient';
+
+describe('getServerFetchOnClientOverride', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('sends Ollama through the server only when the deployment proxies it', () => {
+ expect(getServerFetchOnClientOverride('ollama')).toBe(true);
+
+ vi.stubEnv('OLLAMA_PROXY_URL', 'http://ollama.internal:11434');
+ expect(getServerFetchOnClientOverride('ollama')).toBe(false);
+ });
+
+ it('leaves other providers on their own default', () => {
+ expect(getServerFetchOnClientOverride('lmstudio')).toBeUndefined();
+ expect(getServerFetchOnClientOverride('openai')).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/globalConfig/serverFetchOnClient.ts b/apps/server/src/globalConfig/serverFetchOnClient.ts
new file mode 100644
index 00000000000..43f059bb8f8
--- /dev/null
+++ b/apps/server/src/globalConfig/serverFetchOnClient.ts
@@ -0,0 +1,25 @@
+import { isDesktop } from '@/const/version';
+
+/**
+ * The deployment's `fetchOnClient` default for providers it overrides, as the
+ * server global config hands it to the client store. `undefined` leaves the
+ * provider's own default in place.
+ *
+ * - Desktop builds request local providers from the main process, never the
+ * renderer.
+ * - A deployment with `OLLAMA_PROXY_URL` proxies Ollama through the server.
+ */
+export const getServerFetchOnClientOverride = (provider: string): boolean | undefined => {
+ switch (provider) {
+ case 'lmstudio':
+ case 'unsloth': {
+ return isDesktop ? false : undefined;
+ }
+ case 'ollama': {
+ return isDesktop ? false : !process.env.OLLAMA_PROXY_URL;
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
index f4bf2aa238f..0c73414a50c 100644
--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
@@ -150,6 +150,8 @@ export interface StreamChunkData {
reasoning?: string;
/** Multimodal reasoning parts (text + images) */
reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
+ /** Relayed LLM attempt this chunk re-publishes; the executor client skips its own echo. */
+ relayCallId?: string;
toolsCalling?: ChatToolPayload[];
}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts
new file mode 100644
index 00000000000..aa7da8740f5
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts
@@ -0,0 +1,259 @@
+// @vitest-environment node
+import type { LLMAttemptInput } from '@lobechat/agent-runtime';
+import { ToolNameResolver } from '@lobechat/context-engine';
+import type { ChatMethodOptions } from '@lobechat/model-runtime';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+
+import type { RuntimeExecutorContext } from '../context';
+import {
+ createClientLlmExecutorLostError,
+ createClientLlmExecutorUnavailableError,
+ createClientLlmTimeoutError,
+} from '../llmRelay/errors';
+import { RelayModelRuntime } from '../llmRelay/RelayModelRuntime';
+import { resolveLlmExecutionSite } from '../llmRelay/resolveLlmExecutionSite';
+import { ServerLLMTransport } from './ServerLLMTransport';
+
+const relay = vi.hoisted(() => ({
+ chat: vi.fn(),
+ usageEstimated: false,
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));
+vi.mock('../llmRelay/resolveLlmExecutionSite', () => ({ resolveLlmExecutionSite: vi.fn() }));
+vi.mock('../llmRelay/RelayModelRuntime', () => ({
+ RelayModelRuntime: vi.fn(function (this: any) {
+ this.chat = relay.chat;
+ this.handleChatStreamError = vi.fn();
+ this.result = {
+ get usageEstimated() {
+ return relay.usageEstimated;
+ },
+ };
+ }),
+}));
+vi.mock('../redis', () => ({ getAgentRuntimeRedisClient: () => ({}) }));
+vi.mock('@/business/server/recordModelCompletionFailure', () => ({
+ recordModelCompletionFailure: vi.fn(),
+}));
+vi.mock('@/envs/file', () => ({ fileEnv: { NEXT_PUBLIC_S3_FILE_PATH: 'files' } }));
+
+const toolName = new ToolNameResolver().generate('workspace', 'search', 'builtin');
+
+const createCtx = () => {
+ const publishStreamChunk = vi.fn().mockResolvedValue('chunk-id');
+ const update = vi.fn().mockResolvedValue({ success: true });
+ const ctx = {
+ messageModel: { update } as unknown as RuntimeExecutorContext['messageModel'],
+ operationId: 'op-1',
+ serverDB: {} as RuntimeExecutorContext['serverDB'],
+ stepIndex: 2,
+ streamManager: {
+ publishStreamChunk,
+ publishStreamEvent: vi.fn().mockResolvedValue('event-id'),
+ } as unknown as RuntimeExecutorContext['streamManager'],
+ toolExecutionService: {} as RuntimeExecutorContext['toolExecutionService'],
+ userId: 'user-1',
+ } satisfies RuntimeExecutorContext;
+ return { ctx, publishStreamChunk, update };
+};
+
+const createInput = (attempt = 1): LLMAttemptInput => ({
+ assistantMessageId: 'msg-1',
+ attempt,
+ context: {
+ messages: [{ content: 'Question', role: 'user' }],
+ modelParameters: {},
+ replayAssistantReasoning: false,
+ resolvedTools: {
+ enabledToolIds: [],
+ executorMap: {},
+ manifestMap: {},
+ promptManifestMap: {},
+ sourceMap: {},
+ tools: [
+ {
+ function: { description: 'Search', name: toolName, parameters: { type: 'object' } },
+ type: 'function',
+ },
+ ],
+ },
+ } as unknown as LLMAttemptInput['context'],
+ events: [],
+ maxAttempts: 6,
+ model: 'llama3',
+ provider: 'ollama',
+ state: {} as LLMAttemptInput['state'],
+});
+
+const answerWith =
+ (text: string, error?: unknown) => async (_payload: unknown, options: ChatMethodOptions) => {
+ await options.callback?.onText?.(text);
+ if (error) throw error;
+ await options.callback?.onCompletion?.({
+ text,
+ usage: { totalInputTokens: 3, totalOutputTokens: 1, totalTokens: 4 },
+ });
+ return new Response('');
+ };
+
+/** `{operationId}:{stepIndex}:{generation}:{attempt}` for op-1, step 2, attempt 1. */
+const CALL_ID_1 = /^op-1:2:[\w-]+:1$/;
+
+describe('ServerLLMTransport · LLM relay', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ relay.usageEstimated = false;
+ vi.mocked(resolveLlmExecutionSite).mockResolvedValue({
+ preferredClientId: 'tab-a',
+ runtimeProvider: 'ollama',
+ site: 'client',
+ });
+ });
+
+ it('runs a client-site attempt through RelayModelRuntime and marks the output as client-executed', async () => {
+ const { ctx, publishStreamChunk } = createCtx();
+ relay.chat.mockImplementation(answerWith('Hi from my laptop'));
+ relay.usageEstimated = true;
+
+ const execution = await new ServerLLMTransport(ctx).runAttempt(createInput());
+
+ expect(execution.ok).toBe(true);
+ expect(execution.output).toMatchObject({
+ content: 'Hi from my laptop',
+ executionSite: 'client',
+ usageEstimated: true,
+ });
+ expect(initModelRuntimeFromDB).not.toHaveBeenCalled();
+ expect(RelayModelRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assistantMessageId: 'msg-1',
+ attempt: 1,
+ callId: expect.stringMatching(CALL_ID_1),
+ operationId: 'op-1',
+ preferredClientId: 'tab-a',
+ provider: 'ollama',
+ runtimeProvider: 'ollama',
+ stepIndex: 2,
+ userId: 'user-1',
+ }),
+ );
+ // Re-published chunks carry the call id so the executor skips its own echo.
+ expect(publishStreamChunk).toHaveBeenCalledWith(
+ 'op-1',
+ 2,
+ expect.objectContaining({ chunkType: 'text', relayCallId: expect.stringMatching(CALL_ID_1) }),
+ );
+ });
+
+ it('gives every attempt its own call id', async () => {
+ const { ctx } = createCtx();
+ relay.chat.mockImplementation(answerWith('ok'));
+ const transport = new ServerLLMTransport(ctx);
+
+ await transport.runAttempt(createInput(1));
+ await transport.runAttempt(createInput(2));
+
+ const [first, second] = vi.mocked(RelayModelRuntime).mock.calls.map(([p]) => p.callId);
+ expect(first).toMatch(CALL_ID_1);
+ expect(second).toMatch(/^op-1:2:[\w-]+:2$/);
+ expect(first.split(':')[2]).toBe(second.split(':')[2]);
+ });
+
+ it('keeps a redriven step off the call ids of the execution it replaces', async () => {
+ const { ctx } = createCtx();
+ relay.chat.mockImplementation(answerWith('ok'));
+
+ // The queue redrives the same operation/step after the first worker died.
+ await new ServerLLMTransport(ctx).runAttempt(createInput(1));
+ await new ServerLLMTransport(ctx).runAttempt(createInput(1));
+
+ const [dead, redriven] = vi.mocked(RelayModelRuntime).mock.calls.map(([p]) => p.callId);
+ expect(dead).toMatch(CALL_ID_1);
+ expect(redriven).toMatch(CALL_ID_1);
+ expect(redriven).not.toBe(dead);
+ });
+
+ it('fails fast with ClientLlmExecutorUnavailable when no client can execute the provider', async () => {
+ const { ctx } = createCtx();
+ vi.mocked(resolveLlmExecutionSite).mockResolvedValue({
+ reason: 'no_executor',
+ site: 'unavailable',
+ });
+
+ await expect(new ServerLLMTransport(ctx).runAttempt(createInput())).rejects.toMatchObject({
+ error: { reason: 'no_executor', recoverable: true },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ provider: 'ollama',
+ });
+ expect(relay.chat).not.toHaveBeenCalled();
+ expect(initModelRuntimeFromDB).not.toHaveBeenCalled();
+ });
+
+ it('keeps the server path untouched for server-site providers', async () => {
+ const { ctx } = createCtx();
+ vi.mocked(resolveLlmExecutionSite).mockResolvedValue({ site: 'server' });
+ const chat = vi.fn(answerWith('from the server'));
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ chat,
+ handleChatStreamError: vi.fn(),
+ } as any);
+
+ const execution = await new ServerLLMTransport(ctx).runAttempt(createInput());
+
+ expect(execution.output.content).toBe('from the server');
+ expect(execution.output.executionSite).toBeUndefined();
+ expect(RelayModelRuntime).not.toHaveBeenCalled();
+ });
+
+ it('re-dispatches a lost executor twice and a missed first chunk once, never a missed total or no executor', () => {
+ const { ctx } = createCtx();
+ const { retryPolicy } = new ServerLLMTransport(ctx);
+ const budget = (error: unknown) => retryPolicy.resolveRetryBudget('ollama', error);
+
+ expect(budget(createClientLlmExecutorLostError('ollama', 'idle'))).toBe(2);
+ expect(budget(createClientLlmTimeoutError('ollama', 'first_chunk'))).toBe(1);
+ expect(budget(createClientLlmTimeoutError('ollama', 'total'))).toBe(0);
+ expect(budget(createClientLlmExecutorUnavailableError('ollama', 'claim_timeout'))).toBe(0);
+ expect(retryPolicy.classifyError(createClientLlmExecutorLostError('ollama', 'idle')).kind).toBe(
+ 'retry',
+ );
+ expect(
+ retryPolicy.classifyError(createClientLlmExecutorUnavailableError('ollama', 'no_executor'))
+ .kind,
+ ).toBe('stop');
+ });
+
+ it('keeps the partial output, marked as cut short, when a relay failure is final', async () => {
+ const { ctx, update } = createCtx();
+ relay.chat.mockImplementation(
+ answerWith('Half an answer', createClientLlmTimeoutError('ollama', 'total')),
+ );
+
+ const execution = await new ServerLLMTransport(ctx).runAttempt(createInput());
+
+ expect(execution.ok).toBe(false);
+ expect(update).toHaveBeenCalledWith('msg-1', {
+ content: 'Half an answer',
+ metadata: { executionSite: 'client', interruptedMidStream: true },
+ });
+ });
+
+ it('drops the partial output while a lost executor still has re-dispatches left, keeps it after the last', async () => {
+ const { ctx, update } = createCtx();
+ relay.chat.mockImplementation(
+ answerWith('Half', createClientLlmExecutorLostError('ollama', 'idle')),
+ );
+ const transport = new ServerLLMTransport(ctx);
+
+ await transport.runAttempt(createInput(1));
+ await transport.runAttempt(createInput(2));
+ expect(update).not.toHaveBeenCalled();
+
+ await transport.runAttempt(createInput(3));
+ expect(update).toHaveBeenCalledWith('msg-1', expect.objectContaining({ content: 'Half' }));
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts
index 72efc1c15f7..225a0c9948e 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts
@@ -12,6 +12,10 @@ vi.mock('@/server/modules/ModelRuntime', () => ({
initModelRuntimeFromDB: vi.fn(),
}));
+vi.mock('../llmRelay/resolveLlmExecutionSite', () => ({
+ resolveLlmExecutionSite: vi.fn(async () => ({ site: 'server' })),
+}));
+
describe('ServerLLMTransport.stream · conversation affinity', () => {
it('retains the conversation ID across compression requests and runtime recreation', async () => {
const chat = vi.fn().mockImplementation(async () => new Response(''));
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index bbd5fff08c4..3ebf66e44ab 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -1,3 +1,5 @@
+import { randomBytes } from 'node:crypto';
+
import type {
BlobStore,
ContextBuildOutput,
@@ -13,7 +15,11 @@ import type {
LLMTraceInput,
LLMTransport,
} from '@lobechat/agent-runtime';
-import { resolveLLMMaxAttempts, resolveLLMRetryBudget } from '@lobechat/agent-runtime';
+import {
+ resolveLLMMaxAttempts,
+ resolveLLMRetryBudget,
+ shouldRetryLLM,
+} from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import {
type ChatStreamPayload,
@@ -40,6 +46,17 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import type { RuntimeExecutorContext } from '../context';
import { log, sleep } from '../executorHelpers';
import { classifyLLMError } from '../llmErrorClassification';
+import {
+ createClientLlmExecutorUnavailableError,
+ isClientLlmRelayError,
+ resolveLlmRelayRetryBudget,
+} from '../llmRelay/errors';
+import { buildLlmRelayCallId } from '../llmRelay/protocol';
+import { RelayModelRuntime } from '../llmRelay/RelayModelRuntime';
+import type { LlmExecutionSite } from '../llmRelay/resolveLlmExecutionSite';
+import { resolveLlmExecutionSite } from '../llmRelay/resolveLlmExecutionSite';
+import { getAgentRuntimeRedisClient } from '../redis';
+import type { IStreamEventManager } from '../types';
import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
const getErrorMessage = (error: unknown): string => {
@@ -134,7 +151,9 @@ class ServerLLMRetryPolicy implements LLMRetryPolicy {
resolveRetryBudget(provider: string, error: unknown) {
if (isRetryableNetworkEmptyCompletion(error)) return NETWORK_EMPTY_COMPLETION_MAX_RETRIES;
- return resolveLLMRetryBudget(provider, SERVER_LLM_RETRY_POLICY);
+ return (
+ resolveLlmRelayRetryBudget(error) ?? resolveLLMRetryBudget(provider, SERVER_LLM_RETRY_POLICY)
+ );
}
async waitForRetry(delayMs: number): Promise<void> {
@@ -225,6 +244,24 @@ class ServerLLMTrace implements LLMTrace {
}
}
+/**
+ * The step's stream manager, with every chunk it re-publishes for a relayed
+ * attempt tagged by the attempt's call id, so the executor client can skip
+ * the echo of output it already rendered locally.
+ */
+const tagRelayChunks = (streamManager: IStreamEventManager, callId: string): IStreamEventManager =>
+ new Proxy(streamManager, {
+ get(target, property, receiver) {
+ if (property === 'publishStreamChunk') {
+ const publish: IStreamEventManager['publishStreamChunk'] = (operationId, stepIndex, data) =>
+ target.publishStreamChunk(operationId, stepIndex, { ...data, relayCallId: callId });
+ return publish;
+ }
+ const value = Reflect.get(target, property, receiver);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+
/**
* Server {@link LLMTransport} adapter — wraps model-runtime streaming and
* returns the aggregated content/usage that package executors need.
@@ -232,11 +269,18 @@ class ServerLLMTrace implements LLMTrace {
export class ServerLLMTransport implements LLMTransport {
readonly retryPolicy: LLMRetryPolicy;
+ private readonly executionSitePromises = new Map<string, Promise<LlmExecutionSite>>();
+
private readonly modelRuntimePromises = new Map<
string,
ReturnType<ServerLLMTransport['createModelRuntime']>
>();
+ private relayStreamCount = 0;
+
+ /** Keeps a redriven step's call ids apart from the execution it replaces. */
+ private readonly relayGeneration = randomBytes(6).toString('base64url');
+
constructor(
private readonly ctx: RuntimeExecutorContext,
private readonly blobStore?: BlobStore,
@@ -249,6 +293,35 @@ export class ServerLLMTransport implements LLMTransport {
}
async runAttempt(input: LLMAttemptInput): Promise<LLMAttemptExecution> {
+ const site = await this.getExecutionSite(input.provider, input.state);
+
+ if (site.site === 'unavailable') {
+ throw createClientLlmExecutorUnavailableError(input.provider, site.reason);
+ }
+
+ if (site.site === 'client') {
+ const callId = buildLlmRelayCallId(
+ this.ctx.operationId,
+ this.ctx.stepIndex,
+ this.relayGeneration,
+ input.attempt,
+ );
+ const relayRuntime = this.createRelayRuntime(input.provider, site, {
+ assistantMessageId: input.assistantMessageId,
+ attempt: input.attempt,
+ callId,
+ });
+ const execution = await this.runAttemptWithRuntime(input, relayRuntime, {
+ ...this.ctx,
+ streamManager: tagRelayChunks(this.ctx.streamManager, callId),
+ });
+ execution.output.executionSite = 'client';
+ if (relayRuntime.result.usageEstimated) execution.output.usageEstimated = true;
+
+ if (!execution.ok) await this.keepRelayPartialOnTerminalError(input, execution);
+ return execution;
+ }
+
const modelRuntime = await this.getModelRuntime(input.provider);
return this.runAttemptWithRuntime(input, modelRuntime);
}
@@ -257,7 +330,7 @@ export class ServerLLMTransport implements LLMTransport {
payload: LLMStreamPayload,
handlers?: Parameters<LLMTransport['stream']>[1],
): Promise<LLMStreamResult> {
- const runtime = await this.createModelRuntime(payload.provider);
+ const runtime = await this.createStreamRuntime(payload.provider);
const { provider: _provider, ...runtimePayload } = payload;
let content = '';
let usage: LLMStreamResult['usage'];
@@ -292,6 +365,95 @@ export class ServerLLMTransport implements LLMTransport {
return result;
}
+ /**
+ * Lightweight calls (context compression) follow the same execution site as
+ * the run's attempts; a relayed one gets its own call id outside the attempt
+ * numbering.
+ */
+ private async createStreamRuntime(provider: string) {
+ const state = (await this.ctx.loadAgentState?.(this.ctx.operationId)) ?? undefined;
+ const site = await this.getExecutionSite(provider, state);
+
+ if (site.site === 'unavailable') {
+ throw createClientLlmExecutorUnavailableError(provider, site.reason);
+ }
+ if (site.site === 'client') {
+ this.relayStreamCount += 1;
+ return this.createRelayRuntime(provider, site, {
+ attempt: 1,
+ callId: `${buildLlmRelayCallId(this.ctx.operationId, this.ctx.stepIndex, this.relayGeneration, 1)}:stream${this.relayStreamCount}`,
+ });
+ }
+
+ return this.createModelRuntime(provider);
+ }
+
+ private createRelayRuntime(
+ provider: string,
+ site: Extract<LlmExecutionSite, { site: 'client' }>,
+ call: { assistantMessageId?: string; attempt: number; callId: string },
+ ) {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) throw createClientLlmExecutorUnavailableError(provider, 'relay_unsupported');
+
+ return new RelayModelRuntime({
+ ...call,
+ operationId: this.ctx.operationId,
+ preferredClientId: site.preferredClientId,
+ provider,
+ redis,
+ runtimeProvider: site.runtimeProvider,
+ stepIndex: this.ctx.stepIndex,
+ streamManager: this.ctx.streamManager,
+ userId: this.ctx.userId!,
+ });
+ }
+
+ private getExecutionSite(provider: string, state?: LLMAttemptInput['state']) {
+ let promise = this.executionSitePromises.get(provider);
+ if (!promise) {
+ promise = resolveLlmExecutionSite({
+ db: this.ctx.serverDB,
+ provider,
+ state,
+ userId: this.ctx.userId!,
+ workspaceId: this.ctx.workspaceId,
+ });
+ this.executionSitePromises.set(provider, promise);
+ }
+ return promise;
+ }
+
+ /**
+ * When a relayed attempt fails for good — the executor vanished and the
+ * re-dispatch budget is spent, or the total deadline passed — keep what the
+ * device had already produced on the message, marked as cut short, rather
+ * than dropping it with the error (U4b). Retried attempts start over, so
+ * their partial output is discarded as usual.
+ */
+ private async keepRelayPartialOnTerminalError(
+ input: LLMAttemptInput,
+ execution: Extract<LLMAttemptExecution, { ok: false }>,
+ ) {
+ const { error, output } = execution;
+ if (!input.assistantMessageId || !isClientLlmRelayError(error)) return;
+ if (!output.content && !output.thinkingContent) return;
+
+ const classified = this.retryPolicy.classifyError(error);
+ const budget = this.retryPolicy.resolveRetryBudget(input.provider, error);
+ if (shouldRetryLLM(classified.kind, input.attempt, budget)) return;
+
+ try {
+ await this.ctx.messageModel.update(input.assistantMessageId, {
+ content: output.content,
+ metadata: { executionSite: 'client', interruptedMidStream: true } as any,
+ ...(output.thinkingContent && { reasoning: { content: output.thinkingContent } }),
+ });
+ } catch (error) {
+ console.error('[ServerLLMTransport] Failed to keep relayed partial output:', error);
+ }
+ }
+
private createModelRuntime(provider: string) {
return initModelRuntimeFromDB(
this.ctx.serverDB,
@@ -313,6 +475,7 @@ export class ServerLLMTransport implements LLMTransport {
private async runAttemptWithRuntime(
input: LLMAttemptInput,
modelRuntime: Pick<ModelRuntime, 'chat' | 'handleChatStreamError'>,
+ ctx: RuntimeExecutorContext = this.ctx,
): Promise<LLMAttemptExecution> {
const resolved = input.context.resolvedTools;
if (!resolved) throw new Error('Resolved tools are required for a server LLM attempt');
@@ -333,7 +496,7 @@ export class ServerLLMTransport implements LLMTransport {
attempt: input.attempt,
blobStore: this.blobStore,
chatPayload,
- ctx: this.ctx,
+ ctx,
events: input.events,
maxAttempts: input.maxAttempts,
messageCount: chatPayload.messages.length,
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/RelayBatchReader.ts b/apps/server/src/modules/AgentRuntime/llmRelay/RelayBatchReader.ts
new file mode 100644
index 00000000000..c4fefdb0b66
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/RelayBatchReader.ts
@@ -0,0 +1,143 @@
+import type { LlmRelayBatch, LlmRelayDeadlines } from '@lobechat/agent-gateway-client';
+import type Redis from 'ioredis';
+
+/** What the server keeps of an uploaded batch (the uploader is settled by the lease). */
+export type StoredRelayBatch = Pick<LlmRelayBatch, 'chunks' | 'final' | 'seq'>;
+
+export type RelayDeadline = 'claim' | 'first_chunk' | 'gap' | 'idle' | 'total';
+
+export type RelayReadResult =
+ | { batch: StoredRelayBatch; kind: 'batch' }
+ | { kind: 'aborted' }
+ | { kind: 'timeout'; which: RelayDeadline };
+
+/**
+ * Upper bound of one blocking read, so an abort or a deadline is noticed
+ * within this window even when nothing arrives.
+ */
+const POLL_MS = 2000;
+const READ_COUNT = 100;
+
+/**
+ * Reads the batches of one relayed attempt from its Redis Stream in `seq`
+ * order (T-540 §4.1): a batch at or below the last delivered `seq` is a
+ * duplicate and dropped; one ahead of it waits until the gap fills. Owns a
+ * dedicated (blocking) Redis connection.
+ *
+ * Deadlines (T-540 §4.3), all measured on the server:
+ * - `claim`: no batch at all within `claimMs` of dispatch — nobody picked it up
+ * - `first_chunk`: claimed, but no non-empty batch within `firstChunkMs`
+ * - `idle` / `gap`: nothing delivered for `idleMs` (with a batch stuck behind
+ * a missing one: `gap`); idle executors heartbeat with empty batches
+ * - `total`: the whole attempt, from dispatch
+ */
+export class RelayBatchReader {
+ private claimedAt?: number;
+ private firstChunkAt?: number;
+ private lastDeliveredAt?: number;
+ private lastSeq = 0;
+ private lastStreamId = '0-0';
+ private readonly pending = new Map<number, StoredRelayBatch>();
+
+ constructor(
+ private readonly redis: Redis,
+ private readonly streamKey: string,
+ private readonly deadlines: LlmRelayDeadlines,
+ private readonly dispatchedAt: number,
+ private readonly now: () => number = Date.now,
+ ) {}
+
+ /** A non-empty chunk has been delivered. */
+ get hasOutput() {
+ return this.firstChunkAt !== undefined;
+ }
+
+ /** Release the dedicated connection. */
+ close() {
+ this.redis.disconnect();
+ }
+
+ async next(signal?: AbortSignal): Promise<RelayReadResult> {
+ for (;;) {
+ const ready = this.pending.get(this.lastSeq + 1);
+ if (ready) return { batch: this.deliver(ready), kind: 'batch' };
+
+ if (signal?.aborted) return { kind: 'aborted' };
+
+ const deadline = this.nextDeadline();
+ const now = this.now();
+ if (now >= deadline.at) return { kind: 'timeout', which: deadline.which };
+
+ await this.read(Math.max(1, Math.min(POLL_MS, deadline.at - now)));
+ }
+ }
+
+ private deliver(batch: StoredRelayBatch) {
+ this.pending.delete(batch.seq);
+ this.lastSeq = batch.seq;
+ this.lastDeliveredAt = this.now();
+ if (this.firstChunkAt === undefined && batch.chunks.length > 0) {
+ this.firstChunkAt = this.lastDeliveredAt;
+ }
+ return batch;
+ }
+
+ private nextDeadline(): { at: number; which: RelayDeadline } {
+ const candidates: { at: number; which: RelayDeadline }[] = [
+ { at: this.dispatchedAt + this.deadlines.totalMs, which: 'total' },
+ ];
+
+ if (this.claimedAt === undefined) {
+ candidates.push({ at: this.dispatchedAt + this.deadlines.claimMs, which: 'claim' });
+ } else {
+ if (this.firstChunkAt === undefined) {
+ candidates.push({ at: this.claimedAt + this.deadlines.firstChunkMs, which: 'first_chunk' });
+ }
+ candidates.push({
+ at: (this.lastDeliveredAt ?? this.claimedAt) + this.deadlines.idleMs,
+ which: this.pending.size > 0 ? 'gap' : 'idle',
+ });
+ }
+
+ return candidates.reduce((earliest, candidate) =>
+ candidate.at < earliest.at ? candidate : earliest,
+ );
+ }
+
+ private async read(blockMs: number) {
+ const result = (await this.redis.xread(
+ 'COUNT',
+ READ_COUNT,
+ 'BLOCK',
+ blockMs,
+ 'STREAMS',
+ this.streamKey,
+ this.lastStreamId,
+ )) as [string, [string, string[]][]][] | null;
+
+ for (const [, entries] of result ?? []) {
+ for (const [id, fields] of entries) {
+ this.lastStreamId = id;
+ const batch = parseEntry(fields);
+ if (!batch) continue;
+
+ this.claimedAt ??= this.now();
+ if (batch.seq <= this.lastSeq || this.pending.has(batch.seq)) continue;
+ this.pending.set(batch.seq, batch);
+ }
+ }
+ }
+}
+
+const parseEntry = (fields: string[]): StoredRelayBatch | undefined => {
+ const values: Record<string, string> = {};
+ for (let i = 0; i + 1 < fields.length; i += 2) values[fields[i]] = fields[i + 1];
+
+ try {
+ const batch = JSON.parse(values.body) as StoredRelayBatch;
+ if (!Number.isInteger(batch.seq) || !Array.isArray(batch.chunks)) return;
+ return batch;
+ } catch {
+ return;
+ }
+};
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
new file mode 100644
index 00000000000..92572515f7b
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
@@ -0,0 +1,374 @@
+import type {
+ LlmCancelData,
+ LlmExecuteData,
+ LlmRelayDeadlines,
+} from '@lobechat/agent-gateway-client';
+import type {
+ ChatMethodOptions,
+ ChatStreamPayload,
+ ModelRuntime,
+ ProviderResponseDiagnostics,
+} from '@lobechat/model-runtime';
+import { createCallbacksTransformer } from '@lobechat/model-runtime';
+import type { ModelUsage } from '@lobechat/types';
+import debug from 'debug';
+import type Redis from 'ioredis';
+
+import { getInvocationDeadline } from '@/server/utils/invocationDeadline';
+import { encodeAsync } from '@/utils/tokenizer';
+
+import type { IStreamEventManager } from '../types';
+import {
+ createClientLlmExecutorLostError,
+ createClientLlmExecutorUnavailableError,
+ createClientLlmTimeoutError,
+} from './errors';
+import {
+ DEFAULT_LLM_RELAY_DEADLINES,
+ fitLlmRelayDeadlines,
+ LLM_RELAY_KEY_GRACE_MS,
+ llmRelayKeys,
+ signLlmRelayLease,
+} from './protocol';
+import type { RelayDeadline, StoredRelayBatch } from './RelayBatchReader';
+import { RelayBatchReader } from './RelayBatchReader';
+
+const log = debug('lobe-server:agent-runtime:llm-relay');
+
+export interface RelayModelRuntimeParams {
+ /** Assistant message the attempt streams into, for the client's local rendering. */
+ assistantMessageId?: string;
+ attempt: number;
+ callId: string;
+ deadlines?: LlmRelayDeadlines;
+ now?: () => number;
+ operationId: string;
+ preferredClientId?: string;
+ provider: string;
+ redis: Redis;
+ runtimeProvider: string;
+ stepIndex: number;
+ streamManager: IStreamEventManager;
+ userId: string;
+}
+
+/** What the attempt learned besides the stream, read back by the transport. */
+export interface RelayAttemptResult {
+ /** The client reported no usage; the server estimated it. */
+ usageEstimated: boolean;
+}
+
+const toSseLines = (chunk: StoredRelayBatch['chunks'][number]) => [
+ ...(chunk.id ? [`id: ${chunk.id}\n`] : []),
+ `event: ${chunk.type}\n`,
+ `data: ${JSON.stringify(chunk.data ?? null)}\n\n`,
+];
+
+const createAbortError = () => {
+ const error = new Error('The relayed LLM attempt was aborted');
+ error.name = 'AbortError';
+ return error;
+};
+
+/**
+ * Server half of the LLM relay (T-540 §3.3): same shape as {@link ModelRuntime}
+ * for `serverCallLlmAttempt`, but `chat()` does not dial the provider. It
+ * stores the request for the user's device, dispatches `llm_execute`, and turns
+ * the batches the device uploads back into the normalized protocol stream. The
+ * rest of the pipeline — persistence, push, tool-call resolution, usage, the
+ * next step — runs unchanged on that stream.
+ *
+ * Not built through `initModelRuntimeFromDB`, so the cloud billing hooks never
+ * see a relayed call: the user's own device paid for it.
+ *
+ * One instance per attempt: `callId` is the attempt's idempotency key.
+ */
+export class RelayModelRuntime implements Pick<ModelRuntime, 'chat' | 'handleChatStreamError'> {
+ readonly result: RelayAttemptResult = { usageEstimated: false };
+
+ private readonly deadlines: LlmRelayDeadlines;
+ private readonly now: () => number;
+
+ constructor(private readonly params: RelayModelRuntimeParams) {
+ this.deadlines = fitLlmRelayDeadlines(
+ params.deadlines ?? DEFAULT_LLM_RELAY_DEADLINES,
+ getInvocationDeadline(),
+ );
+ this.now = params.now ?? Date.now;
+ }
+
+ async chat(payload: ChatStreamPayload, options: ChatMethodOptions = {}): Promise<Response> {
+ const { callId, provider, redis } = this.params;
+ const dispatchedAt = this.now();
+ const ttlMs = this.deadlines.totalMs + LLM_RELAY_KEY_GRACE_MS;
+
+ await redis
+ .multi()
+ .del(
+ llmRelayKeys.bytes(callId),
+ llmRelayKeys.cancel(callId),
+ llmRelayKeys.lease(callId),
+ llmRelayKeys.stream(callId),
+ )
+ .set(llmRelayKeys.payload(callId), JSON.stringify(payload), 'PX', ttlMs)
+ .set(llmRelayKeys.open(callId), this.params.userId, 'PX', ttlMs)
+ .exec();
+
+ try {
+ await this.dispatch(payload.model, dispatchedAt);
+ } catch (error) {
+ log('[%s] llm_execute dispatch failed: %O', callId, error);
+ await this.cleanup();
+ throw createClientLlmExecutorUnavailableError(provider, 'relay_unsupported');
+ }
+
+ const reader = new RelayBatchReader(
+ redis.duplicate(),
+ llmRelayKeys.stream(callId),
+ this.deadlines,
+ dispatchedAt,
+ this.now,
+ );
+
+ return new Response(
+ this.createStream(reader, payload, options).pipeThrough(
+ createCallbacksTransformer(options.callback),
+ ),
+ );
+ }
+
+ /**
+ * The provider was never called from here: the device already normalized
+ * its error into the uploaded stream. Nothing to sanitize or bill.
+ */
+ async handleChatStreamError(error: unknown): Promise<void> {
+ log('[%s] relayed attempt failed: %O', this.params.callId, error);
+ }
+
+ private async dispatch(model: string, dispatchedAt: number) {
+ const { params } = this;
+ const data: LlmExecuteData = {
+ assistantMessageId: params.assistantMessageId,
+ attempt: params.attempt,
+ callId: params.callId,
+ deadlines: this.deadlines,
+ leaseToken: signLlmRelayLease({
+ callId: params.callId,
+ exp: dispatchedAt + this.deadlines.totalMs + LLM_RELAY_KEY_GRACE_MS,
+ userId: params.userId,
+ }),
+ model,
+ operationId: params.operationId,
+ preferredClientId: params.preferredClientId,
+ provider: params.provider,
+ runtimeProvider: params.runtimeProvider,
+ stepIndex: params.stepIndex,
+ };
+
+ await params.streamManager.publishStreamEvent(params.operationId, {
+ data,
+ stepIndex: params.stepIndex,
+ type: 'llm_execute',
+ });
+ }
+
+ private createStream(
+ reader: RelayBatchReader,
+ payload: ChatStreamPayload,
+ options: ChatMethodOptions,
+ ): ReadableStream<string> {
+ const { callId, provider } = this.params;
+ const signal = options.signal;
+ const diagnostics = this.createDiagnostics(options);
+ let output = '';
+ let sawUsage = false;
+ let settled = false;
+
+ const settle = async (cancelReason?: LlmCancelData['reason']) => {
+ if (settled) return;
+ settled = true;
+ if (cancelReason) await this.cancel(cancelReason);
+ await this.cleanup(reader);
+ };
+
+ return new ReadableStream<string>({
+ cancel: async () => {
+ await settle('superseded');
+ },
+
+ pull: async (controller) => {
+ try {
+ // A pull that enqueues nothing is not pulled again, so read past
+ // heartbeat batches here — returning on one would stall the stream
+ // and its deadlines with it.
+ for (;;) {
+ const next = await reader.next(signal);
+
+ if (next.kind === 'aborted') {
+ diagnostics.aborted = true;
+ await settle('interrupted');
+ return controller.error(createAbortError());
+ }
+
+ if (next.kind === 'timeout') {
+ log('[%s] relay deadline missed: %s', callId, next.which);
+ await settle('timeout');
+ return controller.error(this.toDeadlineError(next.which));
+ }
+
+ const { batch } = next;
+ for (const chunk of batch.chunks) {
+ diagnostics.eventCount += 1;
+ diagnostics.eventCounts[chunk.type] = (diagnostics.eventCounts[chunk.type] ?? 0) + 1;
+ diagnostics.firstEventAt ??= this.now();
+ if (chunk.type === 'usage') sawUsage = true;
+ if (
+ (chunk.type === 'text' || chunk.type === 'reasoning') &&
+ typeof chunk.data === 'string'
+ )
+ output += chunk.data;
+
+ for (const line of toSseLines(chunk)) controller.enqueue(line);
+ }
+
+ if (!batch.final) {
+ if (batch.chunks.length > 0) return;
+ continue;
+ }
+
+ diagnostics.terminalEventReceived = true;
+ switch (batch.final.reason) {
+ case 'done': {
+ if (!sawUsage) {
+ const usage = await estimateUsage(payload, output);
+ this.result.usageEstimated = true;
+ for (const line of toSseLines({ data: usage, type: 'usage' }))
+ controller.enqueue(line);
+ }
+ await settle();
+ return controller.close();
+ }
+ case 'error': {
+ // The device's provider failed: hand its normalized error to the
+ // pipeline like any provider stream error, so the retry policy
+ // classifies it by its own error type.
+ const error = batch.final.error ?? { message: 'The relayed LLM attempt failed' };
+ for (const line of toSseLines({ data: error, type: 'error' }))
+ controller.enqueue(line);
+ await settle();
+ return controller.close();
+ }
+ default: {
+ // The client ended the attempt without the server asking.
+ if (signal?.aborted) {
+ diagnostics.aborted = true;
+ await settle();
+ return controller.error(createAbortError());
+ }
+ await settle();
+ return controller.error(
+ createClientLlmExecutorLostError(provider, 'client_aborted'),
+ );
+ }
+ }
+ }
+ } catch (error) {
+ await settle('error');
+ controller.error(error);
+ }
+ },
+ });
+ }
+
+ private toDeadlineError(which: RelayDeadline) {
+ const { provider } = this.params;
+ switch (which) {
+ case 'claim': {
+ return createClientLlmExecutorUnavailableError(provider, 'claim_timeout');
+ }
+ case 'first_chunk': {
+ return createClientLlmTimeoutError(provider, 'first_chunk');
+ }
+ case 'total': {
+ return createClientLlmTimeoutError(provider, 'total');
+ }
+ default: {
+ return createClientLlmExecutorLostError(provider, which);
+ }
+ }
+ }
+
+ /**
+ * Tell the executor to stop: the flag answers its next upload with
+ * `cancel: true`, the event reaches it while it is between uploads.
+ */
+ private async cancel(reason: LlmCancelData['reason']) {
+ const { callId, operationId, redis, stepIndex, streamManager } = this.params;
+ try {
+ await redis.set(
+ llmRelayKeys.cancel(callId),
+ reason,
+ 'PX',
+ this.deadlines.totalMs + LLM_RELAY_KEY_GRACE_MS,
+ );
+ const data: LlmCancelData = { callId, reason };
+ await streamManager.publishStreamEvent(operationId, { data, stepIndex, type: 'llm_cancel' });
+ } catch (error) {
+ log('[%s] failed to cancel the relayed attempt: %O', callId, error);
+ }
+ }
+
+ /** Close the call: late uploads find no open call and get `410`. */
+ private async cleanup(reader?: RelayBatchReader) {
+ const { callId, redis } = this.params;
+ try {
+ await redis
+ .multi()
+ .del(llmRelayKeys.open(callId), llmRelayKeys.payload(callId))
+ .pexpire(llmRelayKeys.stream(callId), LLM_RELAY_KEY_GRACE_MS)
+ .exec();
+ } catch (error) {
+ log('[%s] failed to clean up relay keys: %O', callId, error);
+ }
+ reader?.close();
+ }
+
+ private createDiagnostics(options: ChatMethodOptions): ProviderResponseDiagnostics {
+ const diagnostics: ProviderResponseDiagnostics = {
+ apiMode: 'llm_relay',
+ droppedEventCount: 0,
+ eventCount: 0,
+ eventCounts: {},
+ events: [],
+ hasNonWhitespaceText: false,
+ hasNonWhitespaceThinking: false,
+ rawEvents: [],
+ signatureChars: 0,
+ terminalEventReceived: false,
+ textChars: 0,
+ thinkingChars: 0,
+ toolInputChars: 0,
+ toolUseCount: 0,
+ };
+ if (options.diagnostics) options.diagnostics.providerResponse = diagnostics;
+ return diagnostics;
+ }
+}
+
+/**
+ * Usage for a client that reported none (U4f): some OpenAI-compatible local
+ * servers ignore `stream_options.include_usage`. Rough token counts of the
+ * request messages and the streamed text; flagged as estimated on the message.
+ */
+const estimateUsage = async (payload: ChatStreamPayload, output: string): Promise<ModelUsage> => {
+ const inputTokens = await encodeAsync(JSON.stringify(payload.messages ?? []));
+ const outputTokens = await encodeAsync(output);
+
+ return {
+ inputTextTokens: inputTokens,
+ outputTextTokens: outputTokens,
+ totalInputTokens: inputTokens,
+ totalOutputTokens: outputTokens,
+ totalTokens: inputTokens + outputTokens,
+ };
+};
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
new file mode 100644
index 00000000000..4dfbb337455
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
@@ -0,0 +1,476 @@
+// @vitest-environment node
+import type { LlmCancelData, LlmExecuteData } from '@lobechat/agent-gateway-client';
+import { consumeStreamUntilDone } from '@lobechat/model-runtime';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { llmRelayChunks, llmRelayPayload } from '@/server/router-hono/agent/handlers/llmRelay';
+import { runWithInvocationDeadline } from '@/server/utils/invocationDeadline';
+
+import {
+ LLM_RELAY_INVOCATION_MARGIN_MS,
+ LLM_RELAY_LEASE_HEADER,
+ llmRelayKeys,
+ signLlmRelayLease,
+} from '../protocol';
+import { RelayModelRuntime } from '../RelayModelRuntime';
+import { FakeRedis } from './fakeRedis';
+
+let redis: FakeRedis;
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => redis,
+}));
+
+const USER_ID = 'user-1';
+const CALL_ID = 'op_1:0:g1:1';
+
+const payload = {
+ messages: [{ content: 'Say hello', role: 'user' as const }],
+ model: 'llama3',
+ stream: true,
+};
+
+/** The slice of a Hono Context the relay handlers read. */
+const buildContext = (
+ callId: string,
+ { body, lease, request }: { body?: unknown; lease?: string; request?: Request } = {},
+) => {
+ const raw = typeof body === 'string' ? body : JSON.stringify(body ?? {});
+ return {
+ body: (value: string, status: number, headers?: Record<string, string>) =>
+ new Response(value, { headers, status }),
+ json: (value: unknown, status = 200) => Response.json(value, { status }),
+ req: {
+ header: (name: string) => (name === LLM_RELAY_LEASE_HEADER ? lease : undefined),
+ param: (name: string) => (name === 'callId' ? callId : undefined),
+ raw: request ?? new Request('http://localhost/chunks', { body: raw, method: 'POST' }),
+ },
+ } as any;
+};
+
+const createStreamManager = () => {
+ const events: { data: any; type: string }[] = [];
+ return {
+ events,
+ manager: {
+ publishStreamEvent: vi.fn(async (_operationId: string, event: any) => {
+ events.push(event);
+ return 'event-id';
+ }),
+ } as any,
+ };
+};
+
+const createRuntime = (
+ streamManager: any,
+ deadlines = { claimMs: 2000, firstChunkMs: 2000, idleMs: 2000, totalMs: 5000 },
+) =>
+ new RelayModelRuntime({
+ assistantMessageId: 'msg_1',
+ attempt: 1,
+ callId: CALL_ID,
+ deadlines,
+ operationId: 'op_1',
+ preferredClientId: 'tab-a',
+ provider: 'ollama',
+ redis: redis as any,
+ runtimeProvider: 'ollama',
+ stepIndex: 0,
+ streamManager,
+ userId: USER_ID,
+ });
+
+/** Wait until the runtime has dispatched `llm_execute`, then return its data. */
+const waitForExecute = async (events: { data: any; type: string }[]) => {
+ await vi.waitFor(() => expect(events.some((e) => e.type === 'llm_execute')).toBe(true));
+ return events.find((e) => e.type === 'llm_execute')!.data as LlmExecuteData;
+};
+
+const post = (lease: string, body: unknown, callId = CALL_ID) =>
+ llmRelayChunks(buildContext(callId, { body, lease }));
+
+describe('RelayModelRuntime + llm-relay handlers', () => {
+ beforeEach(() => {
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+ redis = new FakeRedis();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('turns uploaded batches back into the server callback pipeline, in seq order and deduped', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+ const onText = vi.fn();
+ const onCompletion = vi.fn();
+
+ const done = runtime
+ .chat(payload, { callback: { onCompletion, onText } })
+ .then((response) => consumeStreamUntilDone(response));
+
+ const execute = await waitForExecute(events);
+ expect(execute).toMatchObject({
+ assistantMessageId: 'msg_1',
+ attempt: 1,
+ callId: CALL_ID,
+ model: 'llama3',
+ operationId: 'op_1',
+ preferredClientId: 'tab-a',
+ provider: 'ollama',
+ runtimeProvider: 'ollama',
+ });
+ // The event carries no messages; the device fetches the body with its lease.
+ expect(JSON.stringify(execute)).not.toContain('Say hello');
+
+ const payloadRes = await llmRelayPayload(buildContext(CALL_ID, { lease: execute.leaseToken }));
+ expect(payloadRes.status).toBe(200);
+ expect(await payloadRes.json()).toEqual(payload);
+
+ const usage = {
+ inputTextTokens: 5,
+ outputTextTokens: 2,
+ totalInputTokens: 5,
+ totalOutputTokens: 2,
+ totalTokens: 7,
+ };
+ // seq 2 arrives before seq 1, and seq 1 is re-sent
+ expect(
+ (
+ await post(execute.leaseToken, {
+ chunks: [{ data: ' world', type: 'text' }],
+ clientId: 'tab-a',
+ seq: 2,
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await post(execute.leaseToken, {
+ chunks: [{ data: 'Hello', type: 'text' }],
+ clientId: 'tab-a',
+ seq: 1,
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await post(execute.leaseToken, {
+ chunks: [{ data: 'Hello', type: 'text' }],
+ clientId: 'tab-a',
+ seq: 1,
+ })
+ ).status,
+ ).toBe(200);
+ const last = await post(execute.leaseToken, {
+ chunks: [{ data: usage, type: 'usage' }],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 3,
+ });
+ expect(await last.json()).toEqual({ ackSeq: 3 });
+
+ await done;
+
+ expect(onText.mock.calls.map(([text]) => text)).toEqual(['Hello', ' world']);
+ expect(onCompletion).toHaveBeenCalledWith(
+ expect.objectContaining({ text: 'Hello world', usage }),
+ );
+ expect(runtime.result.usageEstimated).toBe(false);
+ // The call is closed: no payload left, late uploads are told to stop.
+ expect(redis.peek(llmRelayKeys.payload(CALL_ID))).toBeUndefined();
+ const late = await post(execute.leaseToken, { chunks: [], clientId: 'tab-a', seq: 4 });
+ expect(late.status).toBe(410);
+ expect(await late.json()).toMatchObject({ cancel: true });
+ });
+
+ it('estimates usage when the device reports none', async () => {
+ const { events, manager } = createStreamManager();
+ const runtime = createRuntime(manager);
+ const onCompletion = vi.fn();
+
+ const done = runtime
+ .chat(payload, { callback: { onCompletion } })
+ .then((response) => consumeStreamUntilDone(response));
+ const { leaseToken } = await waitForExecute(events);
+
+ await post(leaseToken, {
+ chunks: [{ data: 'Hello there, how are you today?', type: 'text' }],
+ clientId: 'tab-a',
+ final: { reason: 'done' },
+ seq: 1,
+ });
+ await done;
+
+ expect(runtime.result.usageEstimated).toBe(true);
+ const { usage } = onCompletion.mock.calls[0][0];
+ expect(usage.totalOutputTokens).toBeGreaterThan(0);
+ expect(usage.totalInputTokens).toBeGreaterThan(0);
+ expect(usage.totalTokens).toBe(usage.totalInputTokens + usage.totalOutputTokens);
+ });
+
+ it('hands a device-side provider error to the pipeline as a stream error', async () => {
+ const { events, manager } = createStreamManager();
+ const onError = vi.fn();
+
+ const done = createRuntime(manager)
+ .chat(payload, { callback: { onError } })
+ .then((response) => consumeStreamUntilDone(response));
+ const { leaseToken } = await waitForExecute(events);
+
+ const error = { errorType: 'OllamaServiceUnavailable', message: 'connect ECONNREFUSED' };
+ await post(leaseToken, {
+ chunks: [],
+ clientId: 'tab-a',
+ final: { error, reason: 'error' },
+ seq: 1,
+ });
+ await done;
+
+ expect(onError).toHaveBeenCalledWith(error);
+ });
+
+ it('fails as ClientLlmExecutorUnavailable when nobody claims the call, and cancels it', async () => {
+ const { events, manager } = createStreamManager();
+ const response = await createRuntime(manager, {
+ claimMs: 30,
+ firstChunkMs: 1000,
+ idleMs: 1000,
+ totalMs: 2000,
+ }).chat(payload, {});
+
+ await expect(consumeStreamUntilDone(response)).rejects.toMatchObject({
+ error: { reason: 'claim_timeout', recoverable: true },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ provider: 'ollama',
+ });
+ const cancel = events.find((e) => e.type === 'llm_cancel')?.data as LlmCancelData;
+ expect(cancel).toEqual({ callId: CALL_ID, reason: 'timeout' });
+ expect(redis.peek(llmRelayKeys.cancel(CALL_ID))).toBe('timeout');
+ });
+
+ it('fails as ClientLlmExecutorLost when the executor goes silent mid-stream', async () => {
+ const { events, manager } = createStreamManager();
+ const response = await createRuntime(manager, {
+ claimMs: 1000,
+ firstChunkMs: 1000,
+ idleMs: 40,
+ totalMs: 2000,
+ }).chat(payload, {});
+ const { leaseToken } = await waitForExecute(events);
+ await post(leaseToken, { chunks: [{ data: 'Hel', type: 'text' }], clientId: 'tab-a', seq: 1 });
+
+ await expect(consumeStreamUntilDone(response)).rejects.toMatchObject({
+ error: { reason: 'idle' },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorLost,
+ });
+ });
+
+ it('fails as ClientLlmExecutorLost on a batch gap that never fills', async () => {
+ const { events, manager } = createStreamManager();
+ const response = await createRuntime(manager, {
+ claimMs: 1000,
+ firstChunkMs: 1000,
+ idleMs: 40,
+ totalMs: 2000,
+ }).chat(payload, {});
+ const { leaseToken } = await waitForExecute(events);
+ await post(leaseToken, { chunks: [{ data: 'a', type: 'text' }], clientId: 'tab-a', seq: 1 });
+ await post(leaseToken, { chunks: [{ data: 'c', type: 'text' }], clientId: 'tab-a', seq: 3 });
+
+ await expect(consumeStreamUntilDone(response)).rejects.toMatchObject({
+ error: { reason: 'gap' },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorLost,
+ });
+ });
+
+ it('fits the attempt into what is left of the invocation', async () => {
+ const { events, manager } = createStreamManager();
+ const killedAt = Date.now() + 100_000;
+ const response = await runWithInvocationDeadline(killedAt, () =>
+ createRuntime(manager, {
+ claimMs: 1000,
+ firstChunkMs: 1000,
+ idleMs: 1000,
+ totalMs: 540_000,
+ }).chat(payload, {}),
+ );
+
+ const { deadlines } = await waitForExecute(events);
+ // 100s left, minus the cleanup margin: the device is told to stop by then.
+ expect(deadlines.totalMs).toBeLessThanOrEqual(100_000 - LLM_RELAY_INVOCATION_MARGIN_MS);
+ expect(deadlines.totalMs).toBeGreaterThan(60_000);
+ await response.body?.cancel();
+ });
+
+ it('fails as ClientLlmTimeout(first_chunk) when only heartbeats arrive', async () => {
+ const { events, manager } = createStreamManager();
+ const response = await createRuntime(manager, {
+ claimMs: 1000,
+ firstChunkMs: 40,
+ idleMs: 1000,
+ totalMs: 2000,
+ }).chat(payload, {});
+ const { leaseToken } = await waitForExecute(events);
+ await post(leaseToken, { chunks: [], clientId: 'tab-a', seq: 1 });
+
+ await expect(consumeStreamUntilDone(response)).rejects.toMatchObject({
+ error: { stage: 'first_chunk' },
+ errorType: AgentRuntimeErrorType.ClientLlmTimeout,
+ });
+ });
+
+ it('stops on the step abort signal: aborts, tells the device to cancel, and closes the call', async () => {
+ const { events, manager } = createStreamManager();
+ const controller = new AbortController();
+ const diagnostics: any = {};
+ const onText = vi.fn();
+ const response = await createRuntime(manager).chat(payload, {
+ callback: { onText },
+ diagnostics,
+ signal: controller.signal,
+ });
+ const consumed = consumeStreamUntilDone(response);
+ const { leaseToken } = await waitForExecute(events);
+ await post(leaseToken, {
+ chunks: [{ data: 'partial', type: 'text' }],
+ clientId: 'tab-a',
+ seq: 1,
+ });
+ await vi.waitFor(() => expect(onText).toHaveBeenCalledWith('partial'));
+
+ controller.abort();
+
+ await expect(consumed).rejects.toMatchObject({ name: 'AbortError' });
+ expect(diagnostics.providerResponse.aborted).toBe(true);
+ expect(events.find((e) => e.type === 'llm_cancel')?.data).toEqual({
+ callId: CALL_ID,
+ reason: 'interrupted',
+ });
+ const late = await post(leaseToken, { chunks: [], clientId: 'tab-a', seq: 2 });
+ expect(late.status).toBe(410);
+ });
+
+ it('treats a client that ends the attempt on its own as a lost executor', async () => {
+ const { events, manager } = createStreamManager();
+ const response = await createRuntime(manager).chat(payload, {});
+ const { leaseToken } = await waitForExecute(events);
+ await post(leaseToken, { chunks: [], clientId: 'tab-a', final: { reason: 'aborted' }, seq: 1 });
+
+ await expect(consumeStreamUntilDone(response)).rejects.toMatchObject({
+ error: { reason: 'client_aborted' },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorLost,
+ });
+ });
+});
+
+describe('llm-relay upload handler', () => {
+ beforeEach(() => {
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+ redis = new FakeRedis();
+ void redis.set(llmRelayKeys.open(CALL_ID), USER_ID, 'PX', 60_000);
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ const lease = (overrides: Partial<{ callId: string; exp: number; userId: string }> = {}) =>
+ signLlmRelayLease({ callId: CALL_ID, exp: Date.now() + 60_000, userId: USER_ID, ...overrides });
+
+ it('rejects a missing, forged, expired or other-call lease with 401', async () => {
+ const batch = { chunks: [], clientId: 'tab-a', seq: 1 };
+ expect((await post(undefined as any, batch)).status).toBe(401);
+ expect((await post(`${lease()}x`, batch)).status).toBe(401);
+ expect((await post(lease({ exp: Date.now() - 1 }), batch)).status).toBe(401);
+ expect((await post(lease({ callId: 'op_1:0:g1:2' }), batch)).status).toBe(401);
+ expect(redis.peekStream(llmRelayKeys.stream(CALL_ID))).toHaveLength(0);
+ });
+
+ it("rejects a lease for another user's call with 403", async () => {
+ const res = await post(lease({ userId: 'user-2' }), { chunks: [], clientId: 'tab-a', seq: 1 });
+ expect(res.status).toBe(403);
+ });
+
+ it('lets only the first uploading client write the call (409 for the rest)', async () => {
+ expect((await post(lease(), { chunks: [], clientId: 'tab-a', seq: 1 })).status).toBe(200);
+
+ const rival = await post(lease(), {
+ chunks: [{ data: 'x', type: 'text' }],
+ clientId: 'tab-b',
+ seq: 2,
+ });
+ expect(rival.status).toBe(409);
+ expect(await rival.json()).toMatchObject({ cancel: true });
+ expect(redis.peekStream(llmRelayKeys.stream(CALL_ID))).toHaveLength(1);
+ });
+
+ it('rejects oversized batches with 413 and malformed ones with 400', async () => {
+ const big = {
+ chunks: [{ data: 'x'.repeat(300 * 1024), type: 'text' }],
+ clientId: 'tab-a',
+ seq: 1,
+ };
+ expect((await post(lease(), big)).status).toBe(413);
+ expect((await post(lease(), { chunks: 'nope', clientId: 'tab-a', seq: 1 })).status).toBe(400);
+ expect((await post(lease(), '{not json')).status).toBe(400);
+ });
+
+ /** A body stream of `count` 64 KB parts that records how many parts were read. */
+ const trackedRequest = (count: number, headers?: Record<string, string>) => {
+ let pulled = 0;
+ const part = new TextEncoder().encode('x'.repeat(64 * 1024));
+ const body = new ReadableStream<Uint8Array>(
+ {
+ pull(controller) {
+ if (pulled >= count) return controller.close();
+ pulled += 1;
+ controller.enqueue(part);
+ },
+ },
+ // pull only when the handler reads, so `pulled` counts real reads
+ { highWaterMark: 0 },
+ );
+ // undici requires `duplex` for a streamed request body
+ const request = new Request('http://localhost/chunks', {
+ body,
+ duplex: 'half',
+ headers,
+ method: 'POST',
+ } as RequestInit);
+ return { pulled: () => pulled, request };
+ };
+
+ it('never reads the body of an upload without a valid lease', async () => {
+ const { pulled, request } = trackedRequest(64);
+ const res = await llmRelayChunks(buildContext(CALL_ID, { lease: 'forged', request }));
+
+ expect(res.status).toBe(401);
+ expect(pulled()).toBe(0);
+ });
+
+ it('stops reading an oversized batch at the limit instead of buffering it whole', async () => {
+ // no content-length: the cap has to hold while streaming
+ const streamed = trackedRequest(64);
+ const res = await llmRelayChunks(
+ buildContext(CALL_ID, { lease: lease(), request: streamed.request }),
+ );
+ expect(res.status).toBe(413);
+ expect(streamed.pulled()).toBeLessThanOrEqual(6);
+
+ // a declared content-length over the cap is refused before any read
+ const declared = trackedRequest(64, { 'content-length': String(4 * 1024 * 1024) });
+ const declaredRes = await llmRelayChunks(
+ buildContext(CALL_ID, { lease: lease(), request: declared.request }),
+ );
+ expect(declaredRes.status).toBe(413);
+ expect(declared.pulled()).toBe(0);
+ });
+
+ it('answers cancel: true once the server gave up on the attempt', async () => {
+ await redis.set(llmRelayKeys.cancel(CALL_ID), 'interrupted');
+ const res = await post(lease(), { chunks: [], clientId: 'tab-a', seq: 1 });
+ expect(await res.json()).toEqual({ ackSeq: 1, cancel: true });
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/fakeRedis.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/fakeRedis.ts
new file mode 100644
index 00000000000..1fd2d82f7ec
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/fakeRedis.ts
@@ -0,0 +1,151 @@
+/**
+ * In-memory stand-in for the slice of ioredis the LLM relay uses (strings with
+ * PX/NX, counters, one Redis Stream per key, MULTI). One store is shared by
+ * every `duplicate()`, so the relay runtime and the upload handlers can run
+ * against the same "server" in a test.
+ */
+interface StreamEntry {
+ fields: string[];
+ id: string;
+}
+
+interface Store {
+ expiresAt: Map<string, number>;
+ seq: number;
+ streams: Map<string, StreamEntry[]>;
+ strings: Map<string, string>;
+}
+
+export class FakeRedis {
+ disconnected = false;
+
+ constructor(private readonly store: Store = createStore()) {}
+
+ duplicate() {
+ return new FakeRedis(this.store);
+ }
+
+ disconnect() {
+ this.disconnected = true;
+ }
+
+ async get(key: string) {
+ this.evict(key);
+ return this.store.strings.get(key) ?? null;
+ }
+
+ async set(key: string, value: string, ...args: (string | number)[]) {
+ this.evict(key);
+ if (args.includes('NX') && this.store.strings.has(key)) return null;
+ this.store.strings.set(key, value);
+ const px = args.indexOf('PX');
+ if (px !== -1) this.store.expiresAt.set(key, Date.now() + Number(args[px + 1]));
+ return 'OK';
+ }
+
+ async del(...keys: string[]) {
+ let removed = 0;
+ for (const key of keys) {
+ if (this.store.strings.delete(key) || this.store.streams.delete(key)) removed++;
+ this.store.expiresAt.delete(key);
+ }
+ return removed;
+ }
+
+ async pttl(key: string) {
+ this.evict(key);
+ if (!this.store.strings.has(key) && !this.store.streams.has(key)) return -2;
+ const expiresAt = this.store.expiresAt.get(key);
+ return expiresAt === undefined ? -1 : expiresAt - Date.now();
+ }
+
+ async pexpire(key: string, ms: number) {
+ this.store.expiresAt.set(key, Date.now() + ms);
+ return 1;
+ }
+
+ async incrby(key: string, by: number) {
+ const next = Number((await this.get(key)) ?? 0) + by;
+ this.store.strings.set(key, String(next));
+ return next;
+ }
+
+ async xadd(key: string, ...args: (string | number)[]) {
+ const star = args.indexOf('*');
+ const fields = args.slice(star + 1).map(String);
+ const id = `${++this.store.seq}-0`;
+ const entries = this.store.streams.get(key) ?? [];
+ entries.push({ fields, id });
+ this.store.streams.set(key, entries);
+ return id;
+ }
+
+ async xread(...args: (string | number)[]) {
+ const block = args.indexOf('BLOCK');
+ const streamsAt = args.indexOf('STREAMS');
+ const key = String(args[streamsAt + 1]);
+ const lastId = String(args[streamsAt + 2]);
+ const readNew = () =>
+ (this.store.streams.get(key) ?? []).filter((entry) => compareIds(entry.id, lastId) > 0);
+
+ let entries = readNew();
+ if (entries.length === 0 && block !== -1) {
+ await new Promise((resolve) => setTimeout(resolve, Math.min(Number(args[block + 1]), 5)));
+ entries = readNew();
+ }
+ if (entries.length === 0) return null;
+ return [[key, entries.map((entry) => [entry.id, entry.fields])]];
+ }
+
+ multi() {
+ const queued: (() => Promise<unknown>)[] = [];
+ const chain: any = new Proxy(
+ {},
+ {
+ get: (_target, property: string) => {
+ if (property === 'exec') {
+ return async () => {
+ const results: [null, unknown][] = [];
+ for (const run of queued) results.push([null, await run()]);
+ return results;
+ };
+ }
+ return (...args: unknown[]) => {
+ queued.push(() => (this as any)[property](...args));
+ return chain;
+ };
+ },
+ },
+ );
+ return chain;
+ }
+
+ /** Test helper: current value of a string key. */
+ peek(key: string) {
+ this.evict(key);
+ return this.store.strings.get(key);
+ }
+
+ /** Test helper: raw stream entries of a key. */
+ peekStream(key: string) {
+ return this.store.streams.get(key) ?? [];
+ }
+
+ private evict(key: string) {
+ const expiresAt = this.store.expiresAt.get(key);
+ if (expiresAt !== undefined && expiresAt <= Date.now()) {
+ this.store.strings.delete(key);
+ this.store.streams.delete(key);
+ this.store.expiresAt.delete(key);
+ }
+ }
+}
+
+const createStore = (): Store => ({
+ expiresAt: new Map(),
+ seq: 0,
+ streams: new Map(),
+ strings: new Map(),
+});
+
+const compareIds = (a: string, b: string) => Number(a.split('-')[0]) - Number(b.split('-')[0]);
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
new file mode 100644
index 00000000000..5acea26bba2
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
@@ -0,0 +1,123 @@
+// @vitest-environment node
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+import { resolveLlmExecutionSite } from '../resolveLlmExecutionSite';
+
+const providerRow = vi.hoisted(() => ({ current: undefined as any }));
+const getAiProviderById = vi.hoisted(() => vi.fn(async () => providerRow.current));
+
+vi.mock('@/database/models/aiProvider', () => ({
+ AiProviderModel: vi.fn(function (this: any) {
+ this.getAiProviderById = getAiProviderById;
+ }),
+}));
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(),
+}));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { getUserKeyVaults: vi.fn() },
+}));
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ resolveRuntimeProvider: (provider: string, sdkType?: string) =>
+ ['ollama', 'lmstudio', 'openai'].includes(provider) ? provider : sdkType || 'openai',
+}));
+const executor = (providers: string[]) => ({
+ host: {
+ llmExecutor: { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers },
+ },
+});
+
+const resolve = (provider: string, state?: any) =>
+ resolveLlmExecutionSite({ db: {} as any, provider, state, userId: 'user-1' });
+
+describe('resolveLlmExecutionSite', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ providerRow.current = { fetchOnClient: undefined, keyVaults: {} };
+ vi.mocked(getServerFeatureFlagsStateFromRuntimeConfig).mockResolvedValue({
+ enableLlmRelay: true,
+ } as any);
+ });
+
+ it('keeps every call on the server while the relay is off for the user', async () => {
+ vi.mocked(getServerFeatureFlagsStateFromRuntimeConfig).mockResolvedValue({
+ enableLlmRelay: false,
+ } as any);
+
+ expect(await resolve('ollama', executor(['ollama']))).toEqual({ site: 'server' });
+ expect(getAiProviderById).not.toHaveBeenCalled();
+ });
+
+ it('never relays the platform provider or a shared-agent visitor run', async () => {
+ expect(await resolve('lobehub', executor(['lobehub']))).toEqual({ site: 'server' });
+ expect(
+ await resolve('ollama', {
+ ...executor(['ollama']),
+ principal: { actor: { shareVisitor: { visitorUserId: 'v' } } },
+ }),
+ ).toEqual({ site: 'server' });
+ });
+
+ it('relays Ollama (fetchOnClient by default) to the client that declared it', async () => {
+ expect(await resolve('ollama', executor(['ollama']))).toEqual({
+ preferredClientId: 'tab-a',
+ runtimeProvider: 'ollama',
+ site: 'client',
+ });
+ });
+
+ it('reports unavailable when no client declared it can run the provider', async () => {
+ expect(await resolve('ollama')).toEqual({ reason: 'no_executor', site: 'unavailable' });
+ expect(await resolve('ollama', executor(['lmstudio']))).toEqual({
+ reason: 'no_executor',
+ site: 'unavailable',
+ });
+ expect(
+ await resolve('ollama', {
+ host: {
+ llmExecutor: { capabilities: ['llm_relay@9'], clientId: 'tab-a', providers: ['ollama'] },
+ },
+ }),
+ ).toEqual({ reason: 'no_executor', site: 'unavailable' });
+ });
+
+ it('follows an explicit fetchOnClient: false for a provider that defaults to the client', async () => {
+ providerRow.current = { fetchOnClient: false, keyVaults: {} };
+ expect(await resolve('ollama', executor(['ollama']))).toEqual({ site: 'server' });
+ });
+
+ it('keeps Ollama on the server when the deployment proxies it (OLLAMA_PROXY_URL)', async () => {
+ vi.stubEnv('OLLAMA_PROXY_URL', 'http://ollama.internal:11434');
+ try {
+ expect(await resolve('ollama', executor(['ollama']))).toEqual({ site: 'server' });
+
+ providerRow.current = { fetchOnClient: true, keyVaults: {} };
+ expect(await resolve('ollama', executor(['ollama']))).toMatchObject({ site: 'client' });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it('relays a custom provider with client requests enabled, with its sdkType', async () => {
+ providerRow.current = {
+ fetchOnClient: true,
+ keyVaults: { apiKey: 'sk-local', baseURL: 'http://127.0.0.1:1234/v1' },
+ settings: { sdkType: 'openai' },
+ };
+
+ expect(await resolve('my-local-llm', executor(['my-local-llm']))).toEqual({
+ preferredClientId: 'tab-a',
+ runtimeProvider: 'openai',
+ site: 'client',
+ });
+ });
+
+ it('keeps a provider without client requests on the server, whatever its endpoint', async () => {
+ providerRow.current = { fetchOnClient: false, keyVaults: { baseURL: 'http://127.0.0.1:1234/v1' } };
+
+ expect(await resolve('my-local-llm', executor(['my-local-llm']))).toEqual({ site: 'server' });
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/errors.ts b/apps/server/src/modules/AgentRuntime/llmRelay/errors.ts
new file mode 100644
index 00000000000..eb9672a6201
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/errors.ts
@@ -0,0 +1,89 @@
+import { AgentRuntimeError } from '@lobechat/model-runtime';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+/**
+ * Errors of a relayed LLM attempt, shaped like every other provider error
+ * (`AgentRuntimeError.chat`) so the retry classifier and the error card read
+ * them the same way. Retry budgets for the retryable ones live in
+ * `resolveLlmRelayRetryBudget`.
+ */
+
+export type ClientLlmUnavailableReason =
+ /** The run has no client that declared it can execute this provider. */
+ | 'no_executor'
+ /** An executor was asked, but no batch arrived within `claimMs`. */
+ | 'claim_timeout'
+ /** The deployment cannot relay (no Redis / gateway). */
+ | 'relay_unsupported';
+
+export type ClientLlmTimeoutStage = 'first_chunk' | 'total';
+
+export type ClientLlmLostReason =
+ /** No batch within `idleMs`. */
+ | 'idle'
+ /** A batch went missing and was not re-sent within `idleMs`. */
+ | 'gap'
+ /** The client ended the attempt itself without the server asking. */
+ | 'client_aborted';
+
+export const createClientLlmExecutorUnavailableError = (
+ provider: string,
+ reason: ClientLlmUnavailableReason,
+) =>
+ AgentRuntimeError.chat({
+ error: { reason, recoverable: true },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ provider,
+ });
+
+export const createClientLlmTimeoutError = (provider: string, stage: ClientLlmTimeoutStage) =>
+ AgentRuntimeError.chat({
+ error: { stage },
+ errorType: AgentRuntimeErrorType.ClientLlmTimeout,
+ provider,
+ });
+
+export const createClientLlmExecutorLostError = (provider: string, reason: ClientLlmLostReason) =>
+ AgentRuntimeError.chat({
+ error: { reason },
+ errorType: AgentRuntimeErrorType.ClientLlmExecutorLost,
+ provider,
+ });
+
+const getErrorType = (error: unknown) =>
+ error && typeof error === 'object' ? (error as { errorType?: unknown }).errorType : undefined;
+
+const getErrorDetail = (error: unknown) =>
+ error && typeof error === 'object'
+ ? ((error as { error?: Record<string, unknown> }).error ?? {})
+ : {};
+
+export const isClientLlmRelayError = (error: unknown) => {
+ const errorType = getErrorType(error);
+ return (
+ errorType === AgentRuntimeErrorType.ClientLlmExecutorUnavailable ||
+ errorType === AgentRuntimeErrorType.ClientLlmExecutorLost ||
+ errorType === AgentRuntimeErrorType.ClientLlmTimeout
+ );
+};
+
+/**
+ * Retries a relay failure may take (U4b): a lost executor is re-dispatched as a
+ * fresh attempt (new `callId`) up to twice, a missed first chunk once. A missed
+ * total deadline is not retried — the step has no budget left for another
+ * attempt — and neither is an unavailable executor: nobody would pick it up.
+ * `undefined` for errors that are not relay failures.
+ */
+export const resolveLlmRelayRetryBudget = (error: unknown): number | undefined => {
+ switch (getErrorType(error)) {
+ case AgentRuntimeErrorType.ClientLlmExecutorLost: {
+ return 2;
+ }
+ case AgentRuntimeErrorType.ClientLlmTimeout: {
+ return getErrorDetail(error).stage === 'first_chunk' ? 1 : 0;
+ }
+ case AgentRuntimeErrorType.ClientLlmExecutorUnavailable: {
+ return 0;
+ }
+ }
+};
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts
new file mode 100644
index 00000000000..387258b4a6c
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/protocol.ts
@@ -0,0 +1,145 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+import type { LlmRelayDeadlines } from '@lobechat/agent-gateway-client';
+
+/**
+ * Shared constants and keys of the LLM relay: a server-driven agent loop hands
+ * one LLM attempt to the user's device (`llm_execute`), and the device uploads
+ * the attempt's protocol chunks back in batches over HTTP.
+ *
+ * Redis layout, all keyed by the attempt's `callId`:
+ * - `llm_relay:payload:{callId}` the request body the device fetches once
+ * - `llm_relay:open:{callId}` owning user id; present while the attempt runs
+ * - `llm_relay:lease:{callId}` client id that claimed the call (SET NX)
+ * - `llm_relay:bytes:{callId}` total uploaded bytes, for the per-call cap
+ * - `llm_relay:cancel:{callId}` the server no longer wants the attempt
+ * - `llm_relay:stream:{callId}` Redis Stream of uploaded batches (`seq`, `body`)
+ */
+
+export const LLM_RELAY_CAPABILITY = 'llm_relay@1';
+
+export const LLM_RELAY_LEASE_HEADER = 'x-llm-relay-lease';
+
+/** Upper bound of the whole attempt; keeps it inside a 600s step invocation. */
+const MAX_TOTAL_MS = 540_000;
+
+export const DEFAULT_LLM_RELAY_DEADLINES: LlmRelayDeadlines = {
+ claimMs: 15_000,
+ // Local models can take tens of seconds to load on the first request.
+ firstChunkMs: 120_000,
+ idleMs: 60_000,
+ totalMs: MAX_TOTAL_MS,
+};
+
+/**
+ * Room left before the invocation's kill time for cancelling and cleaning up
+ * an attempt that hit its total deadline.
+ */
+export const LLM_RELAY_INVOCATION_MARGIN_MS = 30_000;
+
+/** Shortest total deadline an attempt gets, however little budget is left. */
+const MIN_TOTAL_MS = 15_000;
+
+/**
+ * The attempt's deadlines within what is left of the invocation: a step the
+ * inline loop starts late cannot wait the full `totalMs`, or the host kills
+ * the worker before it cancels the call and the device keeps generating.
+ */
+export const fitLlmRelayDeadlines = (
+ deadlines: LlmRelayDeadlines,
+ invocationDeadlineAt: number | undefined,
+ now = Date.now(),
+): LlmRelayDeadlines => {
+ if (invocationDeadlineAt === undefined) return deadlines;
+
+ const remaining = invocationDeadlineAt - now - LLM_RELAY_INVOCATION_MARGIN_MS;
+ const totalMs = Math.min(deadlines.totalMs, Math.max(MIN_TOTAL_MS, remaining));
+ return totalMs === deadlines.totalMs ? deadlines : { ...deadlines, totalMs };
+};
+
+/** Single uploaded batch, in bytes of the raw request body. */
+export const LLM_RELAY_MAX_BATCH_BYTES = 256 * 1024;
+
+/** Everything uploaded for one call. */
+export const LLM_RELAY_MAX_CALL_BYTES = 16 * 1024 * 1024;
+
+/** Batches kept in the stream; far above what one attempt produces at 5 batches/s. */
+export const LLM_RELAY_STREAM_MAXLEN = 5000;
+
+/** Keys outlive the attempt by this much, so late uploads get a clean `410`. */
+export const LLM_RELAY_KEY_GRACE_MS = 60_000;
+
+export const llmRelayKeys = {
+ bytes: (callId: string) => `llm_relay:bytes:${callId}`,
+ cancel: (callId: string) => `llm_relay:cancel:${callId}`,
+ lease: (callId: string) => `llm_relay:lease:${callId}`,
+ open: (callId: string) => `llm_relay:open:${callId}`,
+ payload: (callId: string) => `llm_relay:payload:${callId}`,
+ stream: (callId: string) => `llm_relay:stream:${callId}`,
+};
+
+/**
+ * `generation` is a nonce per step execution: a step the queue redrives after
+ * its worker died reruns with the same `operationId`/`stepIndex` and attempt
+ * numbers, and must not reuse the dead execution's lease, stream or cancel keys.
+ */
+export const buildLlmRelayCallId = (
+ operationId: string,
+ stepIndex: number,
+ generation: string,
+ attempt: number,
+) => `${operationId}:${stepIndex}:${generation}:${attempt}`;
+
+// ─── Lease token ───
+
+/**
+ * The lease token is the capability for one call's relay endpoints. It only
+ * travels in the `llm_execute` event, which reaches the run owner's own
+ * authenticated gateway subscriptions, so holding it proves the uploader is
+ * one of that user's clients. It is bound to the call and the user and expires
+ * with the attempt; which of the user's clients executes is settled by the
+ * first upload claiming the call (`llm_relay:lease:{callId}`).
+ */
+interface LeaseClaims {
+ callId: string;
+ exp: number;
+ userId: string;
+}
+
+const getLeaseSecret = () => {
+ const secret = process.env.KEY_VAULTS_SECRET;
+ if (!secret) throw new Error('KEY_VAULTS_SECRET is required to sign LLM relay leases');
+ return secret;
+};
+
+const sign = (body: string) =>
+ createHmac('sha256', getLeaseSecret()).update(`llm-relay-lease:${body}`).digest('base64url');
+
+export const signLlmRelayLease = (claims: LeaseClaims) => {
+ const body = Buffer.from(JSON.stringify(claims)).toString('base64url');
+ return `${body}.${sign(body)}`;
+};
+
+export const verifyLlmRelayLease = (
+ token: string | undefined | null,
+ callId: string,
+ now = Date.now(),
+): LeaseClaims | undefined => {
+ if (!token) return;
+
+ const [body, signature] = token.split('.');
+ if (!body || !signature) return;
+
+ const expected = Buffer.from(sign(body));
+ const actual = Buffer.from(signature);
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
+
+ try {
+ const claims = JSON.parse(Buffer.from(body, 'base64url').toString()) as LeaseClaims;
+ if (claims.callId !== callId || typeof claims.userId !== 'string') return;
+ if (typeof claims.exp !== 'number' || claims.exp < now) return;
+ return claims;
+ } catch {
+ return;
+ }
+};
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
new file mode 100644
index 00000000000..dfbe7ce3974
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
@@ -0,0 +1,94 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import { DEFAULT_LLM_CONFIG } from '@lobechat/business-config';
+import { BRANDING_PROVIDER } from '@lobechat/business-const';
+import debug from 'debug';
+import { ModelProvider } from 'model-bank';
+
+import { AiProviderModel } from '@/database/models/aiProvider';
+import type { LobeChatDatabase } from '@/database/type';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+import { getServerFetchOnClientOverride } from '@/server/globalConfig/serverFetchOnClient';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { resolveRuntimeProvider } from '@/server/modules/ModelRuntime';
+
+import type { ClientLlmUnavailableReason } from './errors';
+import { LLM_RELAY_CAPABILITY } from './protocol';
+
+const log = debug('lobe-server:agent-runtime:llm-relay:site');
+
+export type LlmExecutionSite =
+ | { site: 'server' }
+ | { preferredClientId: string; runtimeProvider: string; site: 'client' }
+ | { reason: ClientLlmUnavailableReason; site: 'unavailable' };
+
+export interface ResolveLlmExecutionSiteParams {
+ db: LobeChatDatabase;
+ provider: string;
+ state?: Pick<AgentState, 'host' | 'principal'>;
+ userId: string;
+ workspaceId?: string;
+}
+
+const SERVER: LlmExecutionSite = { site: 'server' };
+
+/**
+ * `fetchOnClient` as the client store reads it: the user's choice when they
+ * made one, else this deployment's override from the server global config
+ * (desktop, `OLLAMA_PROXY_URL`), else the provider default (Ollama / LM Studio
+ * / Unsloth ship with `fetchOnClient: true`).
+ */
+const resolveFetchOnClient = (provider: string, stored: boolean | undefined) =>
+ stored ??
+ getServerFetchOnClientOverride(provider) ??
+ (DEFAULT_LLM_CONFIG as Record<string, { fetchOnClient?: boolean } | undefined>)[provider]
+ ?.fetchOnClient;
+
+/**
+ * Where one LLM call of a run executes (T-540 §2.1). The server is the
+ * authority — the client only declares that it *can* execute
+ * (`state.host.llmExecutor`).
+ *
+ * - `server`: the default. Also kept when the relay is off for this user, for
+ * platform-owned providers (their credentials never go to a client), and for
+ * shared-agent visitor runs (the creator's provider config is not the
+ * visitor's to run).
+ * - `client`: the provider is one only the user's device can reach — it runs
+ * with client requests (`fetchOnClient`) — and the run's client declared it
+ * can execute that provider.
+ * - `unavailable`: such a provider, but no client to execute it.
+ */
+export const resolveLlmExecutionSite = async ({
+ db,
+ provider,
+ state,
+ userId,
+ workspaceId,
+}: ResolveLlmExecutionSiteParams): Promise<LlmExecutionSite> => {
+ if (provider === BRANDING_PROVIDER || provider === ModelProvider.LobeHub) return SERVER;
+ if (state?.principal?.actor?.shareVisitor) return SERVER;
+
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
+ if (!featureFlags.enableLlmRelay) return SERVER;
+
+ const config = await new AiProviderModel(db, userId, workspaceId).getAiProviderById(
+ provider,
+ KeyVaultsGateKeeper.getUserKeyVaults,
+ );
+ const fetchOnClient = resolveFetchOnClient(provider, config?.fetchOnClient) === true;
+
+ log('provider=%s fetchOnClient=%s', provider, fetchOnClient);
+ if (!fetchOnClient) return SERVER;
+
+ const executor = state?.host?.llmExecutor;
+ const canExecute =
+ !!executor?.clientId &&
+ executor.capabilities.includes(LLM_RELAY_CAPABILITY) &&
+ executor.providers.includes(provider);
+ if (!canExecute) return { reason: 'no_executor', site: 'unavailable' };
+
+ return {
+ preferredClientId: executor.clientId,
+ runtimeProvider: resolveRuntimeProvider(provider, config?.settings?.sdkType),
+ site: 'client',
+ };
+};
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index 95f0949c5c4..aec891ab436 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -73,7 +73,7 @@ type ProviderKeyVaults = OpenAICompatibleKeyVault &
* @param sdkType - The sdkType from provider settings
* @returns The resolved runtime provider
*/
-const resolveRuntimeProvider = (provider: string, sdkType?: string): string => {
+export const resolveRuntimeProvider = (provider: string, sdkType?: string): string => {
const isBuiltin = Object.values(ModelProvider).includes(provider as ModelProvider);
if (isBuiltin) return provider;
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
index 5a0b57f3bef..d514ea9492b 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
@@ -2,6 +2,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '@/server/services/aiAgent';
+import { getInvocationDeadline } from '@/server/utils/invocationDeadline';
import type * as ScheduleAfterResponseModule from '@/server/utils/scheduleAfterResponse';
import { after } from '@/server/utils/scheduleAfterResponse';
@@ -332,6 +333,27 @@ describe('runStep handler', () => {
);
});
+ it('runs its steps knowing when the invocation is killed', async () => {
+ mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
+ let deadlineSeen: number | undefined;
+ mockExecuteStep.mockImplementation(async () => {
+ deadlineSeen = getInvocationDeadline();
+ return {
+ nextStepScheduled: false,
+ state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
+ success: true,
+ };
+ });
+ const startedAt = Date.now();
+
+ const { ctx } = buildContext({ body: validBody });
+ await runStep(ctx);
+
+ // The route's 600s maxDuration, counted from the request.
+ expect(deadlineSeen).toBeGreaterThanOrEqual(startedAt + 600_000);
+ expect(deadlineSeen).toBeLessThanOrEqual(Date.now() + 600_000);
+ });
+
it('opts the AiAgentService into visitor rows when metadata carries streamOwnerUserId', async () => {
// A shared-agent visitor run: the op executes as the creator `userId`
// (`user-owner`) but the visitor (`visitor-1`) owns the stream. The step
diff --git a/apps/server/src/router-hono/agent/handlers/llmRelay.ts b/apps/server/src/router-hono/agent/handlers/llmRelay.ts
new file mode 100644
index 00000000000..5fbb4a103e7
--- /dev/null
+++ b/apps/server/src/router-hono/agent/handlers/llmRelay.ts
@@ -0,0 +1,162 @@
+import type { LlmRelayBatchAck } from '@lobechat/agent-gateway-client';
+import debug from 'debug';
+import type { Context } from 'hono';
+import type Redis from 'ioredis';
+import { z } from 'zod';
+
+import {
+ LLM_RELAY_KEY_GRACE_MS,
+ LLM_RELAY_LEASE_HEADER,
+ LLM_RELAY_MAX_BATCH_BYTES,
+ LLM_RELAY_MAX_CALL_BYTES,
+ LLM_RELAY_STREAM_MAXLEN,
+ llmRelayKeys,
+ verifyLlmRelayLease,
+} from '@/server/modules/AgentRuntime/llmRelay/protocol';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+const log = debug('lobe-server:agent:llm-relay');
+
+const BatchSchema = z.object({
+ chunks: z.array(z.object({ data: z.unknown(), id: z.string().optional(), type: z.string() })),
+ clientId: z.string().min(1),
+ final: z
+ .object({
+ error: z.unknown().optional(),
+ reason: z.enum(['aborted', 'done', 'error']),
+ })
+ .optional(),
+ seq: z.number().int().positive(),
+});
+
+/**
+ * Authorize a relay request: the lease token from `llm_execute` must name this
+ * call, and the call must still be open for the token's user. A closed call
+ * answers `410` so a late executor stops instead of retrying.
+ */
+type Authorized = { callId: string; redis: Redis } | { response: Response };
+
+const authorize = async (c: Context): Promise<Authorized> => {
+ const callId = c.req.param('callId');
+ if (!callId) return { response: c.json({ error: 'Missing callId' }, 400) };
+
+ const claims = verifyLlmRelayLease(c.req.header(LLM_RELAY_LEASE_HEADER), callId);
+ if (!claims) return { response: c.json({ error: 'Invalid or expired lease' }, 401) };
+
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return { response: c.json({ error: 'Redis unavailable' }, 503) };
+
+ const owner = await redis.get(llmRelayKeys.open(callId));
+ if (!owner) return { response: c.json({ cancel: true, error: 'Call is closed' }, 410) };
+ if (owner !== claims.userId) return { response: c.json({ error: 'Forbidden' }, 403) };
+
+ return { callId, redis };
+};
+
+/**
+ * Read a request body as text, giving up once it passes `limit` bytes — by the
+ * declared `content-length` up front, else while streaming — so an oversized
+ * upload is never buffered in full. `undefined` means the body was too large.
+ */
+const readBodyWithin = async (req: Request, limit: number): Promise<string | undefined> => {
+ if (Number(req.headers.get('content-length')) > limit) return undefined;
+ if (!req.body) return '';
+
+ const reader = req.body.getReader();
+ const parts: Uint8Array[] = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > limit) {
+ await reader.cancel();
+ return undefined;
+ }
+ parts.push(value);
+ }
+ return Buffer.concat(parts).toString('utf8');
+};
+
+/**
+ * `GET /api/agent/llm-relay/:callId/payload` — the request body of a relayed
+ * LLM attempt (messages, tools, model parameters), exactly as the server would
+ * have sent it to the provider. Kept out of the `llm_execute` event so large
+ * contexts never ride the gateway socket.
+ */
+export async function llmRelayPayload(c: Context): Promise<Response> {
+ const auth = await authorize(c);
+ if ('response' in auth) return auth.response;
+
+ const payload = await auth.redis.get(llmRelayKeys.payload(auth.callId));
+ if (!payload) return c.json({ cancel: true, error: 'Call is closed' }, 410);
+
+ return c.body(payload, 200, { 'content-type': 'application/json' });
+}
+
+/**
+ * `POST /api/agent/llm-relay/:callId/chunks` — one batch of a relayed attempt's
+ * protocol chunks. Only validates and appends to the call's Redis Stream; the
+ * attempt running in the agent step reads, reorders and dedupes by `seq`.
+ *
+ * - the first batch claims the call for its client (`SET NX`); any other
+ * client gets `409` and must drop its local output
+ * - `413` past 256 KB per batch or 16 MB per call; the attempt then fails on
+ * its idle deadline. The lease is checked first and the batch limit is
+ * enforced while reading, so an unauthorized or oversized body is never
+ * buffered whole
+ * - the reply carries `cancel: true` once the server no longer wants the attempt
+ */
+export async function llmRelayChunks(c: Context): Promise<Response> {
+ // Authorize from the headers before touching the body, so a caller without
+ // a valid lease can never make the server buffer anything.
+ const auth = await authorize(c);
+ if ('response' in auth) return auth.response;
+ const { callId, redis } = auth;
+
+ const raw = await readBodyWithin(c.req.raw, LLM_RELAY_MAX_BATCH_BYTES);
+ if (raw === undefined) return c.json({ error: 'Batch too large' }, 413);
+
+ let parsed;
+ try {
+ parsed = BatchSchema.safeParse(JSON.parse(raw));
+ } catch {
+ return c.json({ error: 'Invalid JSON' }, 400);
+ }
+ if (!parsed.success) return c.json({ error: 'Invalid body', issues: parsed.error.issues }, 400);
+
+ const { clientId, ...batch } = parsed.data;
+ const ttlMs = Math.max(await redis.pttl(llmRelayKeys.open(callId)), 0) + LLM_RELAY_KEY_GRACE_MS;
+
+ await redis.set(llmRelayKeys.lease(callId), clientId, 'PX', ttlMs, 'NX');
+ const holder = await redis.get(llmRelayKeys.lease(callId));
+ if (holder !== clientId) {
+ log('[%s] batch %d from %s rejected: claimed by %s', callId, batch.seq, clientId, holder);
+ return c.json({ cancel: true, error: 'Call claimed by another client' }, 409);
+ }
+
+ const body = JSON.stringify(batch);
+ const total = await redis.incrby(llmRelayKeys.bytes(callId), Buffer.byteLength(body));
+ await redis.pexpire(llmRelayKeys.bytes(callId), ttlMs);
+ if (total > LLM_RELAY_MAX_CALL_BYTES) return c.json({ error: 'Call output too large' }, 413);
+
+ const [[, cancelled]] = (await redis
+ .multi()
+ .get(llmRelayKeys.cancel(callId))
+ .xadd(
+ llmRelayKeys.stream(callId),
+ 'MAXLEN',
+ '~',
+ LLM_RELAY_STREAM_MAXLEN,
+ '*',
+ 'seq',
+ String(batch.seq),
+ 'body',
+ body,
+ )
+ .pexpire(llmRelayKeys.stream(callId), ttlMs)
+ .exec()) as [[Error | null, string | null], ...unknown[]];
+
+ const ack: LlmRelayBatchAck = { ackSeq: batch.seq, ...(cancelled && { cancel: true }) };
+ return c.json(ack);
+}
diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.ts
index 913c810e74d..c8b45cac0ee 100644
--- a/apps/server/src/router-hono/agent/handlers/runStep.ts
+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts
@@ -12,6 +12,7 @@ import {
type AgentStepContinuation,
} from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
+import { runWithInvocationDeadline } from '@/server/utils/invocationDeadline';
import {
flushScheduledWork,
runWithScheduledWorkScope,
@@ -58,6 +59,12 @@ const INLINE_STEP_START_DEADLINE_MS = Number(process.env.AGENT_INLINE_STEP_DEADL
*/
const STEP_BOUNDARY_FLUSH_TIMEOUT_MS = 10_000;
+/**
+ * The route's `maxDuration`: when the host kills this invocation, counted from
+ * the start of the request.
+ */
+const STEP_INVOCATION_MAX_DURATION_MS = 600_000;
+
const toIsoString = (value: Date | string | null | undefined): null | string => {
if (!value) return null;
if (value instanceof Date) return value.toISOString();
@@ -313,116 +320,120 @@ export async function runStep(c: Context): Promise<Response> {
// reserved until the loop ends and squeeze the next reservation. Scoping
// it to the loop starts that work immediately and lets each boundary wait
// for it, which is how it behaved when every step was its own request.
- await runWithScheduledWorkScope(async () => {
- // The first iteration carries this delivery's one-shot payload (human
- // input, approvals, resume flags). Later iterations are plain steps, so
- // they must not replay any of it, and neither must a resumed run — it
- // stands in for a later iteration of a dead loop, not for the original
- // message.
- //
- // `externalRetryCount` is the exception, because it describes this
- // delivery rather than the step's payload. A parked approval whose Review
- // failed to persist is only replayed when the count is nonzero, so
- // dropping it here would leave that approval permanently unavailable.
- result = resumeFrom
- ? await aiAgentService.executeStep({
- context: resumeFrom.context,
- externalRetryCount,
- inlineContinuation: true,
- operationId,
- retainStepLock: true,
- stepIndex: resumeFrom.stepIndex,
- stepLockOwner,
- })
- : await aiAgentService.executeStep({
- approvedToolCall,
- asyncToolVerifyAttempt,
- context,
- externalRetryCount,
- finishAfterAsyncTool,
- groupMemberTimeout,
- humanInput,
+ // Long waits inside a step (a relayed LLM attempt) size themselves to
+ // what is left of this invocation.
+ await runWithInvocationDeadline(startTime + STEP_INVOCATION_MAX_DURATION_MS, () =>
+ runWithScheduledWorkScope(async () => {
+ // The first iteration carries this delivery's one-shot payload (human
+ // input, approvals, resume flags). Later iterations are plain steps, so
+ // they must not replay any of it, and neither must a resumed run — it
+ // stands in for a later iteration of a dead loop, not for the original
+ // message.
+ //
+ // `externalRetryCount` is the exception, because it describes this
+ // delivery rather than the step's payload. A parked approval whose Review
+ // failed to persist is only replayed when the count is nonzero, so
+ // dropping it here would leave that approval permanently unavailable.
+ result = resumeFrom
+ ? await aiAgentService.executeStep({
+ context: resumeFrom.context,
+ externalRetryCount,
+ inlineContinuation: true,
+ operationId,
+ retainStepLock: true,
+ stepIndex: resumeFrom.stepIndex,
+ stepLockOwner,
+ })
+ : await aiAgentService.executeStep({
+ approvedToolCall,
+ asyncToolVerifyAttempt,
+ context,
+ externalRetryCount,
+ finishAfterAsyncTool,
+ groupMemberTimeout,
+ humanInput,
+ inlineContinuation: true,
+ lockRetryAttempt,
+ operationId,
+ rejectAndContinue,
+ rejectionReason,
+ resumeAsyncTool,
+ retainStepLock: true,
+ stepIndex,
+ stepLockOwner,
+ toolMessageId,
+ verifyAsyncToolBarrier,
+ });
+ pendingContinuation = result.continuation;
+ touchedEnvelope ||= Boolean(pendingContinuation);
+
+ while (pendingContinuation) {
+ // Let the previous step's deferred work finish first. Its budget
+ // hold is released there, and the next step reserves again.
+ const settled = await flushScheduledWork({ timeoutMs: STEP_BOUNDARY_FLUSH_TIMEOUT_MS });
+ if (!settled) {
+ // The deferred work cannot be told apart, so a slow telemetry call
+ // and a slow budget settlement look the same. Reserving again on
+ // top of an unreleased hold is exactly the false "over budget"
+ // this wait exists to prevent, so stop inlining and hand the step
+ // to the queue, the way it ran before steps were inlined.
+ log(
+ `[${operationId}] Deferred work still running after ${STEP_BOUNDARY_FLUSH_TIMEOUT_MS}ms, handing step ${pendingContinuation.stepIndex} back to the queue`,
+ );
+ break;
+ }
+
+ const elapsed = Date.now() - startTime;
+ if (elapsed >= INLINE_STEP_START_DEADLINE_MS) {
+ log(
+ `[${operationId}] Inline budget spent after ${inlinedSteps} extra step(s) (${elapsed}ms), handing step ${pendingContinuation.stepIndex} back to the queue`,
+ );
+ break;
+ }
+
+ const next = pendingContinuation;
+ pendingContinuation = undefined;
+ currentStepIndex = next.stepIndex;
+
+ result = await aiAgentService.executeStep({
+ context: next.context,
inlineContinuation: true,
- lockRetryAttempt,
operationId,
- rejectAndContinue,
- rejectionReason,
- resumeAsyncTool,
retainStepLock: true,
- stepIndex,
+ stepIndex: next.stepIndex,
stepLockOwner,
- toolMessageId,
- verifyAsyncToolBarrier,
});
- pendingContinuation = result.continuation;
- touchedEnvelope ||= Boolean(pendingContinuation);
-
- while (pendingContinuation) {
- // Let the previous step's deferred work finish first. Its budget
- // hold is released there, and the next step reserves again.
- const settled = await flushScheduledWork({ timeoutMs: STEP_BOUNDARY_FLUSH_TIMEOUT_MS });
- if (!settled) {
- // The deferred work cannot be told apart, so a slow telemetry call
- // and a slow budget settlement look the same. Reserving again on
- // top of an unreleased hold is exactly the false "over budget"
- // this wait exists to prevent, so stop inlining and hand the step
- // to the queue, the way it ran before steps were inlined.
- log(
- `[${operationId}] Deferred work still running after ${STEP_BOUNDARY_FLUSH_TIMEOUT_MS}ms, handing step ${pendingContinuation.stepIndex} back to the queue`,
- );
- break;
- }
+ inlinedSteps += 1;
+ pendingContinuation = result.continuation;
+ touchedEnvelope ||= Boolean(pendingContinuation);
- const elapsed = Date.now() - startTime;
- if (elapsed >= INLINE_STEP_START_DEADLINE_MS) {
- log(
- `[${operationId}] Inline budget spent after ${inlinedSteps} extra step(s) (${elapsed}ms), handing step ${pendingContinuation.stepIndex} back to the queue`,
- );
- break;
+ // A lock conflict mid-loop means another worker took over this
+ // operation. Stop rather than fight it — that worker owns the rest.
+ if (result.locked) break;
}
- const next = pendingContinuation;
- pendingContinuation = undefined;
- currentStepIndex = next.stepIndex;
-
- result = await aiAgentService.executeStep({
- context: next.context,
- inlineContinuation: true,
- operationId,
- retainStepLock: true,
- stepIndex: next.stepIndex,
- stepLockOwner,
- });
- inlinedSteps += 1;
- pendingContinuation = result.continuation;
- touchedEnvelope ||= Boolean(pendingContinuation);
+ // Whatever is still pending goes back to the queue so the operation
+ // resumes in a fresh invocation.
+ if (pendingContinuation) {
+ await aiAgentService.scheduleContinuation(pendingContinuation);
+ result = { ...result, nextStepScheduled: true };
+ pendingContinuation = undefined;
+ }
- // A lock conflict mid-loop means another worker took over this
- // operation. Stop rather than fight it — that worker owns the rest.
- if (result.locked) break;
- }
-
- // Whatever is still pending goes back to the queue so the operation
- // resumes in a fresh invocation.
- if (pendingContinuation) {
- await aiAgentService.scheduleContinuation(pendingContinuation);
- result = { ...result, nextStepScheduled: true };
- pendingContinuation = undefined;
- }
-
- // Drop the envelope once this invocation is done with it: either the queue
- // owns the next step again, or the operation stopped. Leaving it behind
- // would let a late redelivery re-run a step someone else already owns.
- // Skipped when nothing was ever parked, to keep the flag-off path free of
- // an extra Redis round-trip.
- //
- // Scoped to our lock owner, because "done with it" is only true while we
- // still hold the operation. A delivery that read an envelope and then lost
- // the lock race must not delete the newer one the live worker parked.
- if (touchedEnvelope) {
- await coordinator.clearInlineResume(operationId, stepLockOwner);
- }
- });
+ // Drop the envelope once this invocation is done with it: either the queue
+ // owns the next step again, or the operation stopped. Leaving it behind
+ // would let a late redelivery re-run a step someone else already owns.
+ // Skipped when nothing was ever parked, to keep the flag-off path free of
+ // an extra Redis round-trip.
+ //
+ // Scoped to our lock owner, because "done with it" is only true while we
+ // still hold the operation. A delivery that read an envelope and then lost
+ // the lock race must not delete the newer one the live worker parked.
+ if (touchedEnvelope) {
+ await coordinator.clearInlineResume(operationId, stepLockOwner);
+ }
+ }),
+ );
} finally {
// Owner-scoped, so this is a no-op when the first step never claimed the
// lock (a conflicting delivery, a terminal operation, a watchdog probe).
diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.ts
index 101a0a0f819..568e9d5b6ab 100644
--- a/apps/server/src/router-hono/agent/index.ts
+++ b/apps/server/src/router-hono/agent/index.ts
@@ -9,6 +9,7 @@ import { gatewayCron } from './handlers/gatewayCron';
import { gatewayDesiredConnections } from './handlers/gatewayDesiredConnections';
import { gatewayStart } from './handlers/gatewayStart';
import { groupMemberCallback } from './handlers/groupMemberCallback';
+import { llmRelayChunks, llmRelayPayload } from './handlers/llmRelay';
import { messengerInstall } from './handlers/messengerInstall';
import { messengerOAuthCallback } from './handlers/messengerOAuthCallback';
import { messengerWebhook } from './handlers/messengerWebhook';
@@ -42,6 +43,13 @@ app.get('/run', runStepHealth);
// POST /api/agent/tool-result — gateway-side tool result LPUSH'd to Redis
app.post('/tool-result', serviceTokenAuth(), toolResult);
+// LLM relay: the user's device runs one LLM attempt for a device-only model
+// provider. Auth is the per-call lease token carried by `llm_execute`.
+// GET /api/agent/llm-relay/:callId/payload — request body of the attempt
+app.get('/llm-relay/:callId/payload', llmRelayPayload);
+// POST /api/agent/llm-relay/:callId/chunks — one batch of protocol chunks
+app.post('/llm-relay/:callId/chunks', llmRelayChunks);
+
// POST /api/agent/finalize-abandoned — watchdog reverse-trigger finalize
app.post('/finalize-abandoned', serviceTokenAuth(), finalizeAbandoned);
app.get('/finalize-abandoned', (c) =>
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 3a7da75bf71..57304d80f3c 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1047,6 +1047,18 @@ const ExecAgentSchema = z
* server-initiated run), which keeps the pushed snapshots.
*/
clientProtocol: z.union([z.literal(1), z.literal(2)]).optional(),
+ /**
+ * The calling client can execute single LLM attempts the server relays to
+ * it (`llm_execute`) for providers only this device can reach. Sent only
+ * when the client is inside the `agent_llm_relay` rollout.
+ */
+ llmExecutor: z
+ .object({
+ capabilities: z.array(z.string()).max(16),
+ clientId: z.string().min(1).max(128),
+ providers: z.array(z.string()).max(256),
+ })
+ .optional(),
/** The agent ID to run (either agentId or slug is required) */
agentId: z.string().optional(),
/** Application context for message storage */
@@ -1514,6 +1526,8 @@ const AgentStreamEventSchema = z.object({
'tool_start',
'tool_end',
'tool_execute',
+ 'llm_execute',
+ 'llm_cancel',
'tool_result',
'agent_intervention_request',
'agent_intervention_response',
@@ -2459,6 +2473,7 @@ export const aiAgentRouter = router({
},
clientProtocol: input.clientProtocol,
includeFinalState: input.includeFinalState,
+ llmExecutor: input.llmExecutor,
// This procedure serves the composer (`aiAgentService.execAgentTask`).
// The client already queues follow-ups behind a live run and shows the
// user a tray; refusing here would only make the message disappear.
@@ -2618,6 +2633,7 @@ export const aiAgentRouter = router({
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(task.streamFeatures),
clientProtocol: task.clientProtocol,
includeFinalState: task.includeFinalState,
+ llmExecutor: task.llmExecutor,
agentId,
appContext,
autoStart,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 8057d6adcca..cf809396d40 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -536,6 +536,50 @@ describe('AgentRuntimeService', () => {
},
);
+ describe('relay executor (host.llmExecutor)', () => {
+ const executor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers: ['ollama'] };
+
+ it('stores the executor the client declared', async () => {
+ await service.createOperation({ ...mockParams, autoStart: false, llmExecutor: executor });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.llmExecutor).toEqual(executor);
+ });
+
+ it("lets a group member, mirrored onto its parent's channel, inherit the parent's executor", async () => {
+ await mockCoordinator.saveAgentState('parent-op', { host: { llmExecutor: executor } });
+ mockCoordinator.saveAgentState.mockClear();
+
+ await service.createOperation({
+ ...mockParams,
+ appContext: { ...mockParams.appContext, orchestrationRole: 'member' },
+ autoStart: false,
+ parentOperationId: 'parent-op',
+ });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.llmExecutor).toEqual(executor);
+ });
+
+ it("keeps a genuine sub-agent, streaming on its own channel, off the parent's executor", async () => {
+ await mockCoordinator.saveAgentState('parent-op', { host: { llmExecutor: executor } });
+ mockCoordinator.saveAgentState.mockClear();
+
+ await service.createOperation({
+ ...mockParams,
+ appContext: { ...mockParams.appContext, isSubAgent: true },
+ autoStart: false,
+ parentOperationId: 'parent-op',
+ });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host).not.toHaveProperty('llmExecutor');
+ });
+
+ it('carries no executor for a run nobody declared one for', async () => {
+ await service.createOperation({ ...mockParams, autoStart: false });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host).not.toHaveProperty('llmExecutor');
+ });
+ });
+
it('should create operation successfully with autoStart=true', async () => {
mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 3023c95921a..c81701d8d2a 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import type {
Agent,
+ AgentRunLlmExecutor,
AgentRuntimeContext,
AgentState,
GeneralAgentConfig,
@@ -747,6 +748,41 @@ export class AgentRuntimeService {
return true;
}
+ /**
+ * The relay executor a new run carries: the one its client declared, else —
+ * for a group member, whose stream is mirrored onto its parent's channel —
+ * its parent's, so a member on the same local model reaches the same device.
+ * A genuine sub-agent publishes `llm_execute` on its own channel, which no
+ * client subscribes to, so it inherits nothing and fails fast as
+ * `no_executor` instead of waiting out the claim. Best-effort: an expired
+ * parent leaves the member without one.
+ */
+ private async resolveLlmExecutor(
+ declared: AgentRunLlmExecutor | undefined,
+ parentOperationId: string | undefined,
+ streamsOnParentChannel: boolean,
+ ): Promise<AgentRunLlmExecutor | undefined> {
+ if (declared) return declared;
+ if (!parentOperationId || !streamsOnParentChannel) return;
+
+ return this.getLlmExecutor(parentOperationId);
+ }
+
+ /**
+ * The relay executor an operation carries, e.g. for an approval continuation
+ * that the parked operation's client resumes. Best-effort: an unknown or
+ * expired operation reads as none.
+ */
+ async getLlmExecutor(operationId: string): Promise<AgentRunLlmExecutor | undefined> {
+ try {
+ const state = await this.coordinator.loadAgentState(operationId);
+ return state?.host?.llmExecutor;
+ } catch (error) {
+ log('[%s] Failed to read the relay executor: %O', operationId, error);
+ return;
+ }
+ }
+
/**
* Whether the client that started this operation declared it handles
* `member_runtime_end`. An unknown or expired operation reads as `false`, so
@@ -1222,6 +1258,12 @@ export class AgentRuntimeService {
}))
: undefined;
+ const llmExecutor = await this.resolveLlmExecutor(
+ params.llmExecutor,
+ parentOperationId,
+ appContext?.orchestrationRole === 'member',
+ );
+
const initialState = {
activatedStepTools,
createdAt: new Date().toISOString(),
@@ -1245,6 +1287,7 @@ export class AgentRuntimeService {
host: {
...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),
...(params.includeFinalState === true && { includeFinalState: true }),
+ ...(llmExecutor && { llmExecutor }),
queue: { retries: queueRetries, retryDelay: queueRetryDelay },
},
// Run ledger — everything fixed at creation lives in the typed slots.
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 14da1e82729..aa3a74cd9bc 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -1,4 +1,8 @@
-import { type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';
+import {
+ type AgentRunLlmExecutor,
+ type AgentRuntimeContext,
+ type AgentState,
+} from '@lobechat/agent-runtime';
import type {
AgentGroupConfig,
BotPlatformContext,
@@ -559,6 +563,12 @@ export interface OperationCreationParams {
sourceOperationId: string;
sourceToolMessageIds: string[];
};
+ /**
+ * The client that started this run can execute relayed LLM attempts
+ * (`llm_execute`). Stored on `state.host.llmExecutor`; a sub-agent run
+ * inherits its parent's when it declares none.
+ */
+ llmExecutor?: AgentRunLlmExecutor;
maxSteps?: number;
modelRuntimeConfig?: any;
/** Marks the source claim non-rollbackable once deterministic runtime state is durable. */
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
index b8a1512f77c..8c2a5339d3e 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
@@ -153,6 +153,7 @@ vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(function () {
return {
acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),
+ getLlmExecutor: vi.fn().mockResolvedValue(undefined),
completeGroupActionMember: mockCompleteGroupActionMember,
createOperation: mockCreateOperation,
ensureInterventionContinuationStarted: mockEnsureInterventionContinuationStarted,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 75ccae0b59f..598c62c5c8f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1546,6 +1546,7 @@ export class AiAgentService {
stream,
clientProtocol: params.clientProtocol,
includeFinalState: params.includeFinalState,
+ llmExecutor: params.llmExecutor,
topicStartOwnerOperationId: params.topicStartOwnerOperationId,
updateAbortedAssistantMessage,
userAgent,
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
index 6fec94fa304..fbdaf370287 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
@@ -6,6 +6,8 @@ vi.mock('@/libs/trpc/utils/internalJwt', () => ({
signUserJWT: vi.fn().mockResolvedValue('jwt'),
}));
+const sourceExecutor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers: ['ollama'] };
+
const setup = (sourceAccepts: boolean) => {
const calls: string[] = [];
const agentRuntimeService = {
@@ -14,6 +16,10 @@ const setup = (sourceAccepts: boolean) => {
return sourceAccepts;
}),
createOperation: vi.fn(async () => ({ autoStarted: true, messageId: 'msg-assistant' })),
+ getLlmExecutor: vi.fn(async () => {
+ calls.push('read-executor');
+ return sourceExecutor;
+ }),
};
const deps = {
agentRuntimeService,
@@ -78,7 +84,7 @@ describe('startOperation › member_runtime_end declaration', () => {
expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(
expect.objectContaining({ acceptsMemberRuntimeEnd: true }),
);
- expect(calls).toEqual(['read-source', 'retire-source']);
+ expect(calls).toEqual(['read-source', 'read-executor', 'retire-source']);
});
// Codex P1 on #20102: an older client resuming an approval of a run a newer
@@ -109,3 +115,34 @@ describe('startOperation › member_runtime_end declaration', () => {
);
});
});
+
+describe('startOperation › relay executor', () => {
+ it('carries the parked operation relay executor over to an approval continuation', async () => {
+ const { agentRuntimeService, calls, ctx, deps, input } = setup(true);
+
+ await startOperation(deps, ctx, input({ approvalSourceOperationId: 'op-parked' }));
+
+ expect(agentRuntimeService.getLlmExecutor).toHaveBeenCalledWith('op-parked');
+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ llmExecutor: sourceExecutor }),
+ );
+ // Read before the parked operation is retired.
+ expect(calls.indexOf('read-executor')).toBeLessThan(calls.indexOf('retire-source'));
+ });
+
+ it('keeps the executor the resuming client declared', async () => {
+ const { agentRuntimeService, ctx, deps, input } = setup(true);
+ const declared = { ...sourceExecutor, clientId: 'tab-b' };
+
+ await startOperation(
+ deps,
+ ctx,
+ input({ approvalSourceOperationId: 'op-parked', llmExecutor: declared }),
+ );
+
+ expect(agentRuntimeService.getLlmExecutor).not.toHaveBeenCalled();
+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ llmExecutor: declared }),
+ );
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index ce499e17988..337cebb8ed7 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -48,6 +48,8 @@ export interface StartOperationInput {
/** Final runtime context — base prep context with 16b/16c overrides applied. */
initialContext: OperationPrepResult['initialContext'];
initialStepCount?: number;
+ /** Relay executor the calling client declared; lands on `state.host.llmExecutor`. */
+ llmExecutor?: InternalExecAgentParams['llmExecutor'];
maxSteps?: number;
onOperationCreated?: InternalExecAgentParams['onOperationCreated'];
operationId: string;
@@ -159,10 +161,18 @@ export const startOperation = async (
(approvalSourceOperationId
? await deps.agentRuntimeService.acceptsMemberRuntimeEnd(approvalSourceOperationId)
: undefined);
+ // Same client, same device: the continuation also keeps the parked
+ // operation's relay executor, or its next device-only call has none.
+ const llmExecutor =
+ input.llmExecutor ??
+ (approvalSourceOperationId
+ ? await deps.agentRuntimeService.getLlmExecutor(approvalSourceOperationId)
+ : undefined);
const result = await deps.agentRuntimeService.createOperation({
acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,
clientProtocol: input.clientProtocol,
includeFinalState: input.includeFinalState,
+ llmExecutor,
activeDeviceId: discovery.activeDeviceId,
activeDeviceScope: discovery.activeDeviceScope,
agentConfig,
diff --git a/apps/server/src/utils/invocationDeadline.ts b/apps/server/src/utils/invocationDeadline.ts
new file mode 100644
index 00000000000..5778fd10e86
--- /dev/null
+++ b/apps/server/src/utils/invocationDeadline.ts
@@ -0,0 +1,13 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const deadlineStorage = new AsyncLocalStorage<number>();
+
+/**
+ * Run `fn` knowing the host kills this invocation at `deadlineAt` (epoch ms),
+ * so long waits inside it can stop in time to clean up after themselves.
+ */
+export const runWithInvocationDeadline = <T>(deadlineAt: number, fn: () => Promise<T>) =>
+ deadlineStorage.run(deadlineAt, fn);
+
+/** When the current invocation is killed, if its host declared it. */
+export const getInvocationDeadline = (): number | undefined => deadlineStorage.getStore();
diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdx
index 77b8a37dea3..f59d4c09317 100644
--- a/docs/self-hosting/advanced/feature-flags.mdx
+++ b/docs/self-hosting/advanced/feature-flags.mdx
@@ -36,27 +36,28 @@ You can achieve various feature combinations using the above configuration synta
their default values).
</Callout>
-| Configuration Item | Description | Default Value |
-| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
-| `check_updates` | Allows checking for updates. | Enabled |
-| `provider_settings` | Controls model provider settings display. | Enabled |
-| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |
-| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |
-| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |
-| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
-| `agent_gateway_mux` | Routes agent runs over one multiplexed gateway socket per user. Requires a gateway that serves `/v2/ws` (`AGENT_GATEWAY_PROTOCOL=2`). | Disabled |
-| `edit_agent` | Allows users to edit assistants. | Enabled |
-| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |
-| `speech_to_text` | Enables speech-to-text functionality. | Enabled |
-| `token_counter` | Reserved for token counter display. | Enabled |
-| `welcome_suggest` | Displays welcome suggestions. | Enabled |
-| `changelog` | Controls changelog modal/page display. | Enabled |
-| `market` | Enables the assistant market functionality. | Enabled |
-| `knowledge_base` | Enables the knowledge base functionality. | Enabled |
-| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |
-| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |
-| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |
-| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |
+| Configuration Item | Description | Default Value |
+| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |
+| `check_updates` | Allows checking for updates. | Enabled |
+| `provider_settings` | Controls model provider settings display. | Enabled |
+| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |
+| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |
+| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |
+| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
+| `agent_gateway_mux` | Routes agent runs over one multiplexed gateway socket per user. Requires a gateway that serves `/v2/ws` (`AGENT_GATEWAY_PROTOCOL=2`). | Disabled |
+| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |
+| `edit_agent` | Allows users to edit assistants. | Enabled |
+| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |
+| `speech_to_text` | Enables speech-to-text functionality. | Enabled |
+| `token_counter` | Reserved for token counter display. | Enabled |
+| `welcome_suggest` | Displays welcome suggestions. | Enabled |
+| `changelog` | Controls changelog modal/page display. | Enabled |
+| `market` | Enables the assistant market functionality. | Enabled |
+| `knowledge_base` | Enables the knowledge base functionality. | Enabled |
+| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |
+| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |
+| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |
+| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |
## Interactive Agent Sharing: Deployment and Rollout Boundaries
diff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
index aa0acf46a99..c71f6679d20 100644
--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
@@ -32,27 +32,28 @@ tags:
关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。
</Callout>
-| 配置项 | 解释 | 默认值 |
-| ------------------------ | ---------------------------------------------------------------- | --- |
-| `check_updates` | 允许检查更新。 | 开启 |
-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |
-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |
-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |
-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |
-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
-| `agent_gateway_mux` | 让助理运行共用一条按用户复用的网关连接;需要网关提供 `/v2/ws`(`AGENT_GATEWAY_PROTOCOL=2`)。 | 关闭 |
-| `edit_agent` | 允许用户编辑助手。 | 开启 |
-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |
-| `speech_to_text` | 启用语音转文本功能。 | 开启 |
-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |
-| `welcome_suggest` | 显示欢迎建议。 | 开启 |
-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |
-| `market` | 启用助手市场功能。 | 开启 |
-| `knowledge_base` | 启用知识库功能。 | 开启 |
-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |
-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |
-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |
-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |
+| 配置项 | 解释 | 默认值 |
+| ------------------------ | -------------------------------------------------------------------------------------------------- | --- |
+| `check_updates` | 允许检查更新。 | 开启 |
+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |
+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |
+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |
+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |
+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
+| `agent_gateway_mux` | 让助理运行共用一条按用户复用的网关连接;需要网关提供 `/v2/ws`(`AGENT_GATEWAY_PROTOCOL=2`)。 | 关闭 |
+| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |
+| `edit_agent` | 允许用户编辑助手。 | 开启 |
+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |
+| `speech_to_text` | 启用语音转文本功能。 | 开启 |
+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |
+| `welcome_suggest` | 显示欢迎建议。 | 开启 |
+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |
+| `market` | 启用助手市场功能。 | 开启 |
+| `knowledge_base` | 启用知识库功能。 | 开启 |
+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |
+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |
+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |
+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |
## 交互式助理分享:部署与灰度边界
diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.json
index e5b7f03cc75..22500ac833a 100644
--- a/locales/en-US/modelRuntime.json
+++ b/locales/en-US/modelRuntime.json
@@ -2,6 +2,9 @@
"AccountDeactivated": "Your account has been deactivated or suspended. This may be due to policy, security, or account review reasons. Please contact the provider support for assistance.",
"AgentRuntimeError": "Lobe language model runtime execution error. Please troubleshoot or retry based on the following information.",
"CapabilityNotSupported": "Sorry, this model does not support the requested capability (such as vision input or tool calling). Please switch to a model that supports it.",
+ "ClientLlmExecutorLost": "The device running {{provider}} for this conversation stopped responding before the reply finished — it may have been closed, refreshed or disconnected. Keep the LobeHub window open and try again.",
+ "ClientLlmExecutorUnavailable": "{{provider}} can only be reached from your own device, but no open LobeHub window picked up the request. Open LobeHub on the device where {{provider}} runs, then retry.",
+ "ClientLlmTimeout": "{{provider}} on your device did not respond in time. Make sure the model is running and loaded, then try again.",
"ComfyUIBizError": "An error occurred while requesting the ComfyUI service. Please troubleshoot using the information below or try again.",
"ComfyUIEmptyResult": "No image was generated by ComfyUI. Please check the model configuration or try again.",
"ComfyUIModelError": "Failed to load the ComfyUI model. Please ensure the model file exists.",
diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.json
index ce00e9c5f32..a5ffc83073e 100644
--- a/locales/zh-CN/modelRuntime.json
+++ b/locales/zh-CN/modelRuntime.json
@@ -2,6 +2,9 @@
"AccountDeactivated": "您的账户已被停用或暂停。这可能是由于政策、安全或账户审核原因。请联系服务提供商支持以获取帮助。",
"AgentRuntimeError": "Lobe语言模型运行时执行错误。请根据以下信息进行排查或重试。",
"CapabilityNotSupported": "抱歉,此模型不支持请求的功能(例如视觉输入或工具调用)。请切换到支持该功能的模型。",
+ "ClientLlmExecutorLost": "正在为本次对话运行 {{provider}} 的设备在回复完成前停止了响应,可能是窗口被关闭、刷新或断开了连接。请保持 LobeHub 窗口打开后重试。",
+ "ClientLlmExecutorUnavailable": "{{provider}} 只能从你自己的设备访问,但当前没有打开的 LobeHub 窗口接手这次请求。请在运行 {{provider}} 的设备上打开 LobeHub 后重试。",
+ "ClientLlmTimeout": "你设备上的 {{provider}} 未在规定时间内响应。请确认模型已启动并加载完成后重试。",
"ComfyUIBizError": "请求ComfyUI服务时发生错误。请根据以下信息进行排查或重试。",
"ComfyUIEmptyResult": "ComfyUI未生成任何图像。请检查模型配置或重试。",
"ComfyUIModelError": "加载ComfyUI模型失败。请确保模型文件存在。",
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index ead13cef11d..77b954819a0 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -59,6 +59,11 @@ export type {
AgentStreamEventType,
AgentStreamSessionCompletion,
ConnectionStatus,
+ LlmCancelData,
+ LlmExecuteData,
+ LlmRelayBatch,
+ LlmRelayBatchAck,
+ LlmRelayDeadlines,
MessagePatchData,
MessagePatchUpsert,
SessionStatus,
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index fda0b40c3d1..bf9e1a9dd65 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -35,6 +35,14 @@ export type AgentStreamEventType =
| 'tool_start'
| 'tool_end'
| 'tool_execute'
+ /**
+ * Server → executor client: run one LLM attempt for a model provider only
+ * the user's device can reach, and upload its protocol chunks back over
+ * HTTP (`/api/agent/llm-relay/:callId/chunks`). See {@link LlmExecuteData}.
+ */
+ | 'llm_execute'
+ /** Server → executor client: stop a relayed LLM attempt. See {@link LlmCancelData}. */
+ | 'llm_cancel'
/**
* Producer-side tool result content (heterogeneous CLI agents emit this
* separately from `tool_end`; gateway-driven runs do not). Kept in the
@@ -121,6 +129,12 @@ export interface StreamChunkData {
pluginState?: Record<string, unknown>;
reasoning?: string;
reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
+ /**
+ * Set when the chunk re-publishes output the server received from a relayed
+ * LLM attempt (`llm_execute`). The executor client already rendered that
+ * output locally, so it skips text/reasoning chunks carrying a call id it ran.
+ */
+ relayCallId?: string;
/**
* `lh hetero exec` coalesces main-agent text deltas into full-text
* snapshots: `content` carries the WHOLE message so far and must replace
@@ -350,6 +364,78 @@ export interface ToolExecuteData {
topicId?: string | null;
}
+/** Deadlines a relayed LLM attempt runs under, in milliseconds. */
+export interface LlmRelayDeadlines {
+ /** From dispatch until the first uploaded batch (an empty batch counts). */
+ claimMs: number;
+ /** From the first batch until the first non-empty chunk (model cold start). */
+ firstChunkMs: number;
+ /** Longest gap between two batches; idle executors send an empty batch as heartbeat. */
+ idleMs: number;
+ /** Whole attempt, dispatch included. The client should stop a little earlier. */
+ totalMs: number;
+}
+
+/**
+ * Server → Client (`llm_execute`): run one LLM attempt locally and stream its
+ * normalized protocol chunks back. Carries no messages and no credentials: the
+ * request body is fetched from `GET /api/agent/llm-relay/:callId/payload`, and
+ * the client uses its own provider configuration.
+ */
+export interface LlmExecuteData {
+ /** Assistant message the attempt streams into, for local optimistic rendering. */
+ assistantMessageId?: string;
+ attempt: number;
+ /** Idempotency key of this attempt: `${operationId}:${stepIndex}:${attempt}`. */
+ callId: string;
+ deadlines: LlmRelayDeadlines;
+ /**
+ * Capability for the relay endpoints of this call (payload + chunk upload),
+ * sent as the `x-llm-relay-lease` header. Expires with the attempt.
+ */
+ leaseToken: string;
+ model: string;
+ operationId: string;
+ /**
+ * Client that started the run (`host.llmExecutor.clientId`). It executes;
+ * other clients only take over when it is gone. The first batch to arrive
+ * claims the call, later claimants get 409.
+ */
+ preferredClientId?: string;
+ /** Provider id, for the client's own key vault / endpoint lookup. */
+ provider: string;
+ /** SDK the provider speaks (`sdkType` for custom providers). */
+ runtimeProvider: string;
+ stepIndex: number;
+}
+
+/** Server → Client (`llm_cancel`): stop the relayed attempt and upload a final `aborted` batch. */
+export interface LlmCancelData {
+ callId: string;
+ reason: 'interrupted' | 'timeout' | 'superseded' | 'error';
+}
+
+/** Client → Server: one batch of a relayed attempt's output. */
+export interface LlmRelayBatch {
+ /** Sorted, gap-free per call starting at 1; the server dedupes and reorders by it. */
+ chunks: Array<{ data: unknown; id?: string; type: string }>;
+ /** Uploading client; the first batch claims the call for it. */
+ clientId: string;
+ /** Last batch of the attempt. */
+ final?: {
+ error?: unknown;
+ reason: 'aborted' | 'done' | 'error';
+ };
+ seq: number;
+}
+
+/** Server → Client reply to an uploaded batch. */
+export interface LlmRelayBatchAck {
+ ackSeq: number;
+ /** The server no longer wants this attempt (stopped, timed out, superseded): abort now. */
+ cancel?: boolean;
+}
+
// ─── WebSocket Protocol Messages ───
// Client → Server
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index cefbbe478f7..488f9b0ff25 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -81,6 +81,7 @@ const executePreparedCall = async (
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const execution = await runWithTrace(trace, () =>
llm.runAttempt({
+ assistantMessageId: prepared.assistantMessageId,
attempt,
context: prepared.context,
events,
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index 44f88c926b1..4f4d9c747e9 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -582,6 +582,45 @@ describe('callLlmFinalizer', () => {
});
});
+ it('records a client-executed attempt and its estimated usage on the message', async () => {
+ const messages = createMessageTransport();
+
+ await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-1',
+ events: [],
+ host: createHost(messages),
+ model: 'llama3',
+ output: createOutput({
+ executionSite: 'client',
+ usage: { totalInputTokens: 9, totalOutputTokens: 3, totalTokens: 12 },
+ usageEstimated: true,
+ }),
+ provider: 'ollama',
+ shouldReplayAssistantReasoning: false,
+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),
+ });
+
+ expect(messages.update).toHaveBeenCalledWith(
+ 'assistant-1',
+ expect.objectContaining({
+ metadata: expect.objectContaining({ executionSite: 'client', usageEstimated: true }),
+ }),
+ );
+
+ await persistInterruptedCallLlmResult({
+ assistantMessageId: 'assistant-2',
+ host: createHost(messages),
+ output: createOutput({ content: 'Partial', executionSite: 'client' }),
+ });
+
+ expect(messages.update).toHaveBeenLastCalledWith(
+ 'assistant-2',
+ expect.objectContaining({
+ metadata: { executionSite: 'client', interruptedMidStream: true },
+ }),
+ );
+ });
+
it('persists partial interrupted output and skips empty interruptions', async () => {
const messages = createMessageTransport();
const host = createHost(messages);
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index a837085bbd6..51473a31e31 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -65,16 +65,20 @@ const buildMessageMetadata = ({
answerSalvagedFromReasoning,
currentStepSpeed,
currentStepUsage,
+ executionSite,
finishType,
hasContentImages,
interruptedMidStream,
+ usageEstimated,
}: {
answerSalvagedFromReasoning?: boolean;
currentStepSpeed?: ModelPerformance;
currentStepUsage?: ModelUsage;
+ executionSite?: LLMAttemptOutput['executionSite'];
finishType?: string;
hasContentImages?: boolean;
interruptedMidStream?: boolean;
+ usageEstimated?: boolean;
}): CallLlmMessageMetadata | undefined => {
const metadata: CallLlmMessageMetadata = {
...(currentStepUsage && { ...currentStepUsage, usage: currentStepUsage }),
@@ -83,6 +87,8 @@ const buildMessageMetadata = ({
...(hasContentImages && { isMultimodal: true }),
...(answerSalvagedFromReasoning && { answerSalvagedFromReasoning: true }),
...(interruptedMidStream && { interruptedMidStream: true }),
+ ...(executionSite && { executionSite }),
+ ...(usageEstimated && currentStepUsage && { usageEstimated: true }),
};
return Object.keys(metadata).length > 0 ? metadata : undefined;
@@ -182,8 +188,10 @@ const persistFinalMessage = async ({
answerSalvagedFromReasoning: output.answerSalvagedFromReasoning,
currentStepSpeed: output.speed,
currentStepUsage: output.usage,
+ executionSite: output.executionSite,
finishType: output.finishReason,
hasContentImages: output.hasContentImages,
+ usageEstimated: output.usageEstimated,
});
const workAnchor = buildWorkAnchor({
operationId: host.operation.operationId,
@@ -429,7 +437,9 @@ export const persistInterruptedCallLlmResult = async ({
metadata: buildMessageMetadata({
currentStepSpeed: output.speed,
currentStepUsage: output.usage,
+ executionSite: output.executionSite,
interruptedMidStream: true,
+ usageEstimated: output.usageEstimated,
}),
reasoning: output.thinkingContent ? { content: output.thinkingContent } : undefined,
tools: sanitizePersistedTools(output.toolsCalling),
diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.ts
index 3d8ec4852d6..da66257359b 100644
--- a/packages/agent-runtime/src/transport/llm.ts
+++ b/packages/agent-runtime/src/transport/llm.ts
@@ -47,6 +47,12 @@ export interface LLMAttemptOutput {
answerSalvagedFromReasoning: boolean;
content: string;
contentParts: LLMAttemptContentPart[];
+ /**
+ * Where the model request actually ran. Absent means the host itself (the
+ * server); `client` means the host relayed this attempt to the user's device
+ * and only received its output, so the platform neither paid for nor billed it.
+ */
+ executionSite?: 'client';
finishReason?: string;
grounding: GroundingSearch | null;
hasContentImages: boolean;
@@ -63,9 +69,13 @@ export interface LLMAttemptOutput {
toolsCalling: ChatToolPayload[];
traceId?: string;
usage?: ModelUsage;
+ /** `usage` was estimated by the host because the model reported none. */
+ usageEstimated?: boolean;
}
export interface LLMAttemptInput {
+ /** Assistant message this attempt streams into. */
+ assistantMessageId?: string;
attempt: number;
context: ContextBuildOutput;
events: AgentEvent[];
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index c19fc6818de..e44bda9d4ab 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -186,10 +186,28 @@ export interface AgentRunHostEnvelope {
hooks?: SerializedAgentHook[];
/** Opt into runtime state snapshots on step_complete events. Defaults to false. */
includeFinalState?: boolean;
+ /**
+ * The client that started this run can execute single LLM attempts the
+ * server relays to it (`llm_execute`), for model providers only the user's
+ * device can reach (a local Ollama, a private-network endpoint). Declared by
+ * the client, like `clientProtocol`; absent means no client will pick up a
+ * relayed call, so such a provider fails fast instead of waiting.
+ */
+ llmExecutor?: AgentRunLlmExecutor;
/** Queue retry policy for step scheduling. */
queue?: { retries?: number; retryDelay?: string };
}
+/** A client's declaration that it can run relayed LLM attempts. */
+export interface AgentRunLlmExecutor {
+ /** Relay protocol versions the client speaks, e.g. `llm_relay@1`. */
+ capabilities: string[];
+ /** Stable id of the declaring client (tab / desktop window), preferred as the executor. */
+ clientId: string;
+ /** Provider ids this client confirmed it can reach directly. */
+ providers: string[];
+}
+
/**
* Search route resolved once before the run starts. Declared here rather than
* imported so the runtime package does not depend on the model catalog;
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index f494c8bd689..c82b78ac0ec 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -50,6 +50,15 @@ export const FeatureFlagsSchema = z.object({
*/
agent_gateway_mux: FeatureFlagValue.optional(),
+ /**
+ * Rollout gate for relaying LLM calls to the user's device: a model provider
+ * only that device can reach (a local Ollama / LM Studio, a private-network
+ * endpoint) runs one attempt at a time on the client that started the run,
+ * while the agent loop stays on the server. Off: such providers keep being
+ * dialed by the server. Array values are user ids.
+ */
+ agent_llm_relay: FeatureFlagValue.optional(),
+
// internal flag
agent_self_iteration: FeatureFlagValue.optional(),
agent_onboarding: FeatureFlagValue.optional(),
@@ -117,6 +126,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// v1 socket stays the default everywhere until then.
agent_gateway_mux: false,
+ // Off until the client executor ships everywhere; allowlist first.
+ agent_llm_relay: false,
+
agent_self_iteration: isDev,
agent_onboarding: isDev,
dev_dock: isDev,
@@ -150,6 +162,7 @@ export const mapFeatureFlagsEnvToState = (
enableAgentShare: evaluateFeatureFlag(config.agent_share, userId),
enableGatewayMux: evaluateFeatureFlag(config.agent_gateway_mux, userId),
+ enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId),
showProvider: evaluateFeatureFlag(config.provider_settings, userId),
showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),
diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.ts
index 74bb97a8ab1..64d4bc7c69f 100644
--- a/packages/locales/src/default/modelRuntime.ts
+++ b/packages/locales/src/default/modelRuntime.ts
@@ -5,6 +5,12 @@ export default {
'Lobe language model runtime execution error. Please troubleshoot or retry based on the following information.',
'CapabilityNotSupported':
'Sorry, this model does not support the requested capability (such as vision input or tool calling). Please switch to a model that supports it.',
+ 'ClientLlmExecutorLost':
+ 'The device running {{provider}} for this conversation stopped responding before the reply finished — it may have been closed, refreshed or disconnected. Keep the LobeHub window open and try again.',
+ 'ClientLlmExecutorUnavailable':
+ '{{provider}} can only be reached from your own device, but no open LobeHub window picked up the request. Open LobeHub on the device where {{provider}} runs, then retry.',
+ 'ClientLlmTimeout':
+ '{{provider}} on your device did not respond in time. Make sure the model is running and loaded, then try again.',
'ComfyUIBizError':
'An error occurred while requesting the ComfyUI service. Please troubleshoot using the information below or try again.',
'ComfyUIEmptyResult':
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index b51aeaa8b72..b239cb5b781 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -397,6 +397,30 @@ export const ERROR_CODE_SPECS: SpecMap = {
countAsFailure: false,
description: 'Provider timed out while downloading a remote image or file URL.',
},
+ [AgentRuntimeErrorType.ClientLlmExecutorLost]: {
+ code: AgentRuntimeErrorType.ClientLlmExecutorLost,
+ numericId: 6003,
+ category: 'network',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 504,
+ retryable: true,
+ countAsFailure: false,
+ description:
+ 'The user device running a relayed model request went silent (closed, refreshed or disconnected) mid-stream.',
+ },
+ [AgentRuntimeErrorType.ClientLlmTimeout]: {
+ code: AgentRuntimeErrorType.ClientLlmTimeout,
+ numericId: 6004,
+ category: 'network',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 504,
+ retryable: true,
+ countAsFailure: false,
+ description:
+ 'A relayed model request on the user device missed its first-output or total deadline.',
+ },
// ─── 7xxx Stream / Runtime ────────────────────────────────────────────
[AgentRuntimeErrorType.StreamChunkError]: {
@@ -739,6 +763,18 @@ export const ERROR_CODE_SPECS: SpecMap = {
countAsFailure: false,
description: 'Provider connection check failed during setup.',
},
+ [AgentRuntimeErrorType.ClientLlmExecutorUnavailable]: {
+ code: AgentRuntimeErrorType.ClientLlmExecutorUnavailable,
+ numericId: 9007,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 409,
+ retryable: false,
+ countAsFailure: false,
+ description:
+ 'The model is only reachable from the user device and no open LobeHub client picked up the request.',
+ },
};
/**
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index dbbcbb55ffe..22365569f29 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -5,6 +5,7 @@ export type { ModelRuntimeHooks } from './core/ModelRuntime';
export { ModelRuntime } from './core/ModelRuntime';
export { createOpenAICompatibleRuntime } from './core/openaiCompatibleFactory';
export * from './core/RouterRuntime';
+export { createCallbacksTransformer } from './core/streams/protocol';
export * from './core/usageConverters';
export {
CATEGORY_NUMERIC_PREFIX,
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index d18a67840f8..daa6e3d85d3 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -209,6 +209,16 @@ export interface ExecAgentClientIds {
userMessageId?: string;
}
+/** A client's declaration that it can run relayed LLM attempts (`llm_execute`). */
+export interface ExecAgentLlmExecutor {
+ /** Relay protocol versions the client speaks, e.g. `llm_relay@1`. */
+ capabilities: string[];
+ /** Stable id of the declaring client (tab / desktop window). */
+ clientId: string;
+ /** Provider ids this client can reach directly. */
+ providers: string[];
+}
+
export interface ExecAgentParams {
/** The agent ID to run (either agentId or slug is required) */
agentId?: string;
@@ -247,6 +257,12 @@ export interface ExecAgentParams {
includeFinalState?: boolean;
/** Additional system instructions appended after the agent's own system role */
instructions?: string;
+ /**
+ * This client can execute single LLM attempts the server relays to it
+ * (`llm_execute`) for model providers only this device can reach. Lands on
+ * `state.host.llmExecutor`.
+ */
+ llmExecutor?: ExecAgentLlmExecutor;
/** Current desktop's device ID; used only when the effective target is `local`. */
localDeviceId?: string;
/** Override the agent's default model */
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 1195c3fa978..31683b7c1e4 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -283,6 +283,23 @@ export const AgentRuntimeErrorType = {
OperationInactivityTimeout: 'OperationInactivityTimeout',
InvalidOllamaArgs: 'InvalidOllamaArgs',
+ /**
+ * The model can only be reached from the user's own device, and no open
+ * LobeHub client picked up the request (no client declared it can run this
+ * provider, or none claimed the call in time). Retrying once a client is
+ * open recovers the run.
+ */
+ ClientLlmExecutorUnavailable: 'ClientLlmExecutorUnavailable',
+ /**
+ * The device running a relayed model request stopped sending output
+ * (closed, refreshed or lost its connection) before the request finished.
+ */
+ ClientLlmExecutorLost: 'ClientLlmExecutorLost',
+ /**
+ * A relayed model request on the user's device did not produce its first
+ * output, or did not finish, within the allowed time.
+ */
+ ClientLlmTimeout: 'ClientLlmTimeout',
OllamaBizError: 'OllamaBizError',
OllamaServiceUnavailable: 'OllamaServiceUnavailable',
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 86a43d32403..d7450ea1d85 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -387,6 +387,12 @@ export interface MessageMetadata {
cost?: number;
/** @deprecated use `metadata.performance` instead */
duration?: number;
+ /**
+ * Where the model request behind this message ran. `client`: the server
+ * relayed it to the user's device (a local model only that device can
+ * reach), so the platform neither paid for nor billed it. Absent: the server.
+ */
+ executionSite?: 'client';
/**
* The provider event that produced this server-injected user turn
* (GitHub CI failure, review feedback, …). See {@link ExternalOriginMetadata}.
@@ -580,6 +586,11 @@ export interface MessageMetadata {
* but new writers should target the top-level `usage` instead.
*/
usage?: ModelUsage;
+ /**
+ * The model reported no usage, so the server estimated the token counts from
+ * the request and the output text. Only set alongside `executionSite: 'client'`.
+ */
+ usageEstimated?: boolean;
/**
* Agent Run operation id this verify card belongs to (for role='verify' messages).
* References `agent_operations.id`; the card reads the verify plan + results off it.
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 97dcb2d8ac0..56414b1fb5d 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -35,6 +35,12 @@ export type IFeatureFlagsState = {
*/
enableGatewayMux: boolean | undefined;
enableKnowledgeBase: boolean | undefined;
+ /**
+ * Rollout gate for relaying LLM calls of device-only model providers to the
+ * client that started the run (`agent_llm_relay`). The client declares itself
+ * as an executor only when this is on; the server checks it again.
+ */
+ enableLlmRelay: boolean | undefined;
enableOnboardingV2: boolean | undefined;
enableRAGEval: boolean | undefined;
enableSTT: boolean | undefined;