π€― 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
π fix: hide agent-management callAgent inside sub-agent runs (#18988)
Arvin Xu48385e26c6fd
diff --git a/packages/builtin-tool-agent-management/package.json b/packages/builtin-tool-agent-management/package.jsonindex 25147070b04..475790c3d90 100644--- a/packages/builtin-tool-agent-management/package.json+++ b/packages/builtin-tool-agent-management/package.json@@ -8,6 +8,9 @@"./executor": "./src/executor.ts"},"main": "./src/index.ts",+ "scripts": {+ "test": "vitest"+ },"dependencies": {"@lobechat/agent-manager-runtime": "workspace:*","@lobechat/const": "workspace:*",diff --git a/packages/builtin-tool-agent-management/src/index.ts b/packages/builtin-tool-agent-management/src/index.tsindex a19e7045476..5050d7b7fba 100644--- a/packages/builtin-tool-agent-management/src/index.ts+++ b/packages/builtin-tool-agent-management/src/index.ts@@ -1,4 +1,5 @@export * from './callAgentManifest';export * from './manifest';+export * from './resolveManifest';export * from './systemRole';export * from './types';diff --git a/packages/builtin-tool-agent-management/src/resolveManifest.test.ts b/packages/builtin-tool-agent-management/src/resolveManifest.test.tsnew file mode 100644index 00000000000..1c8d868d8b5--- /dev/null+++ b/packages/builtin-tool-agent-management/src/resolveManifest.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest';++import { AgentManagementManifest } from './manifest';+import { resolveAgentManagementManifest } from './resolveManifest';+import { systemPrompt, systemPromptWithoutCallAgent } from './systemRole';+import { AgentManagementApiName } from './types';++const apiNames = (manifest: { api: { name: string }[] }) => manifest.api.map((a) => a.name);++describe('resolveAgentManagementManifest', () => {+ it('returns the full static manifest in a normal (non-sub-agent) turn', () => {+ const result = resolveAgentManagementManifest({ scope: 'main' });++ // identical reference β no trimming, no clone+ expect(result).toBe(AgentManagementManifest);+ expect(apiNames(result!)).toContain(AgentManagementApiName.callAgent);+ expect(result!.systemRole).toBe(systemPrompt);+ });++ it('returns the full manifest when no context signals are set', () => {+ expect(resolveAgentManagementManifest({})).toBe(AgentManagementManifest);+ });++ it('hides callAgent in both api and systemRole inside a sub-agent run', () => {+ const result = resolveAgentManagementManifest({ isSubAgent: true, scope: 'main' })!;++ const names = apiNames(result);+ expect(names).not.toContain(AgentManagementApiName.callAgent);+ // the rest of agent-management stays available+ expect(names).toContain(AgentManagementApiName.createAgent);+ expect(names).toContain(AgentManagementApiName.searchAgent);+ expect(names).toContain(AgentManagementApiName.getAgentDetail);+ // exactly one API removed+ expect(names).toHaveLength(AgentManagementManifest.api.length - 1);++ // systemRole is rewritten so the prompt no longer instructs the hidden tool+ expect(result.systemRole).toBe(systemPromptWithoutCallAgent);+ expect(result.systemRole).toContain('subagent_context');++ // non-api fields preserved+ expect(result.identifier).toBe(AgentManagementManifest.identifier);+ });+});++describe('systemPromptWithoutCallAgent', () => {+ it('never instructs the model to use callAgent', () => {+ // The only allowed mention is the sub-agent note explaining that the tool+ // does not exist in this context.+ const withoutNote = systemPromptWithoutCallAgent.replace(+ /<subagent_context>[\S\s]*?<\/subagent_context>/,+ '',+ );+ // Not just the API name β natural-language dispatch instructions+ // ("call the agent", "test with sample tasks") must go too, since testing+ // or calling an agent is exactly what a sub-agent cannot do.+ for (const phrase of [+ 'callAgent',+ 'Call agent',+ 'Call the agent',+ 'call it',+ 'Calling Agents',+ 'When calling agents',+ 'Before calling an agent',+ 'Test the agent',+ 'Test with sample',+ 'Test and Iterate',+ 'execution_guide',+ ]) {+ expect(withoutNote).not.toContain(phrase);+ }+ });++ it('keeps the non-dispatch guidance intact', () => {+ for (const section of [+ 'core_capabilities',+ 'context_injection',+ 'self_management',+ 'agent_creation_guide',+ 'search_guide',+ 'workflow_patterns',+ 'best_practices',+ ]) {+ expect(systemPromptWithoutCallAgent).toContain(`<${section}>`);+ }+ });+});diff --git a/packages/builtin-tool-agent-management/src/resolveManifest.ts b/packages/builtin-tool-agent-management/src/resolveManifest.tsnew file mode 100644index 00000000000..68295c197ac--- /dev/null+++ b/packages/builtin-tool-agent-management/src/resolveManifest.ts@@ -0,0 +1,28 @@+import type { BuiltinManifestResolver } from '@lobechat/types';++import { AgentManagementManifest } from './manifest';+import { systemPromptWithoutCallAgent } from './systemRole';+import { AgentManagementApiName } from './types';++/**+ * Context-aware manifest for the agent-management tool.+ *+ * `callAgent` must be hidden inside a sub-agent run: the server executor+ * rejects nested dispatch outright (NESTED_AGENT_CALL_NOT_ALLOWED), so+ * advertising the API there only makes the model burn tool calls on a path+ * that can never succeed. Agent CRUD / search / plugin APIs stay available β+ * this returns a trimmed manifest (not `null`). It rewrites BOTH halves of the+ * manifest in step: the `api` list drops `callAgent`, and `systemRole`+ * switches to the variant without the dispatch guidance plus an explicit note+ * that delegation is unavailable β otherwise the prompt would keep instructing+ * the model to dispatch a tool that is no longer in its tool list.+ */+export const resolveAgentManagementManifest: BuiltinManifestResolver = (context) => {+ if (context.isSubAgent !== true) return AgentManagementManifest;++ return {+ ...AgentManagementManifest,+ api: AgentManagementManifest.api.filter((api) => api.name !== AgentManagementApiName.callAgent),+ systemRole: systemPromptWithoutCallAgent,+ };+};diff --git a/packages/builtin-tool-agent-management/src/systemRole.ts b/packages/builtin-tool-agent-management/src/systemRole.tsindex 1bd1524a32c..8100fff4321 100644--- a/packages/builtin-tool-agent-management/src/systemRole.ts+++ b/packages/builtin-tool-agent-management/src/systemRole.ts@@ -3,8 +3,187 @@** This provides guidance on how to effectively use the agent management tools* to create, configure, search, and orchestrate AI agents.+ *+ * The prompt is assembled by `buildSystemPrompt` so the callAgent guidance can+ * be dropped wholesale in contexts where dispatch is not allowed (sub-agent+ * runs reject callAgent with NESTED_AGENT_CALL_NOT_ALLOWED) β otherwise the+ * prompt would keep instructing the model to use a tool that is no longer in+ * its tool list.*/-export const systemPrompt = `You have Agent Management tools to create, configure, and orchestrate AI agents. Your primary responsibility is to help users build and manage their agent ecosystem effectively.++interface WorkflowPattern {+ /** Pattern only makes sense when the model can dispatch/run agents. */+ requiresCallAgent?: boolean;+ steps: string[];+ /**+ * Replacement steps for the no-callAgent variant. Needed when only part of+ * the pattern depends on dispatching (e.g. a final "call/test the agent"+ * step) β the rest of the workflow is still valid for a sub-agent.+ */+ stepsWithoutCallAgent?: string[];+ title: string;+}++const workflowPatterns: WorkflowPattern[] = [+ {+ steps: [+ 'Review available models and plugins from injected context',+ 'Create agent with complete configuration (title, systemRole, model, provider, plugins)',+ 'Test the agent with sample tasks',+ ],+ stepsWithoutCallAgent: [+ 'Review available models and plugins from injected context',+ 'Create agent with complete configuration (title, systemRole, model, provider, plugins)',+ ],+ title: 'Create with Full Configuration',+ },+ {+ // Create β test β refine is a dispatch loop end to end; drop it entirely.+ requiresCallAgent: true,+ steps: [+ 'Create agent with basic configuration (title, systemRole, model, provider)',+ 'Test with sample tasks',+ 'Update configuration based on results (add plugins, adjust settings)',+ ],+ title: 'Create and Refine',+ },+ {+ requiresCallAgent: true,+ steps: [+ 'Search for existing agents (workspace or marketplace)',+ 'Select the best match for the task',+ 'Call agent with specific instruction',+ ],+ title: 'Find and Use',+ },+ {+ requiresCallAgent: true,+ steps: [+ 'Create a specialized agent for a specific task',+ 'Immediately call the agent to execute the task',+ 'Refine agent configuration based on results',+ ],+ title: 'Create, Call, and Iterate',+ },+ {+ steps: [+ "Use getAgentDetail to inspect an agent's current configuration",+ 'Decide whether to call it, update it, or duplicate it based on the details',+ ],+ stepsWithoutCallAgent: [+ "Use getAgentDetail to inspect an agent's current configuration",+ 'Decide whether to update it or duplicate it based on the details',+ ],+ title: 'Inspect and Decide',+ },+ {+ steps: [+ "Find an existing agent that's close to what's needed",+ 'Use duplicateAgent to create a copy',+ 'Use updateAgent to customize the copy for the new use case',+ ],+ title: 'Duplicate and Customize',+ },+ {+ steps: [+ 'Create or select an agent',+ 'Use installPlugin to add necessary tools/integrations',+ 'Call the agent with instructions that leverage the installed plugins',+ ],+ stepsWithoutCallAgent: [+ 'Create or select an agent',+ 'Use installPlugin to add necessary tools/integrations',+ ],+ title: 'Equip with Plugins',+ },+];++const buildWorkflowPatterns = (includeCallAgent: boolean) =>+ workflowPatterns+ .filter((pattern) => includeCallAgent || !pattern.requiresCallAgent)+ .map((pattern, index) => {+ const steps =+ includeCallAgent || !pattern.stepsWithoutCallAgent+ ? pattern.steps+ : pattern.stepsWithoutCallAgent;+ return `### Pattern ${index + 1}: ${pattern.title}\n${steps+ .map((step, stepIndex) => `${stepIndex + 1}. ${step}`)+ .join('\n')}`;+ })+ .join('\n\n');++const bestPractices: { requiresCallAgent?: boolean; text: string }[] = [+ {+ text: '**Use Context Information**: Always refer to the injected context for accurate model IDs, provider IDs, and plugin IDs',+ },+ {+ text: '**Specify Model AND Provider**: When setting a model, always specify both `model` and `provider` together',+ },+ {+ text: '**Start with Essential Config**: Begin with title, systemRole, model, and provider. Add plugins and other settings as needed',+ },+ {+ requiresCallAgent: true,+ text: '**Clear Instructions**: When calling agents, be specific about expected outcomes and deliverables',+ },+ {+ text: '**Right Tool for the Job**: Match agent capabilities (model, plugins) to task requirements',+ },+ {+ text: '**Meaningful Metadata**: Use descriptive titles, tags, and descriptions for easy discovery',+ },+ {+ requiresCallAgent: true,+ text: '**Test and Iterate**: Test agents with sample tasks and refine configuration based on actual usage',+ },+ {+ text: "**Plugin Selection**: Only enable plugins that are relevant to the agent's purpose to avoid unnecessary overhead",+ },+];++const buildBestPractices = (includeCallAgent: boolean) =>+ bestPractices+ .filter((practice) => includeCallAgent || !practice.requiresCallAgent)+ .map((practice, index) => `${index + 1}. ${practice.text}`)+ .join('\n');++const executionGuideSection = `++<execution_guide>+## Calling Agents++### Synchronous Call (default)+For quick responses in the conversation context:+\`\`\`+callAgent(agentId, instruction)+\`\`\`+The agent will respond directly in the current conversation.++### Asynchronous Task+For longer operations that benefit from focused execution:+\`\`\`+callAgent(agentId, instruction, runAsTask: true, taskTitle: "Brief description")+\`\`\`+The agent will work in the background and return results upon completion.++**When to use runAsTask:**+- Complex multi-step operations+- Tasks requiring extended processing time+- Work that shouldn't block the conversation flow+- Operations that benefit from isolated execution context+</execution_guide>`;++const subAgentContextSection = `++<subagent_context>+## Sub-Agent Context++You are currently running as a sub-agent. Dispatching work to other agents is not available in this context β there is no callAgent tool, and requesting it would be rejected. Complete the task yourself with the tools you have instead of attempting to delegate.+</subagent_context>`;++export const buildSystemPrompt = (+ { includeCallAgent }: { includeCallAgent: boolean } = { includeCallAgent: true },+) => `You have Agent Management tools to create, configure, and orchestrate AI agents. Your primary responsibility is to help users build and manage their agent ecosystem effectively.<core_capabilities>## Tool Overview@@ -23,10 +202,14 @@ export const systemPrompt = `You have Agent Management tools to create, configur- **updatePrompt**: Update an agent's system prompt directly (preferred over updateAgent when only changing the prompt)**Plugin Management:**-- **installPlugin**: Install a plugin/tool for an agent (builtin, Composio, LobehubSkill, or MCP marketplace)+- **installPlugin**: Install a plugin/tool for an agent (builtin, Composio, LobehubSkill, or MCP marketplace)${+ includeCallAgent+ ? `**Execution:**-- **callAgent**: Invoke an agent to handle a task (synchronously or as async background task)+- **callAgent**: Invoke an agent to handle a task (synchronously or as async background task)`+ : ''+}</core_capabilities><context_injection>@@ -35,7 +218,11 @@ export const systemPrompt = `You have Agent Management tools to create, configurWhen this tool is enabled, you will receive contextual information about:- **Current Agent**: Your own agent ID (in the \`<current_agent>\` tag). Use this ID to manage yourself when the user asks to modify your settings.- **Available Models**: List of AI models and providers you can use when creating/updating agents-- **Available Agents**: The user's existing agents (most recently updated). You can call them directly via callAgent without first running searchAgent when one of them clearly matches the user's request.+- **Available Agents**: The user's existing agents (most recently updated).${+ includeCallAgent+ ? " You can call them directly via callAgent without first running searchAgent when one of them clearly matches the user's request."+ : ''+}- **Available Plugins**: List of plugins (builtin tools, Composio integrations, LobehubSkill providers) you can enable for agentsThis information is automatically injected into the conversation context. Use the exact IDs from the context when specifying model/provider/plugins/agentId parameters. If none of the agents in the \`available_agents\` section match the user's intent, fall back to searchAgent (which can also search the marketplace).@@ -55,9 +242,13 @@ You can manage yourself using the same Agent Management tools. Your own agent ID**Tool selection for prompt changes**: When only the system prompt needs updating, always use \`updatePrompt\` instead of \`updateAgent\`. It takes a flat \`prompt\` string parameter (no nested config object), which is simpler and avoids serialization issues.-**Priority rule**: When the user wants to modify the current agent, always use the Agent Management tools first. Only fall back to other tools (e.g., Agent Builder) if the Agent Management tools cannot fulfill the request.+**Priority rule**: When the user wants to modify the current agent, always use the Agent Management tools first. Only fall back to other tools (e.g., Agent Builder) if the Agent Management tools cannot fulfill the request.${+ includeCallAgent+ ? `-**IMPORTANT**: Never use callAgent with your own agent ID β this would create an infinite loop.+**IMPORTANT**: Never use callAgent with your own agent ID β this would create an infinite loop.`+ : ''+}</self_management><agent_creation_guide>@@ -146,8 +337,7 @@ Refer to the injected context for available plugin IDs and descriptions.Use getAgentDetail to inspect an agent's full configuration before making decisions:**When to use:**-- Before calling an agent, to understand its capabilities-- Before updating an agent, to see current settings+${includeCallAgent ? '- Before calling an agent, to understand its capabilities\n' : ''}- Before updating an agent, to see current settings- To check what model, plugins, or system prompt an agent uses\`\`\`@@ -211,68 +401,12 @@ Use searchAgent to discover agents:- Use specific keywords related to the task- Filter by category when browsing marketplace- Check agent descriptions for capability details-</search_guide>--<execution_guide>-## Calling Agents--### Synchronous Call (default)-For quick responses in the conversation context:-\`\`\`-callAgent(agentId, instruction)-\`\`\`-The agent will respond directly in the current conversation.--### Asynchronous Task-For longer operations that benefit from focused execution:-\`\`\`-callAgent(agentId, instruction, runAsTask: true, taskTitle: "Brief description")-\`\`\`-The agent will work in the background and return results upon completion.--**When to use runAsTask:**-- Complex multi-step operations-- Tasks requiring extended processing time-- Work that shouldn't block the conversation flow-- Operations that benefit from isolated execution context-</execution_guide>+</search_guide>${includeCallAgent ? executionGuideSection : subAgentContextSection}<workflow_patterns>## Common Workflows-### Pattern 1: Create with Full Configuration-1. Review available models and plugins from injected context-2. Create agent with complete configuration (title, systemRole, model, provider, plugins)-3. Test the agent with sample tasks--### Pattern 2: Create and Refine-1. Create agent with basic configuration (title, systemRole, model, provider)-2. Test with sample tasks-3. Update configuration based on results (add plugins, adjust settings)--### Pattern 3: Find and Use-1. Search for existing agents (workspace or marketplace)-2. Select the best match for the task-3. Call agent with specific instruction--### Pattern 4: Create, Call, and Iterate-1. Create a specialized agent for a specific task-2. Immediately call the agent to execute the task-3. Refine agent configuration based on results--### Pattern 5: Inspect and Decide-1. Use getAgentDetail to inspect an agent's current configuration-2. Decide whether to call it, update it, or duplicate it based on the details--### Pattern 6: Duplicate and Customize-1. Find an existing agent that's close to what's needed-2. Use duplicateAgent to create a copy-3. Use updateAgent to customize the copy for the new use case--### Pattern 7: Equip with Plugins-1. Create or select an agent-2. Use installPlugin to add necessary tools/integrations-3. Call the agent with instructions that leverage the installed plugins+${buildWorkflowPatterns(includeCallAgent)}</workflow_patterns><agent_card_rendering>@@ -310,12 +444,15 @@ Do NOT render a card when calling \`getAgentDetail\`, \`updateAgent\`, \`updateP<best_practices>## Best Practices-1. **Use Context Information**: Always refer to the injected context for accurate model IDs, provider IDs, and plugin IDs-2. **Specify Model AND Provider**: When setting a model, always specify both \`model\` and \`provider\` together-3. **Start with Essential Config**: Begin with title, systemRole, model, and provider. Add plugins and other settings as needed-4. **Clear Instructions**: When calling agents, be specific about expected outcomes and deliverables-5. **Right Tool for the Job**: Match agent capabilities (model, plugins) to task requirements-6. **Meaningful Metadata**: Use descriptive titles, tags, and descriptions for easy discovery-7. **Test and Iterate**: Test agents with sample tasks and refine configuration based on actual usage-8. **Plugin Selection**: Only enable plugins that are relevant to the agent's purpose to avoid unnecessary overhead+${buildBestPractices(includeCallAgent)}</best_practices>`;++export const systemPrompt = buildSystemPrompt({ includeCallAgent: true });++/**+ * Variant for sub-agent runs, where `callAgent` is filtered out of the manifest+ * (dispatching from within a sub-agent is rejected at execution time). Every+ * callAgent mention is dropped and an explicit note tells the model dispatch is+ * unavailable, so it executes the task itself instead of burning tool calls.+ */+export const systemPromptWithoutCallAgent = buildSystemPrompt({ includeCallAgent: false });diff --git a/packages/builtin-tool-agent-management/vitest.config.mts b/packages/builtin-tool-agent-management/vitest.config.mtsnew file mode 100644index 00000000000..52f86e133c7--- /dev/null+++ b/packages/builtin-tool-agent-management/vitest.config.mts@@ -0,0 +1,11 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ coverage: {+ provider: 'v8',+ reporter: ['text', 'json', 'lcov', 'text-summary'],+ },+ environment: 'node',+ },+});diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex a408bbd0ecc..8057cb05841 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -2,7 +2,10 @@ import { AcceptanceEvidenceManifest } from '@lobechat/builtin-tool-acceptance-evimport { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';-import { AgentManagementManifest } from '@lobechat/builtin-tool-agent-management';+import {+ AgentManagementManifest,+ resolveAgentManagementManifest,+} from '@lobechat/builtin-tool-agent-management';import {agentSignalFeedbackIntentManifest,agentSignalReflectionManifest,@@ -335,6 +338,8 @@ const builtinToolRegistry: LobeBuiltinTool[] = [hidden: true,identifier: AgentManagementManifest.identifier,manifest: AgentManagementManifest,+ // Context-aware: hides the `callAgent` API inside sub-agent runs.+ resolveManifest: resolveAgentManagementManifest,type: 'builtin',},{