custom-agents.mdx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. ---
  2. title: "自定义 Agent - 从 Markdown 到运行时的完整链路"
  3. description: "揭秘 Claude Code 自定义 Agent 完整链路:Agent 定义的 Markdown 数据模型、三种加载来源、工具过滤策略和与 AgentTool 的联动机制。"
  4. keywords: ["自定义 Agent", "Agent 定义", "Markdown Agent", "Agent 配置", "角色定制"]
  5. ---
  6. {/* 本章目标:揭示 Agent 定义的完整数据模型、加载发现机制、工具过滤和与 AgentTool 的联动 */}
  7. ## Agent 定义的三种来源
  8. Claude Code 的 Agent 不仅仅来自用户自定义——系统有三类来源,按优先级合并:
  9. | 来源 | 位置 | 优先级 |
  10. |------|------|--------|
  11. | **Built-in** | `src/tools/AgentTool/built-in/` 硬编码 | 最低(可被覆盖) |
  12. | **Plugin** | 通过插件系统注册 | 中 |
  13. | **User/Project/Policy** | `.claude/agents/*.md` 或 settings.json | 最高 |
  14. 合并逻辑在 `getActiveAgentsFromList()` 中:按 `agentType` 去重,后者覆盖前者。这意味着你可以在 `.claude/agents/` 中放一个 `Explore.md` 来完全替换内置的 Explore Agent。
  15. ## Markdown Agent 文件的完整格式
  16. ```markdown
  17. ---
  18. # === 必需字段 ===
  19. name: "reviewer" # Agent 标识(agentType)
  20. description: "Code review specialist, read-only analysis"
  21. # === 工具控制 ===
  22. tools: "Read,Glob,Grep,Bash" # 允许的工具列表(逗号分隔)
  23. disallowedTools: "Write,Edit" # 显式禁止的工具
  24. # === 模型配置 ===
  25. model: "haiku" # 指定模型(或 "inherit" 继承主线程)
  26. effort: "high" # 推理努力程度:low/medium/high 或整数
  27. # === 行为控制 ===
  28. maxTurns: 10 # 最大 agentic 轮次
  29. permissionMode: "plan" # 权限模式:plan/bypassPermissions 等
  30. background: true # 始终作为后台任务运行
  31. initialPrompt: "/search TODO" # 首轮用户消息前缀(支持斜杠命令)
  32. # === 隔离与持久化 ===
  33. isolation: "worktree" # 在独立 git worktree 中运行
  34. memory: "project" # 持久记忆范围:user/project/local
  35. # === MCP 服务器 ===
  36. mcpServers:
  37. - "slack" # 引用已配置的 MCP 服务器
  38. - database: # 内联定义
  39. command: "npx"
  40. args: ["mcp-db"]
  41. # === Hooks ===
  42. hooks:
  43. PreToolUse:
  44. - command: "audit-log.sh"
  45. timeout: 5000
  46. # === Skills ===
  47. skills: "code-review,security-review" # 预加载的 skills(逗号分隔)
  48. # === 显示 ===
  49. color: "blue" # 终端中的 Agent 颜色标识
  50. ---
  51. 你是代码审查专家。你的职责是...
  52. (正文内容 = system prompt)
  53. ```
  54. ### 字段解析细节
  55. - **`tools`**:通过 `parseAgentToolsFromFrontmatter()` 解析,支持逗号分隔字符串或数组
  56. - **`model: "inherit"`**:使用主线程的模型(区分大小写,只有小写 "inherit" 有效)
  57. - **`memory`**:启用后自动注入 `Write`/`Edit`/`Read` 工具(即使 `tools` 未包含),并在 system prompt 末尾追加 memory 指令
  58. - **`isolation: "remote"`**:仅在 Anthropic 内部可用(`USER_TYPE === 'ant'`),外部构建只支持 `worktree`
  59. - **`background`**:`true` 使 Agent 始终在后台运行,主线程不等待结果
  60. ## 加载与发现机制
  61. `getAgentDefinitionsWithOverrides()`(被 `memoize` 缓存)执行完整的发现流程:
  62. ```
  63. 1. 加载 Markdown 文件
  64. ├── loadMarkdownFilesForSubdir('agents', cwd)
  65. │ ├── ~/.claude/agents/*.md (用户级,source = 'userSettings')
  66. │ ├── .claude/agents/*.md (项目级,source = 'projectSettings')
  67. │ └── managed/policy sources (策略级,source = 'policySettings')
  68. └── 每个 .md 文件:
  69. ├── 解析 YAML frontmatter
  70. ├── 正文作为 system prompt
  71. ├── 校验必需字段(name, description)
  72. ├── 静默跳过无 frontmatter 的 .md 文件(可能是参考文档)
  73. └── 解析失败 → 记录到 failedFiles,不阻塞其他 Agent
  74. 2. 并行加载 Plugin Agents
  75. └── loadPluginAgents() → memoized
  76. 3. 初始化 Memory Snapshots(如果 AGENT_MEMORY_SNAPSHOT 启用)
  77. └── initializeAgentMemorySnapshots()
  78. 4. 合并 Built-in + Plugin + Custom
  79. └── getActiveAgentsFromList() → 按 agentType 去重,后者覆盖前者
  80. 5. 分配颜色
  81. └── setAgentColor(agentType, color) → 终端 UI 中区分不同 Agent
  82. ```
  83. ## 工具过滤的实现
  84. 当 Agent 被派生时,`AgentTool` 根据定义中的 `tools` / `disallowedTools` 过滤可用工具列表:
  85. ```
  86. 全部工具
  87. ↓ disallowedTools 移除
  88. ↓ tools 白名单过滤(如果指定)
  89. 可用工具
  90. ```
  91. - **`tools` 未指定**:Agent 可以使用所有工具(默认全能)
  92. - **`tools` 指定**:只能使用列出的工具
  93. - **`disallowedTools`**:即使 `tools` 未指定,这些工具也被禁止
  94. - **自动注入**:`memory` 启用时自动添加 `Write`/`Edit`/`Read`
  95. 以内置 Explore Agent 为例:
  96. ```typescript
  97. // src/tools/AgentTool/built-in/exploreAgent.ts
  98. disallowedTools: [
  99. 'Agent', // 不能嵌套调用 Agent
  100. 'ExitPlanMode', // 不需要 plan mode
  101. 'FileEdit', // 只读
  102. 'FileWrite', // 只读
  103. 'NotebookEdit', // 只读
  104. ]
  105. ```
  106. ## System Prompt 的注入方式
  107. Agent 的 system prompt 通过 `getSystemPrompt()` 闭包延迟生成:
  108. ```typescript
  109. // Markdown Agent
  110. getSystemPrompt: () => {
  111. if (isAutoMemoryEnabled() && memory) {
  112. return systemPrompt + '\n\n' + loadAgentMemoryPrompt(agentType, memory)
  113. }
  114. return systemPrompt
  115. }
  116. ```
  117. 这意味着:
  118. 1. **Markdown 正文 = 完整的 system prompt**——不是追加,而是替换默认 prompt
  119. 2. **Memory 指令**在 memory 启用时自动追加到末尾
  120. 3. **闭包延迟计算**——memory 状态可能在文件加载后才变化
  121. 对于 Built-in Agent,`getSystemPrompt` 接受 `toolUseContext` 参数,可以根据运行时状态(如是否使用嵌入式搜索工具)动态调整 prompt 内容。
  122. ## 与 AgentTool 的联动
  123. 当主 Agent 需要派生子 Agent 时:
  124. ```
  125. AgentTool.call({ subagent_type: "reviewer", ... })
  126. 1. 从 agentDefinitions.activeAgents 查找 agentType === "reviewer"
  127. 2. 检查 requiredMcpServers(如果 Agent 要求特定 MCP 服务器)
  128. 3. 过滤工具列表(tools / disallowedTools)
  129. 4. 解析模型:
  130. - "inherit" → 使用主线程模型
  131. - 具体模型名 → 直接使用
  132. - 未指定 → 主线程模型
  133. 5. 解析权限模式(permissionMode)
  134. 6. 构建隔离环境(如果 isolation === "worktree")
  135. 7. 注入 system prompt(getSystemPrompt())
  136. 8. 注入 initialPrompt(如果定义了)
  137. 9. 启动子 Agent 循环(forkSubagent / runAgent)
  138. ```
  139. ## 内置 Agent 参考
  140. | Agent | agentType | 角色 | 工具限制 | 模型 |
  141. |-------|-----------|------|---------|------|
  142. | **General Purpose** | `general-purpose` | 默认子 Agent | 全部工具 | 主线程模型 |
  143. | **Explore** | `Explore` | 代码搜索专家 | 只读(无 Write/Edit) | haiku(外部) |
  144. | **Plan** | `Plan` | 规划专家 | 只读 + ExitPlanMode | inherit |
  145. | **Verification** | `verification` | 结果验证 | 由 feature flag 控制 | — |
  146. | **Code Guide** | `claude-code-guide` | Claude Code 使用指南 | 只读 | — |
  147. | **Statusline Setup** | `statusline-setup` | 终端状态栏配置 | 有限 | — |
  148. SDK 入口(`sdk-ts`/`sdk-py`/`sdk-cli`)不加载 Code Guide Agent。环境变量 `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` 可以完全禁用内置 Agent,给 SDK 用户提供空白画布。
  149. ## Agent Memory:持久化的 Agent 状态
  150. 当 `memory` 字段启用时,Agent 获得跨会话的持久记忆:
  151. - **`local`**:当前项目、当前用户有效
  152. - **`project`**:当前项目所有用户共享
  153. - **`user`**:所有项目共享
  154. Memory 通过 `loadAgentMemoryPrompt()` 注入到 system prompt 末尾,包含读写记忆的指令。Agent Memory Snapshot 机制在项目间同步 `user` 级记忆。