# 多智能体协作 Claude Code 的多智能体系统允许创建和协调多个 AI 代理协同工作。本文档详细介绍 AgentTool 和相关协作机制。 ## 1. AgentTool 概述 ### 1.1 核心文件 **位置:** `/src/tools/AgentTool/` **主要文件:** - `runAgent.ts` - Agent 运行核心逻辑 - `builtInAgents.ts` - 内置 Agent 定义 - `loadAgentsDir.ts` - Agent 目录加载 - `agentMemory.ts` - Agent 内存管理 - `built-in/` - 内置 Agent 实现 ### 1.2 Agent 定义结构 ```typescript export type AgentDefinition = { agentType: string // Agent 类型标识 whenToUse?: string // 使用建议 disallowedTools?: string[] // 禁用工具列表 tools?: string[] | '*' // 允许的工具 source?: string // 来源 baseDir?: string // 基础目录 model?: string // 模型设置 permissionMode?: PermissionMode // 权限模式 maxTurns?: number // 最大轮次 getSystemPrompt?: () => string // 系统提示 hooks?: HooksSettings // 钩子设置 skills?: string[] // 预加载技能 mcpServers?: MCPServerSpec[] // MCP 服务器 omitClaudeMd?: boolean // 是否省略 CLAUDE.md effort?: EffortValue // 努力值 callback?: () => void // 完成回调 } ``` ## 2. 子智能体生成 ### 2.1 runAgent 函数 **位置:** `/src/tools/AgentTool/runAgent.ts` `runAgent` 是创建和运行子智能体的核心函数: ```typescript export async function* runAgent({ agentDefinition, // Agent 定义 promptMessages, // 提示消息 toolUseContext, // 工具使用上下文 canUseTool, // 工具使用权限检查 isAsync, // 是否异步执行 querySource, // 查询来源 model, // 模型覆盖 maxTurns, // 最大轮次 allowedTools, // 允许的工具列表 // ... }): AsyncGenerator ``` ### 2.2 消息过滤 ```typescript // 过滤不完整的工具调用 export function filterIncompleteToolCalls(messages: Message[]): Message[] { // 移除有工具调用但没有结果的助手消息 } ``` ### 2.3 上下文隔离 ```typescript // 为子智能体创建隔离的上下文 const agentToolUseContext = createSubagentContext(toolUseContext, { options: agentOptions, agentId, agentType: agentDefinition.agentType, messages: initialMessages, readFileState: agentReadFileState, abortController: agentAbortController, getAppState: agentGetAppState, shareSetAppState: !isAsync, // 同步 Agent 共享状态 }) ``` ## 3. 智能体生命周期管理 ### 3.1 生命周期阶段 1. **初始化阶段** - 创建 Agent ID - 设置上下文 - 初始化 MCP 服务器 - 注册 Hooks 2. **执行阶段** - 运行查询循环 - 处理工具调用 - 管理会话 3. **清理阶段** - 清理 MCP 服务器 - 清除会话 Hooks - 释放内存 - 杀死后台任务 ### 3.2 生命周期钩子 ```typescript // SubagentStart 钩子 for await (const hookResult of executeSubagentStartHooks( agentId, agentDefinition.agentType, agentAbortController.signal, )) { // 收集额外上下文 } // SubagentStop 钩子 if (agentDefinition.hooks) { clearSessionHooks(rootSetAppState, agentId) } ``` ## 4. 内置智能体 (built-in/) ### 4.1 generalPurposeAgent **位置:** `/src/tools/AgentTool/built-in/generalPurposeAgent.ts` 通用目的 Agent,适用于复杂研究和多步骤任务执行: ```typescript export const GENERAL_PURPOSE_AGENT: BuiltInAgentDefinition = { agentType: 'general-purpose', whenToUse: 'General-purpose agent for researching complex questions...', tools: ['*'], // 允许所有工具 source: 'built-in', getSystemPrompt: getGeneralPurposeSystemPrompt, } ``` ### 4.2 planAgent **位置:** `/src/tools/AgentTool/built-in/planAgent.ts` 软件架构师 Agent,用于设计实现计划: **关键特性:** - **只读模式**:禁止任何文件修改操作 - 严格禁用工具:`Edit`, `Write`, `NotebookEdit`, `Agent` - 允许工具:`Read`, `Glob`, `Grep`, `Bash`(仅限只读操作) **系统提示片段:** ``` === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS === This is a READ-ONLY planning task. You are STRICTLY PROHIBITED from: - Creating new files (no Write, touch, or file creation of any kind) - Modifying existing files (no Edit operations) - Deleting files (no rm or deletion) ... ``` ### 4.3 verificationAgent 验证 Agent,用于验证任务完成情况: ```typescript // 在 TaskUpdateTool 中引用 const VERIFICATION_AGENT_TYPE = 'verification' // 当满足条件时提示验证 if (allTasks.length >= 3 && !allTasks.some(t => /verif/i.test(t.subject))) { verificationNudgeNeeded = true } ``` ### 4.4 exploreAgent 探索 Agent,用于代码库探索和搜索: **特性:** - 只读操作 - 使用 `find`/`grep` 或 `Glob`/`Grep` 进行搜索 - 不加载 CLAUDE.md(节省 token) ### 4.5 statuslineSetup 状态栏设置 Agent,用于配置状态行显示。 ### 4.6 claudeCodeGuideAgent Claude Code 指南 Agent,帮助用户学习使用 Claude Code。 ## 5. Agent 内存管理 ### 5.1 Agent 内存结构 **位置:** `/src/tools/AgentTool/agentMemory.ts` ```typescript export type AgentMemory = { sessionId: string agentId: string messages: Message[] toolUseResults: Map fileState: FileStateCache } ``` ### 5.2 文件状态缓存 ```typescript // 克隆文件状态缓存 const agentReadFileState = forkContextMessages !== undefined ? cloneFileStateCache(toolUseContext.readFileState) : createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE) // 清理时释放 agentToolUseContext.readFileState.clear() ``` ### 5.3 转录记录 ```typescript // 记录初始消息 await recordSidechainTranscript(initialMessages, agentId) // 记录新消息 await recordSidechainTranscript([message], agentId, lastRecordedUuid) ``` ## 6. 团队协调器 (coordinator/) ### 6.1 协调器模式 **位置:** `/src/coordinator/coordinatorMode.ts` 协调器模式允许多个 Agent 在团队中协作。 ### 6.2 协调器 Agent ```typescript // 获取协调器 Agent function getCoordinatorAgents(): AgentDefinition[] ``` ## 7. 团队管理工具 ### 7.1 TeamCreateTool **位置:** `/src/tools/TeamCreateTool/TeamCreateTool.ts` 创建团队,管理团队配置。 ### 7.2 TeamDeleteTool **位置:** `/src/tools/TeamDeleteTool/TeamDeleteTool.ts` 删除团队,清理团队资源。 ### 7.3 团队文件结构 **位置:** `/src/utils/swarm/teamHelpers.ts` ```typescript export type TeamFile = { name: string description?: string createdAt: number leadAgentId: string leadSessionId?: string hiddenPaneIds?: string[] teamAllowedPaths?: TeamAllowedPath[] members: Array<{ agentId: string name: string agentType?: string model?: string prompt?: string color?: string planModeRequired?: boolean joinedAt: number tmuxPaneId: string cwd: string worktreePath?: string sessionId?: string subscriptions: string[] backendType?: BackendType isActive?: boolean mode?: PermissionMode }> } ``` ## 8. Agent 与技能的集成 ### 8.1 技能预加载 Agent 可以预加载技能: ```typescript const skillsToPreload = agentDefinition.skills ?? [] if (skillsToPreload.length > 0) { const allSkills = await getSkillToolCommands(getProjectRoot()) // 加载并注入技能内容 } ``` ### 8.2 技能名称解析 ```typescript function resolveSkillName( skillName: string, allSkills: Command[], agentDefinition: AgentDefinition ): string | null { // 1. 精确匹配 if (hasCommand(skillName, allSkills)) return skillName // 2. 前缀匹配 (e.g., "my-skill" → "my-plugin:my-skill") const qualifiedName = `${pluginPrefix}:${skillName}` if (hasCommand(qualifiedName, allSkills)) return qualifiedName // 3. 后缀匹配 (e.g., ":my-skill") // ... } ``` ## 9. MCP 服务器集成 ### 9.1 Agent 专用 MCP 服务器 Agent 可以定义自己的 MCP 服务器: ```typescript async function initializeAgentMcpServers( agentDefinition: AgentDefinition, parentClients: MCPServerConnection[] ): Promise<{ clients: MCPServerConnection[] tools: Tools cleanup: () => Promise }> ``` ### 9.2 服务器合并 ```typescript // 合并父级和 Agent 专用的 MCP 客户端 const allTools = uniqBy([...resolvedTools, ...agentMcpTools], 'name') ``` ## 10. 权限与隔离 ### 10.1 权限模式 ```typescript const agentPermissionMode = agentDefinition.permissionMode if (agentPermissionMode && state.toolPermissionContext.mode !== 'bypassPermissions' && state.toolPermissionContext.mode !== 'acceptEdits') { toolPermissionContext = { ...toolPermissionContext, mode: agentPermissionMode } } ``` ### 10.2 工具过滤 ```typescript const resolvedTools = resolveAgentTools( agentDefinition, availableTools, isAsync ).resolvedTools ``` ## 11. 性能优化 ### 11.1 CLAUDE.md 省略 ```typescript const shouldOmitClaudeMd = agentDefinition.omitClaudeMd && !override?.userContext && getFeatureValue_CACHED_MAY_BE_STALE('tengu_slim_subagent_claudemd', true) ``` ### 11.2 Git 状态省略 ```typescript const resolvedSystemContext = agentDefinition.agentType === 'Explore' || agentDefinition.agentType === 'Plan' ? systemContextNoGit // 省略 gitStatus : baseSystemContext ``` ### 11.3 推理配置 ```typescript thinkingConfig: useExactTools ? toolUseContext.options.thinkingConfig // 继承父级 : { type: 'disabled' as const } // 禁用 ``` ## 12. Telemetry 与追踪 ### 12.1 Perfetto 追踪 ```typescript if (isPerfettoTracingEnabled()) { registerPerfettoAgent(agentId, agentDefinition.agentType, parentId) } // 清理时注销 unregisterPerfettoAgent(agentId) ``` ### 12.2 转录存储 ```typescript // 边链转录 await recordSidechainTranscript(initialMessages, agentId) // Agent 元数据 await writeAgentMetadata(agentId, { agentType: agentDefinition.agentType, worktreePath, description }) ```