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.

πŸ› fix(agent-runtime): stop sub-agent runs from activating callAgent or being told to delegate (#20060)

Arvin Xua140b392fc4a
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index f27a123647d..99c5636a7bd 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -117,6 +117,7 @@ export const buildServerCallLlmContext = async ({
enabledToolIds: resolved.enabledToolIds,
executionTarget,
features: resolveServerConnectorFeatures(),
+ isSubAgent: state.origin?.lineage?.isSubAgent === true,
mentionedAgents: (state as any).initialContext?.initialContext?.mentionedAgents,
messages: messagesForContext,
shareVisitor: state.principal?.actor?.shareVisitor ?? ctx.agentShareVisitor,
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index ea974af7a75..a1f20e5c619 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -26,6 +26,7 @@ import {
} from '@lobechat/mecha';
import { FILE_INLINE_MAX_CHARS, isOversizedFileContent } from '@lobechat/prompts';
import type {
+ BuiltinToolResolveContext,
ChatTopicBotContext,
FrozenCredentialFacts,
FrozenModelFacts,
@@ -1058,6 +1059,38 @@ export const discoverTools = async (
const activeComposioManifests = dropDisabledManifests(composioManifests);
const activeConnectorManifests = dropDisabledManifests(connectorManifests);
+ // Context-aware builtin manifests: inside a sub-agent (or group) run,
+ // lobe-agent drops `callSubAgent` so the model can't recurse into nested
+ // sub-agents (which the runtime rejects, looping until the inactivity
+ // watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.
+ // `executionEnv` mirrors the resolved plan, while preserving the local
+ // target for a routed desktop because its readFile implementation can
+ // return images. It also keeps the `device-unrouted` degradation, where
+ // the user picked a local device that is offline and exec silently lands
+ // in the sandbox.
+ // For bot conversations we also pass the IM platform so `lobe-message`
+ // can drop APIs the platform can't fulfil (e.g. WeChat has no
+ // `readMessages`). Telegram Guest Mode uses a stricter overlay β€”
+ // the bot is not a chat member and has no regular channel tools.
+ // The discovery pool below resolves with the same context, so a tool
+ // activated mid-run carries the trimmed manifest too.
+ const manifestContext: BuiltinToolResolveContext = {
+ ...(botContext?.platform && {
+ botPlatform: {
+ id: botContext.platform,
+ unsupportedMessageApis: resolveUnsupportedMessageApis(
+ botContext.platform,
+ botContext.platformThreadId,
+ ),
+ },
+ }),
+ executionEnv: executionPlanToManifestExecutionEnv(executionPlan, localDeviceId),
+ executionEnvUnroutedReason:
+ executionPlan.kind === 'device-unrouted' ? executionPlan.reason : undefined,
+ isSubAgent: appContext?.isSubAgent,
+ scope: appContext?.scope ?? undefined,
+ };
+
toolsEngine = createServerAgentToolsEngine(toolsContext, {
additionalManifests: [
...activeLobehubSkillManifests,
@@ -1089,35 +1122,7 @@ export const discoverTools = async (
isBotConversation,
isGroupSupervisor,
modelAbilities,
- // Context-aware builtin manifests: inside a sub-agent (or group) run,
- // lobe-agent drops `callSubAgent` so the model can't recurse into nested
- // sub-agents (which the runtime rejects, looping until the inactivity
- // watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.
- // `executionEnv` mirrors the resolved plan, while preserving the local
- // target for a routed desktop because its readFile implementation can
- // return images. It also keeps the `device-unrouted` degradation, where
- // the user picked a local device that is offline and exec silently lands
- // in the sandbox.
- // For bot conversations we also pass the IM platform so `lobe-message`
- // can drop APIs the platform can't fulfil (e.g. WeChat has no
- // `readMessages`). Telegram Guest Mode uses a stricter overlay β€”
- // the bot is not a chat member and has no regular channel tools.
- manifestContext: {
- ...(botContext?.platform && {
- botPlatform: {
- id: botContext.platform,
- unsupportedMessageApis: resolveUnsupportedMessageApis(
- botContext.platform,
- botContext.platformThreadId,
- ),
- },
- }),
- executionEnv: executionPlanToManifestExecutionEnv(executionPlan, localDeviceId),
- executionEnvUnroutedReason:
- executionPlan.kind === 'device-unrouted' ? executionPlan.reason : undefined,
- isSubAgent: appContext?.isSubAgent,
- scope: appContext?.scope ?? undefined,
- },
+ manifestContext,
model,
provider,
useApplicationBuiltinSearchTool: searchDecision.useApplicationBuiltinSearchTool,
@@ -1177,6 +1182,7 @@ export const discoverTools = async (
exclusivePluginIds,
executionTarget: executionPlan.target,
lobehubSkills: activeLobehubSkillManifests,
+ manifestContext,
});
Object.assign(toolManifestMap, discovery.manifestMap);
Object.assign(toolSourceMap, discovery.sourceMap);
diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts
index 1b939f6bd49..9f099e6605e 100644
--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts
+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts
@@ -299,6 +299,39 @@ describe('gatherContextFacts', () => {
mentionedAgents: [{ id: 'agt_9', title: 'Nine' }],
});
});
+
+ it('invites no delegation inside a sub-agent run, where callAgent is rejected', async () => {
+ const listRecentAgents = vi.fn(async () => recent);
+ const facts = await gatherContextFacts(
+ request({
+ enabledToolIds: ['lobe-agent-management'],
+ isSubAgent: true,
+ mentionedAgents: [{ id: 'agt_9', title: 'Nine' }] as never,
+ }),
+ {
+ listEnabledProviders: async () => [{ id: 'openai', models: [], name: 'OpenAI' }],
+ listRecentAgents,
+ },
+ );
+
+ const ctx = facts.step.agentManagementContext!;
+ expect(listRecentAgents).not.toHaveBeenCalled();
+ expect(ctx.availableAgents).toBeUndefined();
+ expect(ctx.mentionedAgents).toBeUndefined();
+ // Its own id stays, for updateAgent / installPlugin on itself.
+ expect(ctx.currentAgent).toEqual({ id: 'agt_1', title: 'Helper' });
+ // CRUD facts for createAgent / updateAgent still flow.
+ expect(ctx.availableProviders).toEqual([{ id: 'openai', models: [], name: 'OpenAI' }]);
+ });
+
+ it('invites no delegation in an auto-mode sub-agent without the tool', async () => {
+ const listRecentAgents = vi.fn(async () => recent);
+ const facts = await gatherContextFacts(request({ isSubAgent: true }), { listRecentAgents });
+ expect(listRecentAgents).not.toHaveBeenCalled();
+ expect(facts.step.agentManagementContext).toEqual({
+ currentAgent: { id: 'agt_1', title: 'Helper' },
+ });
+ });
});
it('lists LobeHub skill connectors in the official tool catalog with their status', () => {
diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
index 31eada57fe6..d9ad42a2891 100644
--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
@@ -374,6 +374,10 @@ const gatherGroupAgentBuilderContext = async (
* - nothing owner-scoped for a share visitor: the creator's other agents,
* providers and plugins are theirs, and the share gate has already removed
* the tool that could act on them.
+ * - no delegation facts (`availableAgents` / `mentionedAgents`) inside a
+ * sub-agent run: the executor rejects nested `callAgent` there and the
+ * manifest already hides it, so inviting delegation only sends the model
+ * to a tool call that can never succeed.
*/
const gatherAgentManagementContext = async (
request: ContextFactRequest,
@@ -382,26 +386,35 @@ const gatherAgentManagementContext = async (
const isVisitor = !!request.shareVisitor;
const isEnabled = !isVisitor && request.enabledToolIds.includes(AgentManagementIdentifier);
const isAutoSkillMode = !isVisitor && request.agent.chatConfig?.skillActivateMode !== 'manual';
+ const canDelegate = request.isSubAgent !== true;
let context: AgentManagementContext | undefined;
if ((isAutoSkillMode || isEnabled) && providers.listRecentAgents) {
- const { listRecentAgents } = providers;
- const recent =
- (await attempt('recentAgents', () => listRecentAgents(AVAILABLE_AGENTS_LIMIT + 2))) ?? [];
- // The model is the current agent: its identity is already established by
- // the system role, and it must never see its own id (it cannot call itself).
- const others = request.agentId ? recent.filter((a) => a.id !== request.agentId) : recent;
- context = {
- availableAgents: others.slice(0, AVAILABLE_AGENTS_LIMIT).map((a) => ({
- description: a.description ?? undefined,
- id: a.id,
- title: a.title ?? 'Untitled',
- })),
- availableAgentsHasMore: others.length > AVAILABLE_AGENTS_LIMIT,
- ...(request.agentId && {
- currentAgent: { id: request.agentId, title: request.agent.title ?? undefined },
- }),
- };
+ // Self-management (updateAgent / installPlugin on itself) stays available
+ // inside a sub-agent, so its own id is kept; only the delegation list goes.
+ const currentAgent = request.agentId
+ ? { id: request.agentId, title: request.agent.title ?? undefined }
+ : undefined;
+
+ if (canDelegate) {
+ const { listRecentAgents } = providers;
+ const recent =
+ (await attempt('recentAgents', () => listRecentAgents(AVAILABLE_AGENTS_LIMIT + 2))) ?? [];
+ // The model is the current agent: its identity is already established by
+ // the system role, and it must never see its own id (it cannot call itself).
+ const others = request.agentId ? recent.filter((a) => a.id !== request.agentId) : recent;
+ context = {
+ availableAgents: others.slice(0, AVAILABLE_AGENTS_LIMIT).map((a) => ({
+ description: a.description ?? undefined,
+ id: a.id,
+ title: a.title ?? 'Untitled',
+ })),
+ availableAgentsHasMore: others.length > AVAILABLE_AGENTS_LIMIT,
+ ...(currentAgent && { currentAgent }),
+ };
+ } else if (currentAgent) {
+ context = { currentAgent };
+ }
}
if (isEnabled) {
@@ -416,7 +429,7 @@ const gatherAgentManagementContext = async (
};
}
- if (request.mentionedAgents?.length) {
+ if (canDelegate && request.mentionedAgents?.length) {
context = { ...context, mentionedAgents: request.mentionedAgents };
}
diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.ts
index f5c80988fbf..1801bf23ae4 100644
--- a/packages/mecha/src/contextEngineering/facts/types.ts
+++ b/packages/mecha/src/contextEngineering/facts/types.ts
@@ -98,6 +98,11 @@ export interface ContextFactRequest {
executionTarget?: string;
/** Which connector families this deployment offers. */
features: { composio: boolean; lobehubSkill: boolean };
+ /**
+ * The run is a sub-agent (`origin.lineage.isSubAgent`). Nested agent
+ * dispatch is rejected there, so no fact may invite delegation.
+ */
+ isSubAgent?: boolean;
/** Agents the user @-mentioned in the turn. */
mentionedAgents?: RuntimeMentionedAgent[];
/** Conversation as the engine will see it (history hints already applied). */
diff --git a/packages/mecha/src/toolSet/discoveryPool.test.ts b/packages/mecha/src/toolSet/discoveryPool.test.ts
index 7c82ca59500..5c6d7121c64 100644
--- a/packages/mecha/src/toolSet/discoveryPool.test.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.test.ts
@@ -1,3 +1,7 @@
+import {
+ AgentManagementManifest,
+ resolveAgentManagementManifest,
+} from '@lobechat/builtin-tool-agent-management';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
@@ -171,6 +175,43 @@ describe('resolveDiscoveryPool', () => {
expect(pool.sourceMap).toEqual({ gmail: 'composio', linear: 'lobehubSkill' });
expect(pool.manifestMap.gmail).toBeDefined();
});
+
+ describe('context-aware builtin manifests', () => {
+ const agentManagement = {
+ identifier: AgentManagementManifest.identifier,
+ manifest: AgentManagementManifest,
+ resolveManifest: resolveAgentManagementManifest,
+ };
+ const apiNames = (m?: LobeToolManifest) => m?.api.map((api) => api.name);
+
+ it('resolves a discoverable builtin for the run, so a sub-agent cannot activate callAgent', () => {
+ const pool = resolveDiscoveryPool(
+ request({ builtinTools: [agentManagement], manifestContext: { isSubAgent: true } }),
+ );
+
+ const discovered = pool.manifestMap[AgentManagementManifest.identifier];
+ expect(apiNames(discovered)).not.toContain('callAgent');
+ expect(apiNames(discovered)).toContain('getAgentDetail');
+ expect(discovered.systemRole).toContain('Dispatching work to other agents is not available');
+ });
+
+ it('keeps callAgent discoverable in a top-level run', () => {
+ const pool = resolveDiscoveryPool(
+ request({ builtinTools: [agentManagement], manifestContext: { isSubAgent: false } }),
+ );
+ expect(apiNames(pool.manifestMap[AgentManagementManifest.identifier])).toContain('callAgent');
+ });
+
+ it('drops a builtin whose resolver opts out of the run', () => {
+ const pool = resolveDiscoveryPool(
+ request({
+ builtinTools: [{ ...builtin('lobe-opt-out'), resolveManifest: () => null }],
+ manifestContext: {},
+ }),
+ );
+ expect(pool.manifestMap['lobe-opt-out']).toBeUndefined();
+ });
+ });
});
describe('resolveClientExecutors', () => {
diff --git a/packages/mecha/src/toolSet/discoveryPool.ts b/packages/mecha/src/toolSet/discoveryPool.ts
index 140c592392d..6103d518751 100644
--- a/packages/mecha/src/toolSet/discoveryPool.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.ts
@@ -4,6 +4,7 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import type { LobeToolManifest } from '@lobechat/context-engine';
import {
+ type BuiltinToolResolveContext,
type DeviceExecutionTarget,
executionTargetToRuntimeMode,
type LobeBuiltinTool,
@@ -49,7 +50,10 @@ export const resolveInvocationToolIds = (request: InvocationToolIdsRequest): str
export interface DiscoveryPoolRequest {
/** Builtin tools after the device walls, with their `discoverable` flag. */
- builtinTools: readonly Pick<LobeBuiltinTool, 'discoverable' | 'identifier' | 'manifest'>[];
+ builtinTools: readonly Pick<
+ LobeBuiltinTool,
+ 'discoverable' | 'identifier' | 'manifest' | 'resolveManifest'
+ >[];
/** Disabled-filtered Composio manifests. */
composio?: readonly LobeToolManifest[];
/** Gateway device facts; absent without a gateway. */
@@ -70,6 +74,13 @@ export interface DiscoveryPoolRequest {
executionTarget: DeviceExecutionTarget;
/** Disabled-filtered LobeHub skill manifests. */
lobehubSkills?: readonly LobeToolManifest[];
+ /**
+ * Runtime context for context-aware builtin manifests β€” the same one the
+ * tools engine resolved the enabled set with. A discoverable builtin is
+ * activated mid-run from THIS map, so it must be trimmed for the run too
+ * (e.g. agent-management drops `callAgent` inside a sub-agent run).
+ */
+ manifestContext?: BuiltinToolResolveContext;
}
export interface DiscoveryPool {
@@ -144,9 +155,13 @@ export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPo
if (!isManifestIngestAllowed(tool.identifier)) continue;
if (tool.identifier === CloudSandboxManifest.identifier && !cloudSandboxAllowed) continue;
if (stripDeviceTools && isDeviceToolIdentifier(tool.identifier)) continue;
- if (tool.discoverable !== false && !manifestMap[tool.identifier]) {
- manifestMap[tool.identifier] = tool.manifest as LobeToolManifest;
- }
+ if (tool.discoverable === false || manifestMap[tool.identifier]) continue;
+ const manifest =
+ request.manifestContext && tool.resolveManifest
+ ? tool.resolveManifest(request.manifestContext)
+ : tool.manifest;
+ // A resolver returning `null` opts the tool out of this run entirely.
+ if (manifest) manifestMap[tool.identifier] = manifest as LobeToolManifest;
}
// Local-system and Computer Use are only `discoverable` on the desktop, so