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 independent sub-agents through the parent's executor (#20446)

Arvin Xu125a7ac35349
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts
index 1596d5a2b12..be1355d149a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.relay.test.ts
@@ -177,6 +177,55 @@ describe('ServerLLMTransport Β· LLM relay', () => {
expect(redriven).not.toBe(dead);
});
+ describe("a sub-agent relaying on its parent's channel", () => {
+ beforeEach(() => {
+ vi.mocked(resolveLlmExecutionSite).mockResolvedValue({
+ channelOperationId: 'parent-op',
+ preferredClientId: 'tab-a',
+ runtimeProvider: 'ollama',
+ site: 'client',
+ });
+ });
+
+ it("dispatches the child's attempts on the parent's channel", async () => {
+ const { ctx } = createCtx();
+ relay.chat.mockImplementation(answerWith('ok'));
+
+ await new ServerLLMTransport(ctx).runAttempt(createInput());
+
+ expect(RelayModelRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ callId: expect.stringMatching(CALL_ID_1),
+ channelOperationId: 'parent-op',
+ operationId: 'op-1',
+ preferredClientId: 'tab-a',
+ }),
+ );
+ });
+
+ it("sends the child's context-compression call to the same executor and channel", async () => {
+ const { ctx } = createCtx();
+ relay.chat.mockImplementation(answerWith('summary'));
+
+ const result = await new ServerLLMTransport(ctx).stream({
+ messages: [{ content: 'Summarize', role: 'user' }],
+ model: 'llama3',
+ provider: 'ollama',
+ });
+
+ expect(result.content).toBe('summary');
+ expect(initModelRuntimeFromDB).not.toHaveBeenCalled();
+ expect(RelayModelRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ callId: expect.stringMatching(/^op-1:2:[\w-]+:1:stream1$/),
+ channelOperationId: 'parent-op',
+ operationId: 'op-1',
+ preferredClientId: 'tab-a',
+ }),
+ );
+ });
+ });
+
it('fails fast with ClientLlmExecutorUnavailable when no client can execute the provider', async () => {
const { ctx } = createCtx();
vi.mocked(resolveLlmExecutionSite).mockResolvedValue({
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index f16be516881..a4f58fbfc9a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -411,6 +411,7 @@ export class ServerLLMTransport implements LLMTransport {
return new RelayModelRuntime({
...call,
+ channelOperationId: site.channelOperationId,
operationId: this.ctx.operationId,
preferredClientId: site.preferredClientId,
provider,
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
index a1e4526a292..9e5db5daa05 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/RelayModelRuntime.ts
@@ -44,6 +44,12 @@ export interface RelayModelRuntimeParams {
assistantMessageId?: string;
attempt: number;
callId: string;
+ /**
+ * Gateway channel `llm_execute` / `llm_cancel` go out on, when the executor
+ * listens on another run's (a sub-agent relaying through its parent's).
+ * Defaults to `operationId`, which the event still names as the run.
+ */
+ channelOperationId?: string;
deadlines?: LlmRelayDeadlines;
now?: () => number;
operationId: string;
@@ -201,6 +207,11 @@ export class RelayModelRuntime implements Pick<
log('[%s] relayed attempt failed: %O', this.params.callId, error);
}
+ /** The gateway channel the executor listens on. */
+ private get channel() {
+ return this.params.channelOperationId ?? this.params.operationId;
+ }
+
/**
* Hand the call to the user's clients. Resolves to how many the gateway
* delivered it to when it can tell, else `undefined`.
@@ -232,8 +243,9 @@ export class RelayModelRuntime implements Pick<
};
const { streamManager } = params;
+ const channel = this.channel;
if (streamManager.sendLlmExecute) {
- const { delivered, routed } = await streamManager.sendLlmExecute(params.operationId, data);
+ const { delivered, routed } = await streamManager.sendLlmExecute(channel, data);
log(
'[%s] llm_execute dispatched (routed=%s, delivered=%s)',
params.callId,
@@ -244,7 +256,7 @@ export class RelayModelRuntime implements Pick<
return routed ? delivered : undefined;
}
- await streamManager.publishStreamEvent(params.operationId, {
+ await streamManager.publishStreamEvent(channel, {
data,
stepIndex: params.stepIndex,
type: 'llm_execute',
@@ -502,7 +514,8 @@ export class RelayModelRuntime implements Pick<
* `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;
+ const { callId, redis, stepIndex, streamManager } = this.params;
+ const channel = this.channel;
try {
await redis.set(
llmRelayKeys.cancel(callId),
@@ -512,9 +525,9 @@ export class RelayModelRuntime implements Pick<
);
const data: LlmCancelData = { callId, reason };
if (streamManager.sendLlmCancel) {
- await streamManager.sendLlmCancel(operationId, { ...data, stepIndex });
+ await streamManager.sendLlmCancel(channel, { ...data, stepIndex });
} else {
- await streamManager.publishStreamEvent(operationId, {
+ await streamManager.publishStreamEvent(channel, {
data,
stepIndex,
type: 'llm_cancel',
@@ -527,7 +540,8 @@ export class RelayModelRuntime implements Pick<
/** Close the call: late uploads find no open call and get `410`. */
private async cleanup(reader?: RelayBatchReader) {
- const { callId, operationId, redis, streamManager } = this.params;
+ const { callId, redis, streamManager } = this.params;
+ const channel = this.channel;
try {
await redis
.multi()
@@ -541,7 +555,7 @@ export class RelayModelRuntime implements Pick<
// Stop the gateway replaying the attempt to clients that subscribe later.
// Best-effort and bounded by the attempt deadline anyway, so a stalled
// gateway must not hold up settling the stream.
- void Promise.resolve(streamManager.closeLlmCall?.(operationId, callId)).catch((error) =>
+ void Promise.resolve(streamManager.closeLlmCall?.(channel, callId)).catch((error) =>
log('[%s] failed to close the call on the gateway: %O', callId, error),
);
}
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
index 43006d271b4..7deca5faacb 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/RelayModelRuntime.test.ts
@@ -65,11 +65,13 @@ const createStreamManager = () => {
const createRuntime = (
streamManager: any,
deadlines = { claimMs: 2000, firstChunkMs: 2000, idleMs: 2000, totalMs: 5000 },
+ channelOperationId?: string,
) =>
new RelayModelRuntime({
assistantMessageId: 'msg_1',
attempt: 1,
callId: CALL_ID,
+ channelOperationId,
deadlines,
operationId: 'op_1',
preferredClientId: 'tab-a',
@@ -591,6 +593,55 @@ describe('RelayModelRuntime over a gateway with relay routes', () => {
expect(manager.publishStreamEvent).not.toHaveBeenCalled();
});
+ it("runs a sub-agent's call over its parent's channel, still naming the sub-agent's run", async () => {
+ const { executes, manager } = createGatewayManager();
+ const controller = new AbortController();
+ const response = await createRuntime(manager, undefined, 'parent_op').chat(payload, {
+ signal: controller.signal,
+ });
+ const consumed = consumeStreamUntilDone(response);
+ await vi.waitFor(() => expect(executes).toHaveLength(1));
+
+ expect(manager.sendLlmExecute).toHaveBeenCalledWith(
+ 'parent_op',
+ expect.objectContaining({ callId: CALL_ID, operationId: 'op_1', preferredClientId: 'tab-a' }),
+ );
+
+ await post(executes[0].leaseToken, { chunks: [], clientId: 'tab-a', seq: 1 });
+ controller.abort();
+
+ await expect(consumed).rejects.toMatchObject({ name: 'AbortError' });
+ expect(manager.sendLlmCancel).toHaveBeenCalledWith('parent_op', {
+ callId: CALL_ID,
+ reason: 'interrupted',
+ stepIndex: 0,
+ });
+ expect(manager.closeLlmCall).toHaveBeenCalledWith('parent_op', CALL_ID);
+ });
+
+ it("falls back to a stream event on the parent's channel without relay routes", async () => {
+ const published: { operationId: string; type: string }[] = [];
+ const manager = {
+ publishStreamEvent: vi.fn(async (operationId: string, event: any) => {
+ published.push({ operationId, type: event.type });
+ return 'event-id';
+ }),
+ };
+ const controller = new AbortController();
+ const response = await createRuntime(manager, undefined, 'parent_op').chat(payload, {
+ signal: controller.signal,
+ });
+ const consumed = consumeStreamUntilDone(response);
+ await vi.waitFor(() => expect(published).toHaveLength(1));
+ controller.abort();
+ await expect(consumed).rejects.toMatchObject({ name: 'AbortError' });
+
+ expect(published).toEqual([
+ { operationId: 'parent_op', type: 'llm_execute' },
+ { operationId: 'parent_op', type: 'llm_cancel' },
+ ]);
+ });
+
it('fails as ClientLlmExecutorUnavailable when the gateway refuses the dispatch', async () => {
const { manager } = createGatewayManager();
manager.sendLlmExecute.mockRejectedValueOnce(new Error('Gateway returned 409'));
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
index 013b40c272c..372e6e5f560 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/resolveLlmExecutionSite.test.ts
@@ -69,6 +69,18 @@ describe('resolveLlmExecutionSite', () => {
});
});
+ it('relays an inherited executor on the channel its client subscribed to', async () => {
+ const inherited = executor(['ollama']);
+ (inherited.host.llmExecutor as any).channelOperationId = 'parent-op';
+
+ expect(await resolve('ollama', inherited)).toEqual({
+ channelOperationId: 'parent-op',
+ 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({
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
index 63959efca67..9375562bd93 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
@@ -18,7 +18,13 @@ const log = debug('lobe-server:agent-runtime:llm-relay:site');
export type LlmExecutionSite =
| { site: 'server' }
- | { preferredClientId: string; runtimeProvider: string; site: 'client' }
+ | {
+ /** Channel to dispatch on when the executor listens on another run's; see `AgentRunLlmExecutor`. */
+ channelOperationId?: string;
+ preferredClientId: string;
+ runtimeProvider: string;
+ site: 'client';
+ }
| { reason: ClientLlmUnavailableReason; site: 'unavailable' };
export interface ResolveLlmExecutionSiteParams {
@@ -105,6 +111,7 @@ export const resolveLlmExecutionSite = async ({
if (!canExecute) return { reason: 'no_executor', site: 'unavailable' };
return {
+ ...(executor.channelOperationId && { channelOperationId: executor.channelOperationId }),
preferredClientId: executor.clientId,
runtimeProvider: relay.runtimeProvider,
site: 'client',
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
index 92233accf1f..7eece903a2a 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
@@ -124,15 +124,44 @@ describe('aiAgentRouter.execSubAgentTask', () => {
topicId: testTopicId,
});
- expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith({
+ expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith(
+ {
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ timeout: undefined,
+ title: undefined,
+ topicId: testTopicId,
+ },
+ { llmRelay: undefined },
+ );
+ });
+
+ it('hands the tab relay channel and executor to the service', async () => {
+ mockExecGroupSubAgentTask.mockResolvedValue({ success: true, threadId: 'thread-123' });
+ const llmExecutor = {
+ capabilities: ['llm_relay@1'],
+ clientId: 'tab-1',
+ providers: ['ollama'],
+ };
+ const channel = `llmcall:${userId}:personal-3f2a9c1d8e7b4a60`;
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execSubAgentTask({
agentId: testAgentId,
- groupId: testGroupId,
instruction: 'Test instruction',
+ llmExecutor: { ...llmExecutor, channelOperationId: 'someone-else-op' } as any,
+ llmRelayChannel: channel,
parentMessageId: 'parent-msg-1',
- timeout: undefined,
- title: undefined,
topicId: testTopicId,
});
+
+ // A client cannot pick the channel through the executor itself.
+ expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith(expect.anything(), {
+ llmRelay: { channel, executor: llmExecutor },
+ });
});
it('should pass parent operation metadata to the service', async () => {
@@ -159,6 +188,7 @@ describe('aiAgentRouter.execSubAgentTask', () => {
parentOperationId: 'parent-operation-1',
title: 'Delegated task',
}),
+ expect.anything(),
);
});
@@ -211,6 +241,7 @@ describe('aiAgentRouter.execSubAgentTask', () => {
expect.objectContaining({
timeout: 60000,
}),
+ expect.anything(),
);
});
});
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 48eb61f0b21..39dfee45c50 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1608,6 +1608,13 @@ const ExecSubAgentTaskSchema = z.object({
groupId: z.string().optional(),
/** Task instruction/prompt for the SubAgent */
instruction: z.string(),
+ /**
+ * The dispatching tab runs the sub-agent's device-only LLM calls: its
+ * executor declaration and the one-shot relay channel it subscribed to for
+ * them. Both or neither.
+ */
+ llmExecutor: LlmExecutorSchema.optional(),
+ llmRelayChannel: z.string().min(1).max(256).optional(),
/** The parent message ID (Supervisor's tool call message or task message) */
parentMessageId: z.string(),
/** Parent operation ID for dispatching callAgent hooks */
@@ -2960,6 +2967,8 @@ export const aiAgentRouter = router({
agentId,
groupId,
instruction,
+ llmExecutor,
+ llmRelayChannel,
parentMessageId,
parentOperationId,
title,
@@ -2986,16 +2995,24 @@ export const aiAgentRouter = router({
});
// External procedure name stays `execSubAgentTask`; the service method is `execSubAgent`.
- return await ctx.aiAgentService.execSubAgent({
- agentId,
- groupId,
- instruction,
- parentMessageId,
- ...(parentOperationId && { parentOperationId }),
- timeout,
- title,
- topicId,
- });
+ return await ctx.aiAgentService.execSubAgent(
+ {
+ agentId,
+ groupId,
+ instruction,
+ parentMessageId,
+ ...(parentOperationId && { parentOperationId }),
+ timeout,
+ title,
+ topicId,
+ },
+ {
+ llmRelay:
+ llmExecutor && llmRelayChannel
+ ? { channel: llmRelayChannel, executor: llmExecutor }
+ : undefined,
+ },
+ );
} catch (error: any) {
log('execSubAgentTask failed: %O', error);
@@ -3432,6 +3449,16 @@ export const aiAgentRouter = router({
return ctx.aiAgentService.resumeFromClientLlmWait(input);
}),
+ /**
+ * The tab stopped standing by on the relay channel it named in
+ * `execSubAgentTask` (the sub-agent finished or was given up): end it.
+ */
+ releaseSubAgentLlmRelay: aiAgentWriteProcedure
+ .input(z.object({ channel: z.string().min(1).max(256) }))
+ .mutation(async ({ input, ctx }) => {
+ return ctx.aiAgentService.releaseSubAgentLlmRelay(input.channel);
+ }),
+
interruptTask: aiAgentWriteProcedure
.input(InterruptTaskSchema)
.mutation(async ({ input, ctx }) => {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index c9c5050d012..f4de15b5849 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -568,6 +568,11 @@ describe('AgentRuntimeService', () => {
describe('relay executor (host.llmExecutor)', () => {
const executor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers: ['ollama'] };
+ // A parent run of the caller's own.
+ const ownParent = (host: Record<string, unknown>) => ({
+ host,
+ origin: { userId: mockUserId },
+ });
it('stores the executor the client declared', async () => {
await service.createOperation({ ...mockParams, autoStart: false, llmExecutor: executor });
@@ -576,7 +581,7 @@ describe('AgentRuntimeService', () => {
});
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 } });
+ await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));
mockCoordinator.saveAgentState.mockClear();
await service.createOperation({
@@ -586,11 +591,36 @@ describe('AgentRuntimeService', () => {
parentOperationId: 'parent-op',
});
const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
- expect(savedState.host.llmExecutor).toEqual(executor);
+ expect(savedState.host.llmExecutor).toEqual({
+ ...executor,
+ channelOperationId: 'parent-op',
+ });
+ });
+
+ it("lets an independent sub-agent inherit the parent's executor, relaying on the parent's channel", async () => {
+ await mockCoordinator.saveAgentState('parent-op', ownParent({ 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];
+ // The tab only subscribes to the parked parent's channel, so the
+ // child's `llm_execute` has to ride that one.
+ expect(savedState.host.llmExecutor).toEqual({
+ ...executor,
+ channelOperationId: 'parent-op',
+ });
});
- 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 } });
+ it("keeps a nested child on the channel the executor's tab subscribed to", async () => {
+ await mockCoordinator.saveAgentState(
+ 'parent-op',
+ ownParent({ llmExecutor: { ...executor, channelOperationId: 'root-op' } }),
+ );
mockCoordinator.saveAgentState.mockClear();
await service.createOperation({
@@ -600,6 +630,62 @@ describe('AgentRuntimeService', () => {
parentOperationId: 'parent-op',
});
const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.llmExecutor).toEqual({
+ ...executor,
+ channelOperationId: 'root-op',
+ });
+ });
+
+ it('relays on its own channel when the client declared the executor itself', async () => {
+ await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));
+ mockCoordinator.saveAgentState.mockClear();
+
+ const own = { ...executor, clientId: 'tab-b' };
+ await service.createOperation({
+ ...mockParams,
+ appContext: { ...mockParams.appContext, isSubAgent: true },
+ autoStart: false,
+ llmExecutor: own,
+ parentOperationId: 'parent-op',
+ });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.llmExecutor).toEqual(own);
+ });
+
+ it("does not inherit the executor of another user's run", async () => {
+ // A client names `parentOperationId`; a foreign run's executor would
+ // hand this child's LLM payload to that user's tab.
+ await mockCoordinator.saveAgentState('foreign-op', {
+ host: { llmExecutor: executor },
+ origin: { userId: 'someone-else' },
+ });
+ mockCoordinator.saveAgentState.mockClear();
+
+ await service.createOperation({
+ ...mockParams,
+ appContext: { ...mockParams.appContext, isSubAgent: true },
+ autoStart: false,
+ parentOperationId: 'foreign-op',
+ });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host).not.toHaveProperty('llmExecutor');
+ });
+
+ it("does not inherit the executor of the user's run in another workspace", async () => {
+ // The same user's run elsewhere relays with that workspace's providers.
+ await mockCoordinator.saveAgentState('other-workspace-op', {
+ host: { llmExecutor: executor },
+ origin: { userId: mockUserId, workspaceId: 'ws-other' },
+ });
+ mockCoordinator.saveAgentState.mockClear();
+
+ await service.createOperation({
+ ...mockParams,
+ appContext: { ...mockParams.appContext, isSubAgent: true },
+ autoStart: false,
+ parentOperationId: 'other-workspace-op',
+ });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
expect(savedState.host).not.toHaveProperty('llmExecutor');
});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 58e2a0bab3c..447f65c7ea3 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -806,23 +806,47 @@ export class AgentRuntimeService {
}
/**
- * 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.
+ * The relay executor a new run carries: the one its client declared, else
+ * its parent's, so a child run (group member, `callSubAgent` / `callAgent`
+ * sub-agent) on the same local model reaches the same device. No client
+ * subscribes to the child's own channel β€” the gateway only hands
+ * `llm_execute` to subscribers of the op it is sent on β€” so the inherited
+ * executor names the channel its tab does listen on: the parent's, or the
+ * one the parent already inherited. The parent stays subscribed meanwhile: it
+ * is parked (`waiting_for_async_tool`) or supervising its members.
+ * Only the caller's own parent in this workspace counts: a client can name
+ * any `parentOperationId`, and a foreign run's executor would hand this
+ * child's LLM payload to another user's tab, or to a tab of the same user
+ * relaying with another workspace's providers.
+ * Best-effort: an expired parent leaves the child without one.
*/
private async resolveLlmExecutor(
declared: AgentRunLlmExecutor | undefined,
parentOperationId: string | undefined,
- streamsOnParentChannel: boolean,
): Promise<AgentRunLlmExecutor | undefined> {
if (declared) return declared;
- if (!parentOperationId || !streamsOnParentChannel) return;
+ if (!parentOperationId) return;
- return this.getLlmExecutor(parentOperationId);
+ let parent: AgentState | null | undefined;
+ try {
+ parent = await this.coordinator.loadAgentState(parentOperationId);
+ } catch (error) {
+ log('[%s] Failed to read the parent relay executor: %O', parentOperationId, error);
+ return;
+ }
+ if (
+ parent?.origin?.userId !== this.userId ||
+ (parent.origin.workspaceId ?? undefined) !== (this.workspaceId ?? undefined)
+ )
+ return;
+
+ const inherited = parent.host?.llmExecutor;
+ if (!inherited) return;
+
+ return {
+ ...inherited,
+ channelOperationId: inherited.channelOperationId ?? parentOperationId,
+ };
}
/**
@@ -1359,11 +1383,7 @@ export class AgentRuntimeService {
}))
: undefined;
- const llmExecutor = await this.resolveLlmExecutor(
- params.llmExecutor,
- parentOperationId,
- appContext?.orchestrationRole === 'member',
- );
+ const llmExecutor = await this.resolveLlmExecutor(params.llmExecutor, parentOperationId);
// A member's pushes reach the supervisor's client, so it renders what
// that client declared.
const fileWorksAccepted =
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 3f5e4321fbc..cc2345b320f 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -585,7 +585,8 @@ export interface OperationCreationParams {
/**
* 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.
+ * inherits its parent's when it declares none, relaying on the parent's
+ * channel (`channelOperationId`).
*/
llmExecutor?: AgentRunLlmExecutor;
maxSteps?: number;
diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
index 97eca1f4d0a..dac1bfb4764 100644
--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
@@ -128,6 +128,17 @@ vi.mock('@/server/modules/ModelRuntime', () => ({
initModelRuntimeFromDB: vi.fn(),
}));
+const mockStreamManager = {
+ closeLlmRelayChannel: vi.fn(),
+ openLlmRelayChannel: vi.fn(),
+ sendLlmExecute: vi.fn(),
+};
+
+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ createStreamEventManager: () => mockStreamManager,
+}));
+
describe('AiAgentService.execSubAgent', () => {
let service: AiAgentService;
const mockDb = {} as any;
@@ -797,4 +808,110 @@ describe('AiAgentService.execSubAgent', () => {
);
});
});
+
+ describe('a sub-agent the tab dispatches itself (direct @mention)', () => {
+ // Bound to the personal scope the service runs in (`personal-<random>`).
+ const channel = 'llmcall:test-user-id:personal-3f2a9c1d8e7b4a60';
+ const executor = {
+ capabilities: ['llm_relay@1'],
+ clientId: 'tab-1',
+ providers: ['ollama'],
+ };
+ const params = {
+ agentId: 'agent-1',
+ instruction: 'Summarize',
+ // The tab's own, client-local operation: no server run to inherit from.
+ parentMessageId: 'parent-msg-1',
+ parentOperationId: 'client-local-op',
+ topicId: 'topic-1',
+ };
+
+ beforeEach(() => {
+ mockStreamManager.openLlmRelayChannel.mockResolvedValue(undefined);
+ mockStreamManager.closeLlmRelayChannel.mockResolvedValue(undefined);
+ });
+
+ it('relays the child on the channel the tab stands by on', async () => {
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+
+ await service.execSubAgent(params, { llmRelay: { channel, executor } });
+
+ expect(mockStreamManager.openLlmRelayChannel).toHaveBeenCalledWith(channel, userId);
+ expect(execAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ llmExecutor: { ...executor, channelOperationId: channel },
+ }),
+ );
+ });
+
+ it('ignores a channel that is not the caller own', async () => {
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+
+ await service.execSubAgent(params, {
+ llmRelay: { channel: 'llmcall:someone-else:nonce-12345678', executor },
+ });
+
+ expect(mockStreamManager.openLlmRelayChannel).not.toHaveBeenCalled();
+ expect(execAgentSpy.mock.calls[0][0]).not.toHaveProperty('llmExecutor');
+ });
+
+ it('ignores a channel bound to no workspace or another one', async () => {
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+
+ // A request's one-shot channel (no scope), and the user's channel of another workspace.
+ for (const other of [
+ 'llmcall:test-user-id:3f2a9c1d-8e7b-4a60-9c1d-8e7b4a603f2a',
+ 'llmcall:test-user-id:ws_other12345-3f2a9c1d8e7b4a60',
+ ]) {
+ await service.execSubAgent(params, { llmRelay: { channel: other, executor } });
+ }
+
+ expect(mockStreamManager.openLlmRelayChannel).not.toHaveBeenCalled();
+ for (const [call] of execAgentSpy.mock.calls) expect(call).not.toHaveProperty('llmExecutor');
+ });
+
+ it('accepts a channel bound to the workspace the request runs in', async () => {
+ const wsService = new AiAgentService(mockDb, userId, { workspaceId: 'ws_a1b2c3d4e5f6' });
+ const execAgentSpy = vi
+ .spyOn(wsService, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+ const wsChannel = 'llmcall:test-user-id:ws_a1b2c3d4e5f6-3f2a9c1d8e7b4a60';
+
+ await wsService.execSubAgent(params, { llmRelay: { channel, executor } });
+ expect(execAgentSpy.mock.calls[0][0]).not.toHaveProperty('llmExecutor');
+
+ await wsService.execSubAgent(params, { llmRelay: { channel: wsChannel, executor } });
+ expect(execAgentSpy.mock.calls[1][0]).toMatchObject({
+ llmExecutor: { ...executor, channelOperationId: wsChannel },
+ });
+ });
+
+ it('runs the child without an executor when the gateway does not open the channel', async () => {
+ mockStreamManager.openLlmRelayChannel.mockRejectedValue(new Error('gateway down'));
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+
+ await service.execSubAgent(params, { llmRelay: { channel, executor } });
+
+ expect(execAgentSpy.mock.calls[0][0]).not.toHaveProperty('llmExecutor');
+ });
+
+ it('ends only the caller own channel once the tab releases it', async () => {
+ expect(await service.releaseSubAgentLlmRelay(channel)).toEqual({ success: true });
+ expect(mockStreamManager.closeLlmRelayChannel).toHaveBeenCalledWith(channel);
+
+ mockStreamManager.closeLlmRelayChannel.mockClear();
+ expect(await service.releaseSubAgentLlmRelay('llmcall:someone-else:nonce-12345678')).toEqual({
+ success: false,
+ });
+ expect(mockStreamManager.closeLlmRelayChannel).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 9adc99b6500..2716ca2dfb4 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -34,6 +34,7 @@ import { TaskModel } from '@/database/models/task';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
import { AgentService } from '@/server/services/agent';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import type {
@@ -83,6 +84,8 @@ import { startOperation } from './pipeline/startOperation';
import { resolveNewTopicSnapshot, setupTurn } from './pipeline/turnSetup';
import { createRunFacts, type RunFacts } from './runFacts';
import { applyShareGateToAgentConfig } from './shareGate';
+import type { SubAgentLlmRelayRequest } from './subAgentLlmRelay';
+import { closeSubAgentLlmRelay, openSubAgentLlmRelay } from './subAgentLlmRelay';
import type { SubAgentRunDeps } from './subAgentRuns';
import { execAgentMember, execAgentThreadRun } from './subAgentRuns';
import { acquireTopicStartReservation, TopicStartReservationError } from './topicStartReservation';
@@ -1703,11 +1706,30 @@ export class AiAgentService {
* virtual sub-agent and it does not install the async completion bridge.
*/
// Arrow field (not a method) so it stays bound when handed to AgentRuntimeService.
- execSubAgent = async (params: ExecSubAgentParams): Promise<ExecSubAgentResult> =>
- execAgentThreadRun(this.subAgentRunDeps, params, {
+ execSubAgent = async (
+ params: ExecSubAgentParams,
+ options: {
+ /** The dispatching tab stands by on this channel to run the child's device-only LLM calls. */
+ llmRelay?: SubAgentLlmRelayRequest;
+ } = {},
+ ): Promise<ExecSubAgentResult> => {
+ const llmExecutor = await openSubAgentLlmRelay(options.llmRelay, {
+ streamManager: createStreamEventManager(),
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+
+ return execAgentThreadRun(this.subAgentRunDeps, params, {
isSubAgent: false,
+ llmExecutor,
logScope: 'execSubAgent',
});
+ };
+
+ /** The tab stopped standing by on a sub-agent's relay channel: end it on the gateway. */
+ releaseSubAgentLlmRelay = async (channel: string): Promise<{ success: boolean }> => ({
+ success: await closeSubAgentLlmRelay(channel, this.userId, createStreamEventManager()),
+ });
/**
* Execute a virtual sub-agent created by `lobe-agent.callSubAgent`.
diff --git a/apps/server/src/services/aiAgent/subAgentLlmRelay.ts b/apps/server/src/services/aiAgent/subAgentLlmRelay.ts
new file mode 100644
index 00000000000..11b6f8c6efa
--- /dev/null
+++ b/apps/server/src/services/aiAgent/subAgentLlmRelay.ts
@@ -0,0 +1,77 @@
+import { isOwnLlmRelayChannelId, isScopedLlmRelayChannelId } from '@lobechat/agent-gateway-client';
+import type { AgentRunLlmExecutor } from '@lobechat/agent-runtime';
+import type { ExecAgentLlmExecutor } from '@lobechat/types';
+import debug from 'debug';
+
+import type { IStreamEventManager } from '@/server/modules/AgentRuntime/types';
+
+const log = debug('lobe-server:ai-agent-service:sub-agent-llm-relay');
+
+/**
+ * A sub-agent a tab dispatches itself (`execSubAgentTask`, e.g. a direct
+ * `@agent` mention) has no server parent run whose relay executor it could
+ * inherit, and no tab subscribes to the child's own channel. So the tab
+ * subscribes to a one-shot relay channel (`llmcall:<userId>:…`) first and
+ * names it here; the child's `llm_execute` rides that channel.
+ */
+export interface SubAgentLlmRelayRequest {
+ /** The one-shot channel the dispatching tab subscribed to. */
+ channel: string;
+ /** The dispatching tab's executor declaration. */
+ executor: ExecAgentLlmExecutor;
+}
+
+export interface SubAgentLlmRelayScope {
+ streamManager: IStreamEventManager;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Open the requested channel on the gateway and return the executor the child
+ * run carries: the tab's declaration, relaying on that channel. `undefined`
+ * when the channel is not the caller's own or the deployment cannot relay β€”
+ * the child then runs without an executor, exactly as before.
+ */
+export const openSubAgentLlmRelay = async (
+ request: SubAgentLlmRelayRequest | undefined,
+ { streamManager, userId, workspaceId }: SubAgentLlmRelayScope,
+): Promise<AgentRunLlmExecutor | undefined> => {
+ if (!request) return;
+ // Only the caller's own channels, bound to the workspace this request runs
+ // in: anything else could name a real run's operation, another user's
+ // channel, or the user's tab of another workspace, whose providers differ.
+ if (!isScopedLlmRelayChannelId(request.channel, userId, workspaceId)) {
+ log('ignoring relay channel %s outside %s / %s', request.channel, userId, workspaceId);
+ return;
+ }
+ if (!streamManager.openLlmRelayChannel || !streamManager.sendLlmExecute) {
+ log('deployment cannot relay, child runs without an executor');
+ return;
+ }
+
+ try {
+ await streamManager.openLlmRelayChannel(request.channel, userId);
+ } catch (error) {
+ log('failed to open relay channel %s: %O', request.channel, error);
+ return;
+ }
+
+ return { ...request.executor, channelOperationId: request.channel };
+};
+
+/**
+ * End a channel opened by {@link openSubAgentLlmRelay}. The tab calls it once
+ * it stops standing by (the child finished or was given up), since only the
+ * tab knows when that is. Best effort.
+ */
+export const closeSubAgentLlmRelay = async (
+ channel: string,
+ userId: string,
+ streamManager: IStreamEventManager,
+): Promise<boolean> => {
+ if (!isOwnLlmRelayChannelId(channel, userId)) return false;
+
+ await streamManager.closeLlmRelayChannel?.(channel);
+ return true;
+};
diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.ts
index 5498e26a5ff..2a06e0b87ea 100644
--- a/apps/server/src/services/aiAgent/subAgentRuns.ts
+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts
@@ -1,3 +1,4 @@
+import type { AgentRunLlmExecutor } from '@lobechat/agent-runtime';
import { isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';
import type {
ExecAgentResult,
@@ -66,6 +67,12 @@ export interface ExecAgentThreadRunOptions {
*/
deviceId?: string;
isSubAgent: boolean;
+ /**
+ * Relay executor for the spawned run, when the dispatching tab stands by on a
+ * channel of its own (see `openSubAgentLlmRelay`). Unset, the run inherits
+ * its parent's, if any.
+ */
+ llmExecutor?: AgentRunLlmExecutor;
localDeviceId?: string;
logScope: 'execSubAgent' | 'execVirtualSubAgent';
/**
@@ -337,6 +344,7 @@ export const execAgentThreadRun = async (
chatConfigOverride: options.chatConfig,
deviceId: options.deviceId,
hooks,
+ ...(options.llmExecutor && { llmExecutor: options.llmExecutor }),
localDeviceId: options.localDeviceId,
// Explicit sub-agent model override resolved at the spawn site.
model: options.model,
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 651125ba137..a503b2101a2 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -1,3 +1,4 @@
+import type { AgentRunLlmExecutor } from '@lobechat/agent-runtime';
import type { BotPlatformContext } from '@lobechat/context-engine';
import type {
BotSenderMetadata,
@@ -185,6 +186,11 @@ export interface InternalExecAgentParams extends ExecAgentParams {
* and a refusal here destroys the message before it is ever persisted.
*/
interactiveStart?: boolean;
+ /**
+ * The client's relay executor. Server callers may also set the channel it
+ * relays on (`channelOperationId`), which a client never can.
+ */
+ llmExecutor?: AgentRunLlmExecutor;
/** Maximum steps for the agent operation */
maxSteps?: number;
/**
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index 531dd18b36d..0bdaf1d3704 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -49,11 +49,13 @@ export {
CLIENT_PROTOCOL_VERSION,
isLlmRelayChannelId,
isOwnLlmRelayChannelId,
+ isScopedLlmRelayChannelId,
LLM_RELAY_CAPABILITY,
LLM_RELAY_CHANNEL_HEADER,
LLM_RELAY_CHANNEL_PREFIX,
LLM_RELAY_CLIENT_ID_HEADER,
LLM_RELAY_LEASE_HEADER,
+ llmRelayChannelScope,
} from './protocol';
export { isSessionTerminalEvent } from './terminalEvent';
export type {
diff --git a/packages/agent-gateway-client/src/protocol.ts b/packages/agent-gateway-client/src/protocol.ts
index 4ff67445a49..7bcb498eb5e 100644
--- a/packages/agent-gateway-client/src/protocol.ts
+++ b/packages/agent-gateway-client/src/protocol.ts
@@ -63,3 +63,24 @@ export const isOwnLlmRelayChannelId = (channel: string, userId: string): boolean
const prefix = buildLlmRelayChannelId(userId, '');
return channel.startsWith(prefix) && CHANNEL_NONCE.test(channel.slice(prefix.length));
};
+
+/**
+ * The scope a channel that outlives one request (a sub-agent's relay) is bound
+ * to: the workspace the dispatching request runs in, `personal` outside one.
+ * It leads the nonce (`<scope>-<random>`), so a request in one workspace cannot
+ * name the same user's channel of another workspace, whose tab relays with
+ * that workspace's providers.
+ */
+export const llmRelayChannelScope = (workspaceId?: string | null): string =>
+ workspaceId || 'personal';
+
+/** Whether `channel` is `userId`'s own channel bound to `workspaceId`'s scope. */
+export const isScopedLlmRelayChannelId = (
+ channel: string,
+ userId: string,
+ workspaceId?: string | null,
+): boolean =>
+ isOwnLlmRelayChannelId(channel, userId) &&
+ channel
+ .slice(buildLlmRelayChannelId(userId, '').length)
+ .startsWith(`${llmRelayChannelScope(workspaceId)}-`);
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 478e2b31062..5c0459b5c72 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -234,6 +234,13 @@ export interface AgentRunClientLlmWait {
export interface AgentRunLlmExecutor {
/** Relay protocol versions the client speaks, e.g. `llm_relay@1`. */
capabilities: string[];
+ /**
+ * Operation whose gateway channel the client listens on, when it is not the
+ * run's own: a sub-agent inherits its parent's executor, but the tab only
+ * subscribed to the parent's run, so the sub-agent's `llm_execute` rides that
+ * channel. Set by the server, never by the client.
+ */
+ channelOperationId?: 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. */
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 8b5b8f142df..b8238c4f27d 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -194,6 +194,10 @@ export interface ExecSubAgentTaskParams {
/** Optional for Single Agent mode, required for Group mode */
groupId?: string;
instruction: string;
+ /** This tab runs the sub-agent's device-only LLM calls (with {@link llmRelayChannel}). */
+ llmExecutor?: ExecAgentLlmExecutor;
+ /** The one-shot relay channel this tab stands by on for the sub-agent's LLM calls. */
+ llmRelayChannel?: string;
parentMessageId: string;
/** Parent operation ID for dispatching callAgent hooks */
parentOperationId?: string;
@@ -335,6 +339,11 @@ class AiAgentService {
return await lambdaClient.aiAgent.execSubAgentTask.mutate(params);
}
+ /** This tab stopped standing by on the relay channel it named in `execSubAgentTask`. */
+ async releaseSubAgentLlmRelay(params: { channel: string }) {
+ return await lambdaClient.aiAgent.releaseSubAgentLlmRelay.mutate(params);
+ }
+
/**
* Get SubAgent task status by threadId
* Works for both Group and Single Agent mode tasks
diff --git a/src/services/llmRelay/executor.test.ts b/src/services/llmRelay/executor.test.ts
index a6ca5fe04ca..86ce7ae2187 100644
--- a/src/services/llmRelay/executor.test.ts
+++ b/src/services/llmRelay/executor.test.ts
@@ -189,6 +189,30 @@ describe('LlmRelayExecutor', () => {
expect(server.batches.some((batch) => batch.final)).toBe(false);
});
+ it("drops a sub-agent's attempt when the run whose channel delivered it ends", async () => {
+ const server = createServer();
+ const model = createModel();
+ const executor = new LlmRelayExecutor({
+ clientId: () => 'tab-1',
+ createRuntime: async () => model.runtime,
+ fetch: server.fetch,
+ });
+
+ // A child run's call rides its parent's channel but names the child.
+ const done = executor.execute(callData({ callId: 'child-op:0:1', operationId: 'child-op' }), {
+ channelOperationId: 'parent-op',
+ });
+ await waitFor(() => model.calls.length === 1);
+ model.emit('text', 'partial');
+
+ // The parent is interrupted: its terminal event ends the parent channel.
+ executor.cancelOperation('parent-op');
+ await done;
+
+ expect(model.calls[0].signal?.aborted).toBe(true);
+ expect(executor.isRunning('child-op:0:1')).toBe(false);
+ });
+
it('stops as soon as an upload ack says the server no longer wants the attempt', async () => {
const server = createServer((batch) =>
batch.chunks.length > 0
diff --git a/src/services/llmRelay/executor.ts b/src/services/llmRelay/executor.ts
index 10bac50347d..349e9825c7a 100644
--- a/src/services/llmRelay/executor.ts
+++ b/src/services/llmRelay/executor.ts
@@ -43,6 +43,12 @@ export interface LlmRelayExecutorDeps {
}
export interface ExecuteRelayCallOptions {
+ /**
+ * The run whose gateway channel delivered the call, when it is not the
+ * call's own: a sub-agent's call rides its parent's channel. That run ending
+ * ends the call too ({@link LlmRelayExecutor.cancelOperation}).
+ */
+ channelOperationId?: string;
/**
* Each protocol chunk this client produces for the call, as soon as it is
* produced β€” for rendering the reply locally before the server's echo.
@@ -54,6 +60,7 @@ export interface ExecuteRelayCallOptions {
type StopReason = LlmCancelData['reason'] | 'deadline' | 'operation_ended' | RelayUploadRejection;
interface ActiveCall {
+ channelOperationId?: string;
controller: AbortController;
operationId: string;
owned: boolean;
@@ -141,7 +148,8 @@ export class LlmRelayExecutor {
}
/**
- * The run ended (stopped, failed, finished): drop its in-flight attempts.
+ * The run ended (stopped, failed, finished): drop its in-flight attempts,
+ * and those of sub-agents relayed on its channel.
* Its `llm_cancel` can trail the terminal event, which closes the session
* that would deliver it. Nothing more is uploaded β€” the server has already
* settled the step, and a late `aborted` batch must not look like a lost
@@ -149,7 +157,8 @@ export class LlmRelayExecutor {
*/
cancelOperation(operationId: string) {
for (const call of this.active.values()) {
- if (call.operationId === operationId) call.stop('operation_ended');
+ if (call.operationId === operationId || call.channelOperationId === operationId)
+ call.stop('operation_ended');
}
}
@@ -163,6 +172,7 @@ export class LlmRelayExecutor {
let stopReason: StopReason | undefined;
const call: ActiveCall = {
+ channelOperationId: options.channelOperationId,
controller,
operationId: data.operationId,
owned: false,
diff --git a/src/services/llmRelay/index.ts b/src/services/llmRelay/index.ts
index 382dbffdc49..1589e791f63 100644
--- a/src/services/llmRelay/index.ts
+++ b/src/services/llmRelay/index.ts
@@ -78,6 +78,7 @@ export const oneShotRelay = new OneShotRelay({
},
isDeviceProvider: (provider) =>
aiProviderSelectors.isProviderFetchOnClient(provider)(getAiInfraStoreState()),
+ endOperation: (operationId) => llmRelayExecutor.cancelOperation(operationId),
onCancel: (data) => llmRelayExecutor.cancel(data),
onExecute: (data) => void llmRelayExecutor.execute(data),
subscribe: (channel, onEvent) => {
diff --git a/src/services/llmRelay/oneShot.test.ts b/src/services/llmRelay/oneShot.test.ts
index 58e19c67693..0849d50f4f8 100644
--- a/src/services/llmRelay/oneShot.test.ts
+++ b/src/services/llmRelay/oneShot.test.ts
@@ -131,6 +131,78 @@ describe('OneShotRelay', () => {
expect(close).toHaveBeenCalledTimes(1);
});
+ it('stops the calls a run relayed on the channel left running once it is released', async () => {
+ const endOperation = vi.fn();
+ const { close, emit, markReady, relay } = createRelay({ endOperation });
+
+ const result = relay.run('ollama', async () => {
+ // A sub-agent's call names the child run, not the channel.
+ emit({ data: { callId: 'c1', operationId: 'child-op' }, type: 'llm_execute' } as any);
+ return 'given up';
+ });
+ await vi.waitFor(() => expect(endOperation).not.toHaveBeenCalled());
+ markReady();
+
+ expect(await result).toBe('given up');
+ expect(endOperation).toHaveBeenCalledWith('child-op');
+ expect(close).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads a lazy provider list only once the provider runtime state is known', async () => {
+ let enabled: string[] = [];
+ let markKnown!: () => void;
+ const { deps, markReady, relay } = createRelay({
+ whenProvidersKnown: () =>
+ new Promise<void>((resolve) => {
+ markKnown = () => {
+ enabled = ['openai', 'ollama'];
+ resolve();
+ };
+ }),
+ });
+
+ // Read too early, the list would be empty and no channel would open.
+ const result = relay.run(
+ () => enabled,
+ async () => 'ok',
+ );
+ await Promise.resolve();
+ expect(deps.subscribe).not.toHaveBeenCalled();
+
+ markKnown();
+ await vi.waitFor(() => expect(deps.subscribe).toHaveBeenCalled());
+ markReady();
+ expect(await result).toBe('ok');
+ });
+
+ it('binds the channel to a scope when asked', async () => {
+ const { deps, markReady, relay } = createRelay();
+
+ const result = relay.run('ollama', async () => 'ok', { scope: 'ws_a1b2c3d4e5f6' });
+ await vi.waitFor(() => expect(deps.subscribe).toHaveBeenCalled());
+ markReady();
+ await result;
+
+ const [channel] = vi.mocked(deps.subscribe).mock.calls[0];
+ expect(channel).toMatch(/^llmcall:user-1:ws_a1b2c3d4e5f6-[\da-f]{32}$/);
+ });
+
+ it('stands by for a list of providers when any of them needs this tab', async () => {
+ const { deps, markReady, relay } = createRelay();
+ const request = vi.fn(async () => 'ok');
+
+ expect(await relay.run(['openai'], request)).toBe('ok');
+ expect(deps.subscribe).not.toHaveBeenCalled();
+
+ const result = relay.run(['openai', 'ollama'], request);
+ await vi.waitFor(() => expect(deps.subscribe).toHaveBeenCalled());
+ markReady();
+ expect(await result).toBe('ok');
+ expect(request).toHaveBeenLastCalledWith(
+ expect.objectContaining({ channel: expect.stringMatching(/^llmcall:user-1:/) }),
+ );
+ });
+
it('releases the channel when the request fails', async () => {
const { close, markReady, relay } = createRelay();
const result = relay.run('ollama', async () => {
diff --git a/src/services/llmRelay/oneShot.ts b/src/services/llmRelay/oneShot.ts
index ffd3a28837d..90cf6aca3d9 100644
--- a/src/services/llmRelay/oneShot.ts
+++ b/src/services/llmRelay/oneShot.ts
@@ -37,6 +37,12 @@ export interface OneShotChannelSubscription {
export interface OneShotRelayDeps {
clientId?: () => string;
+ /**
+ * Stop what a run relayed on this channel left running here, once the
+ * channel is released. A sub-agent's calls name the child run, not the
+ * channel, so its in-flight call would otherwise outlive the wait.
+ */
+ endOperation?: (operationId: string) => void;
/** The deployment can relay: `agent_llm_relay` is on and an Agent Gateway is configured. */
isAvailable: () => boolean;
/** Whether calls to `provider` leave from this device (shared `fetchOnClient` rule). */
@@ -119,12 +125,21 @@ export class OneShotRelay {
* to `provider`: `request` gets the headers to send, and the channel is
* released once it settles (`signal`: an aborted caller stops waiting for
* the subscription). A provider the server reaches itself runs
- * `request` as-is, without a channel.
+ * `request` as-is, without a channel. A list stands by when any of them
+ * needs this tab β€” for a request whose provider only the server resolves;
+ * pass it as a function to read it once the provider runtime state is known.
*/
async run<T>(
- provider: string | undefined,
+ provider: string | string[] | (() => string[]) | undefined,
request: (relay?: OneShotRelayHandle) => Promise<T>,
- { signal }: { signal?: AbortSignal } = {},
+ {
+ scope,
+ signal,
+ }: {
+ /** Bind the channel to a scope (`llmRelayChannelScope`), for a server that checks it. */
+ scope?: string;
+ signal?: AbortSignal;
+ } = {},
): Promise<T> {
const providersLoading =
provider && this.deps.isAvailable() ? this.deps.whenProvidersKnown?.() : undefined;
@@ -134,12 +149,21 @@ export class OneShotRelay {
await withTimeout(providersLoading, undefined, signal);
if (signal?.aborted) return request();
}
- if (!this.needsRelay(provider)) return request();
+ const resolved = typeof provider === 'function' ? provider() : provider;
+ const providers = Array.isArray(resolved) ? resolved : [resolved];
+ if (!providers.some((item) => this.needsRelay(item))) return request();
- const channel = buildLlmRelayChannelId(this.deps.userId()!, randomNonce());
+ const channel = buildLlmRelayChannelId(
+ this.deps.userId()!,
+ scope ? `${scope}-${randomNonce().replaceAll('-', '')}` : randomNonce(),
+ );
+ const operationIds = new Set<string>();
const subscribing = this.deps.subscribe(channel, (event) => {
- if (event.type === 'llm_execute') this.deps.onExecute(event.data as LlmExecuteData);
- else if (event.type === 'llm_cancel') this.deps.onCancel(event.data as LlmCancelData);
+ if (event.type === 'llm_execute') {
+ const data = event.data as LlmExecuteData;
+ if (data.operationId) operationIds.add(data.operationId);
+ this.deps.onExecute(data);
+ } else if (event.type === 'llm_cancel') this.deps.onCancel(event.data as LlmCancelData);
});
try {
@@ -154,7 +178,7 @@ export class OneShotRelay {
// An aborted caller has nothing to wait for: its request settles at once.
signal,
);
- log('channel %s for %s: subscription %s', channel, provider, outcome);
+ log('channel %s for %o: subscription %s', channel, resolved, outcome);
return await request({
channel,
@@ -164,6 +188,7 @@ export class OneShotRelay {
},
});
} finally {
+ for (const operationId of operationIds) this.deps.endOperation?.(operationId);
// A subscription that lands after the request settled is released too.
subscribing.then(
(subscription) => subscription.close(),
diff --git a/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts b/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts
index c523fd7db4c..2e6f455b1c4 100644
--- a/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts
@@ -2,6 +2,7 @@ import { type ExecSubAgentParams, ThreadStatus } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiAgentService } from '@/services/aiAgent';
+import { buildLlmExecutorDeclaration, oneShotRelay } from '@/services/llmRelay';
import type { ChatStore } from '@/store/chat/store';
import { ClientSubAgentTransport } from './ClientSubAgentTransport';
@@ -11,9 +12,19 @@ vi.mock('@/services/aiAgent', () => ({
execSubAgentTask: vi.fn(),
getSubAgentTaskStatus: vi.fn(),
interruptTask: vi.fn(),
+ releaseSubAgentLlmRelay: vi.fn(),
},
}));
+vi.mock('@/business/client/trpc-headers', () => ({
+ getBusinessTrpcHeaders: vi.fn(async () => ({ 'X-Workspace-Id': 'ws_a1b2c3d4e5f6' })),
+}));
+
+vi.mock('@/services/llmRelay', () => ({
+ buildLlmExecutorDeclaration: vi.fn(),
+ oneShotRelay: { run: vi.fn() },
+}));
+
const params: ExecSubAgentParams = {
agentId: 'agent-1',
groupId: 'group-1',
@@ -53,6 +64,10 @@ describe('ClientSubAgentTransport', () => {
vi.clearAllMocks();
vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValue(dispatchResult);
vi.mocked(aiAgentService.interruptTask).mockResolvedValue({ success: true });
+ vi.mocked(aiAgentService.releaseSubAgentLlmRelay).mockResolvedValue({ success: true });
+ // Outside the `agent_llm_relay` rollout: no executor, the request runs as-is.
+ vi.mocked(buildLlmExecutorDeclaration).mockReturnValue(undefined);
+ vi.mocked(oneShotRelay.run).mockImplementation(async (_provider, request) => request());
});
afterEach(() => {
@@ -184,4 +199,49 @@ describe('ClientSubAgentTransport', () => {
success: false,
});
});
+
+ it('stands by on a relay channel while the child runs, so its device-only LLM calls reach this tab', async () => {
+ const { store } = createStore();
+ const llmExecutor = {
+ capabilities: ['llm_relay@1'],
+ clientId: 'tab-1',
+ providers: ['ollama', 'openai'],
+ };
+ const channel = 'llmcall:user-1:ws_a1b2c3d4e5f6-3f2a9c1d8e7b4a60';
+ let standingBy = false;
+ vi.mocked(buildLlmExecutorDeclaration).mockImplementation(() =>
+ // The provider runtime state loads after the transport is called.
+ vi.mocked(oneShotRelay.run).mock.calls.length > 0 ? llmExecutor : undefined,
+ );
+ vi.mocked(oneShotRelay.run).mockImplementation(async (provider, request, options) => {
+ // Bound to the workspace the dispatch runs in.
+ expect(options).toMatchObject({ scope: 'ws_a1b2c3d4e5f6' });
+ // The providers are read when the relay asks for them, after the
+ // provider runtime state has loaded β€” not snapshotted at dispatch.
+ expect(typeof provider === 'function' ? provider() : provider).toEqual(['ollama', 'openai']);
+ standingBy = true;
+ try {
+ return await request({ channel, headers: {} });
+ } finally {
+ standingBy = false;
+ }
+ });
+ vi.mocked(aiAgentService.getSubAgentTaskStatus).mockImplementation(async () => {
+ // Still subscribed while the child is polled.
+ expect(standingBy).toBe(true);
+ return { result: 'done', status: 'completed' } as any;
+ });
+
+ const result = await new ClientSubAgentTransport(() => store, 'root-operation').execSubAgent(
+ params,
+ );
+
+ expect(aiAgentService.execSubAgentTask).toHaveBeenCalledWith({
+ ...params,
+ llmExecutor,
+ llmRelayChannel: channel,
+ });
+ expect(aiAgentService.releaseSubAgentLlmRelay).toHaveBeenCalledWith({ channel });
+ expect(result).toMatchObject({ result: 'done', status: 'completed', success: true });
+ });
});
diff --git a/src/store/chat/agents/transports/ClientSubAgentTransport.ts b/src/store/chat/agents/transports/ClientSubAgentTransport.ts
index 071f6852b26..be75d6092e4 100644
--- a/src/store/chat/agents/transports/ClientSubAgentTransport.ts
+++ b/src/store/chat/agents/transports/ClientSubAgentTransport.ts
@@ -1,7 +1,11 @@
+import { llmRelayChannelScope } from '@lobechat/agent-gateway-client';
import type { SubAgentExecutionResult, SubAgentTransport } from '@lobechat/agent-runtime';
import type { ExecSubAgentParams, ExecVirtualSubAgentParams } from '@lobechat/types';
+import { getBusinessTrpcHeaders } from '@/business/client/trpc-headers';
+import type { ExecSubAgentTaskParams } from '@/services/aiAgent';
import { aiAgentService } from '@/services/aiAgent';
+import { buildLlmExecutorDeclaration, oneShotRelay } from '@/services/llmRelay';
import type { ChatStore } from '@/store/chat/store';
const DEFAULT_TIMEOUT_MS = 1_800_000;
@@ -45,7 +49,44 @@ export class ClientSubAgentTransport implements SubAgentTransport {
return this.execute(params);
}
+ /**
+ * The child runs on the server, but a device-only model (a local Ollama, any
+ * `fetchOnClient` provider) can only run on this tab β€” and no server run
+ * here has an executor for the child to inherit. So this tab stands by on a
+ * relay channel of its own for as long as it waits on the child, and names
+ * it in the dispatch; the server relays the child's LLM calls on it. Which
+ * model the child uses is the server's call, so any device provider this tab
+ * runs is reason enough. Both are read once the provider runtime state has
+ * loaded, so a mention sent right after the page opens still stands by.
+ */
private async execute(params: ExecSubAgentParams): Promise<SubAgentExecutionResult> {
+ // The server accepts only a channel bound to the workspace it runs the
+ // dispatch in β€” the one the business headers name.
+ const workspaceId = (await getBusinessTrpcHeaders())['X-Workspace-Id'];
+
+ return oneShotRelay.run(
+ () => buildLlmExecutorDeclaration()?.providers ?? [],
+ async (relay) => {
+ const llmExecutor = relay && buildLlmExecutorDeclaration();
+ if (!relay || !llmExecutor) return this.dispatchAndWait(params);
+
+ try {
+ return await this.dispatchAndWait({
+ ...params,
+ llmExecutor,
+ llmRelayChannel: relay.channel,
+ });
+ } finally {
+ void aiAgentService
+ .releaseSubAgentLlmRelay({ channel: relay.channel })
+ .catch(() => undefined);
+ }
+ },
+ { scope: llmRelayChannelScope(workspaceId) },
+ );
+ }
+
+ private async dispatchAndWait(params: ExecSubAgentTaskParams): Promise<SubAgentExecutionResult> {
let dispatchResult: Awaited<ReturnType<typeof aiAgentService.execSubAgentTask>> | undefined;
let interruptPromise: Promise<void> | undefined;
const interrupt = () => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts
index a0994670a66..e6037ffe5aa 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts
@@ -105,7 +105,10 @@ describe('createGatewayEventHandler β€” LLM relay', () => {
});
handler(makeEvent('llm_execute', execute()));
- expect(relay.execute).toHaveBeenCalledWith(execute(), { onOutput: expect.any(Function) });
+ expect(relay.execute).toHaveBeenCalledWith(execute(), {
+ channelOperationId: 'op-1',
+ onOutput: expect.any(Function),
+ });
emit({ data: 'Hello', type: 'text' });
emit({ data: ' world', type: 'text' });
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 668ef988d3f..d11dbe6c591 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -1151,6 +1151,8 @@ export const createGatewayEventHandler = (
const data = event.data as LlmExecuteData | undefined;
if (!data?.callId || context.agentShareId) break;
void llmRelayExecutor.execute(data, {
+ // A sub-agent's call rides this run's channel: this run ending ends it.
+ channelOperationId: event.operationId || gatewayOperationId,
onOutput: (chunk) => {
enqueue(() => applyLocalRelayOutput(data, chunk));
},