🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): block nested sub-agent calls (#15575)
Arvin Xu126075624659
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.tsindex c1be7093a93..78a08b173de 100644--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts@@ -2405,6 +2405,7 @@ export const createRuntimeExecutors = (execSubAgent: ctx.execSubAgent,executionTimeoutMs: timeoutMs,groupId: state.metadata?.groupId,+ isSubAgent: state.metadata?.isSubAgent === true,memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,messageId: state.metadata?.sourceMessageId,operationId,@@ -2985,6 +2986,7 @@ export const createRuntimeExecutors = (execSubAgent: ctx.execSubAgent,executionTimeoutMs: timeoutMs,groupId: state.metadata?.groupId,+ isSubAgent: state.metadata?.isSubAgent === true,memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,messageId: state.metadata?.sourceMessageId,operationId,@@ -3366,6 +3368,32 @@ export const createRuntimeExecutors = (// targetAgentId is a cloud extension injected by agentManagement.callAgentconst targetAgentId = (task as any).targetAgentId ?? agentId;+ if (state.metadata?.isSubAgent === true) {+ log('[%s] Nested sub-agent dispatch blocked', taskLogId);+ return {+ events,+ newState: state,+ nextContext: {+ payload: {+ parentMessageId,+ result: {+ error: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ success: false,+ taskMessageId: parentMessageId,+ threadId: '',+ },+ },+ phase: 'sub_agent_result',+ session: {+ messageCount: state.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ } as unknown as AgentRuntimeContext,+ };+ }+let taskMessageId: string | undefined;try {const taskMessage = await ctx.messageModel.create({@@ -3461,6 +3489,33 @@ export const createRuntimeExecutors = (log('[%s] Starting batch of %d tasks', taskLogId, tasks.length);+ if (state.metadata?.isSubAgent === true) {+ log('[%s] Nested sub-agent batch dispatch blocked', taskLogId);+ return {+ events,+ newState: state,+ nextContext: {+ payload: {+ parentMessageId,+ results: tasks.map((task) => ({+ description: task.description,+ error: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ success: false,+ taskMessageId: parentMessageId,+ threadId: '',+ })),+ },+ phase: 'sub_agents_batch_result',+ session: {+ messageCount: state.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ } as unknown as AgentRuntimeContext,+ };+ }+let lastTaskMessageId: string | undefined;const taskResults: Array<{ success: boolean; taskMessageId: string; threadId: string }> = [];diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 909ee705d4c..fdd87785c6b 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -4769,6 +4769,46 @@ describe('RuntimeExecutors', () => {expect(result.nextContext?.phase).toBe('sub_agent_result');});+ it('exec_sub_agent blocks nested dispatch when current state is already a sub-agent', async () => {+ const mockExecSubAgentTask = vi.fn();+ const ctxWithCallback = {+ ...ctx,+ execSubAgentTask: mockExecSubAgentTask,+ topicId: 'topic-123',+ };++ const executors = createRuntimeExecutors(ctxWithCallback);+ const state = createMockState({+ metadata: {+ agentId: 'parent-agent-id',+ isSubAgent: true,+ topicId: 'topic-123',+ },+ });++ const instruction = {+ payload: {+ parentMessageId: 'tool-msg-id',+ task: {+ description: 'Nested call',+ instruction: 'Do nested work',+ targetAgentId: 'target-agent-id',+ },+ },+ type: 'exec_sub_agent' as const,+ };++ const result = await executors.exec_sub_agent!(instruction as any, state);++ expect(result.nextContext?.phase).toBe('sub_agent_result');+ expect((result.nextContext?.payload as any).result).toMatchObject({+ error: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ success: false,+ });+ expect(mockMessageModel.create).not.toHaveBeenCalled();+ expect(mockExecSubAgentTask).not.toHaveBeenCalled();+ });+it('exec_sub_agent gracefully skips dispatch when execSubAgent not injected', async () => {// No callback injected (e.g. in tests that don't set it up)const executors = createRuntimeExecutors(ctx);diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex b383d154e26..67c98b00470 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -168,6 +168,7 @@ export interface OperationCreationParams {defaultTaskAssigneeAgentId?: string;documentId?: string | null;groupId?: string | null;+ isSubAgent?: boolean;scope?: string | null;/** Source user message ID used for same-turn Agent Signal procedure suppression. */sourceMessageId?: string;diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 77ae05e1f0a..0fc2ac0e8b8 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -2,7 +2,7 @@ import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';import { builtinSkills } from '@lobechat/builtin-skills';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';-import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';+import { LobeAgentIdentifier, LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';@@ -629,6 +629,10 @@ export class AiAgentService {log('execAgent: injected task-agent runtime for task scope');}+ if (appContext?.isSubAgent) {+ agentConfig.plugins = agentConfig.plugins?.filter((id) => id !== LobeAgentIdentifier);+ }+await throwIfExecutionAborted('agent configuration');// 2.5. Append additional instructions to agent's systemRole@@ -2545,6 +2549,7 @@ export class AiAgentService {defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,documentId: appContext?.documentId,groupId: appContext?.groupId,+ isSubAgent: appContext?.isSubAgent,scope: appContext?.scope,sourceMessageId: userMessageRecord?.id ?? parentMessageId ?? undefined,taskId: operationTaskId,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.tsindex cd395b8a436..a48b80c0a5b 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts@@ -506,6 +506,21 @@ describe('lobeAgentRuntime', () => {});describe('callSubAgent', () => {+ it('rejects nested sub-agent execution without calling the injected runner', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi.fn();++ const result = await runtime.callSubAgent(+ { description: 'Research', instruction: 'Find the answer' },+ { ...baseContext, isSubAgent: true, subAgent: { run } } as ToolExecutionContext,+ );++ expect(result.success).toBe(false);+ expect(result.deferred).toBeUndefined();+ expect(result).toMatchObject({ error: { code: 'NESTED_SUB_AGENT_NOT_ALLOWED' } });+ expect(run).not.toHaveBeenCalled();+ });+it('returns a deferred result and kicks off the sub-agent via the injected runner', async () => {const runtime = lobeAgentRuntime.factory(baseContext);const run = vidiff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex 4b019e1d855..b6d44d8e763 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -132,6 +132,13 @@ class LobeAgentExecutionRuntime {params: CallSubAgentParams,ctx: ToolExecutionContext,): Promise<BuiltinServerRuntimeOutput> => {+ if (ctx.isSubAgent) {+ return buildError(+ 'Sub-agent calls cannot be triggered from within another sub-agent.',+ 'NESTED_SUB_AGENT_NOT_ALLOWED',+ );+ }+if (!ctx.subAgent) {return buildError('Sub-agent execution is not available in this runtime.',diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex e9126bfa40a..0866ddeeec2 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -70,6 +70,8 @@ export interface ToolExecutionContext {executionTimeoutMs?: number;/** Current group ID for group chat context */groupId?: string | null;+ /** Whether this tool call is executing inside an isolated sub-agent run. */+ isSubAgent?: boolean;/*** Optional server-owned embedding runtime for memory search.*diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex 77a8cf2656a..311414f0745 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -137,6 +137,15 @@ const createAbortController = (signal?: AbortSignal) => {const isVisualSourceMessage = (message: unknown): message is VisualSourceMessage =>!!message && typeof message === 'object';+const nestedSubAgentDisabledResult = (): BuiltinToolResult => ({+ content: 'Nested sub-agent execution is not allowed.',+ error: {+ message: 'Sub-agent calls cannot be triggered from within another sub-agent.',+ type: 'NestedSubAgentNotAllowed',+ },+ success: false,+});+class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {readonly identifier = LobeAgentManifest.identifier;protected readonly apiEnum = LobeAgentApiName;@@ -367,6 +376,10 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {params: CallSubAgentParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {+ if (ctx.isSubAgent) {+ return nestedSubAgentDisabledResult();+ }+const { description, instruction, inheritMessages, timeout } = params;if (!description || !instruction) {diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex ab0773577f8..7d64db89cfd 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -73,6 +73,11 @@ export interface ExecAgentAppContext {repos?: string[];workingDirectory?: string;};+ /**+ * Whether this operation is an isolated sub-agent execution. Used to disable+ * recursive sub-agent dispatch.+ */+ isSubAgent?: boolean;/** Scope identifier */scope?: string | null;/** Session ID */diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.tsindex 3dbcf9a1b78..b631339d14b 100644--- a/packages/types/src/conversation.ts+++ b/packages/types/src/conversation.ts@@ -156,6 +156,11 @@ export interface ConversationContext {* panels (Task Manager) that maintain their own topic pointer.*/isolatedTopic?: boolean;+ /**+ * Whether this conversation is an isolated sub-agent execution spawned by+ * another agent. Used to disable recursive sub-agent dispatch.+ */+ isSubAgent?: boolean;/*** Whether the current agent is the Supervisor in group orchestration* - Used to mark assistant messages with metadata.isSupervisordiff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex d3c31f15313..1921b48db43 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -467,6 +467,12 @@ export interface BuiltinToolContext {*/groupOrchestration?: GroupOrchestrationCallbacks;+ /**+ * Whether the current tool is executing inside a sub-agent. Sub-agents must+ * not spawn additional sub-agents.+ */+ isSubAgent?: boolean;+/*** The tool message ID*/diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 0851a619a0f..099b0fcaf09 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -510,7 +510,11 @@ export class StreamingExecutorActionImpl {if (!operationId) {const { operationId: newOperationId } = this.#get().startOperation({type: 'execAgentRuntime',- context: { ...context, messageId: parentMessageId },+ context: {+ ...context,+ ...(isSubAgent ? { isSubAgent: true } : {}),+ messageId: parentMessageId,+ },parentOperationId: params.parentOperationId, // Pass parent operation IDlabel: 'AI Generation',metadata: {@@ -1041,7 +1045,13 @@ export class StreamingExecutorActionImpl {void this.#get().refreshThreads();// 2. Build the sub-agent ConversationContext (threadId provides isolation)- const subContext: ConversationContext = { agentId, scope: 'thread', threadId, topicId };+ const subContext: ConversationContext = {+ agentId,+ isSubAgent: true,+ scope: 'thread',+ threadId,+ topicId,+ };// 3. Create a child operation chained to the parent runtime operationconst { operationId: taskOperationId } = this.#get().startOperation({diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.tsindex 8e82e5c8380..150ccd8913b 100644--- a/src/store/chat/slices/plugin/action.test.ts+++ b/src/store/chat/slices/plugin/action.test.ts@@ -360,6 +360,64 @@ describe('ChatPluginAction', () => {expect(capturedContext?.toolCallId).toBe('tool-call-1');});+ it('should pass sub-agent context to Tool Store executor', async () => {+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);++ const { result } = renderHook(() => useChatStore());+ const messageId = 'sub-agent-tool-message-id';++ act(() => {+ const rootOperationId = result.current.startOperation({+ type: 'execClientSubAgent',+ context: {+ agentId: 'agent-1',+ isSubAgent: true,+ messageId: 'sub-agent-user-msg-1',+ scope: 'thread',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ }).operationId;++ const toolOperationId = result.current.startOperation({+ type: 'executeToolCall',+ context: { messageId },+ parentOperationId: rootOperationId,+ }).operationId;++ result.current.associateMessageWithOperation(messageId, toolOperationId);+ });++ let capturedContext: BuiltinToolContext | undefined;+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(+ async (_id, _api, _params, ctx) => {+ capturedContext = ctx;+ return { success: true };+ },+ );++ const payload = {+ identifier: 'test-tool',+ apiName: 'mockBuiltinAction',+ arguments: JSON.stringify({ input: 'test' }),+ id: 'tool-call-1',+ type: 'builtin',+ } as ChatToolPayload;++ await act(async () => {+ await result.current.invokeBuiltinTool(messageId, payload);+ });++ expect(capturedContext).toMatchObject({+ agentId: 'agent-1',+ isSubAgent: true,+ messageId,+ scope: 'thread',+ topicId: 'topic-1',+ });+ });+it('should fall back to root operation message id as source message id', async () => {const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex cda942b5822..64d83b40116 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -113,6 +113,8 @@ export class PluginTypesActionImpl {const viewedTask = operation?.context?.viewedTask ?? rootRuntimeOperationContext?.viewedTask;const taskId = viewedTask?.type === 'detail' ? viewedTask.taskId : undefined;const topicId = operation?.context?.topicId ?? rootRuntimeOperationContext?.topicId;+ const isSubAgent =+ operation?.context?.isSubAgent ?? rootRuntimeOperationContext?.isSubAgent ?? false;// For agent-builder tools, inject activeAgentId from store if not in context// This is needed because AgentBuilderProvider uses a separate scope for messages@@ -186,6 +188,7 @@ export class PluginTypesActionImpl {messageId: id,operationId,rootRuntimeOperationId,+ isSubAgent,scope,taskId,topicId,@@ -198,6 +201,7 @@ export class PluginTypesActionImpl {documentId,groupId,groupOrchestration,+ isSubAgent,messageId: id,operationId,registerAfterCompletion,diff --git a/src/store/tool/slices/builtin/executors/index.test.ts b/src/store/tool/slices/builtin/executors/index.test.tsindex 76772e3d57f..3973557fec7 100644--- a/src/store/tool/slices/builtin/executors/index.test.ts+++ b/src/store/tool/slices/builtin/executors/index.test.ts@@ -5,7 +5,7 @@ import {} from '@lobechat/builtin-tool-web-onboarding';import { describe, expect, it, vi } from 'vitest';-import { getApiNamesForIdentifier, hasExecutor } from './index';+import { getApiNamesForIdentifier, hasExecutor, invokeExecutor } from './index';vi.hoisted(() => {const storage = new Map<string, string>();@@ -41,4 +41,27 @@ describe('builtin executor registry', () => {it('registers visual understanding executor APIs', () => {expect(hasExecutor(LobeAgentIdentifier, LobeAgentApiName.analyzeVisualMedia)).toBe(true);});++ it('rejects nested sub-agent execution', async () => {+ const subAgentRun = vi.fn();+ const baseContext = {+ isSubAgent: true,+ messageId: 'tool-message-id',+ subAgent: { run: subAgentRun },+ };++ await expect(+ invokeExecutor(+ LobeAgentIdentifier,+ LobeAgentApiName.callSubAgent,+ { description: 'Nested work', instruction: 'Do nested work' },+ baseContext,+ ),+ ).resolves.toMatchObject({+ error: { type: 'NestedSubAgentNotAllowed' },+ success: false,+ });++ expect(subAgentRun).not.toHaveBeenCalled();+ });});