Claude Code(七)Subagents:构建分工协作的多智能体系统
深入探索 Claude Code 的 Subagent 机制。从单体 Agent 到多智能体编排,解析如何通过专业分工更好地管理上下文,实现复杂任务的并行处理与高效交付。
随着我对 Claude Code 使用的深入,我发现一个问题:当任务变得过于复杂时,单一的通用 Agent 开始显露出疲态。
比如,当我要求它”重构整个后端 API 并同步更新前端组件和文档”时,它往往会顾此失彼——要么改了后端忘了前端,要么更新了代码忘了文档。这是因为通用大模型的上下文是有限的,试图让一个模型同时处理三个截然不同的领域(SQL、React、Markdown),容易导致遗漏和错误。
这促使我开始探索 Subagents(子智能体) 机制。这不仅仅是功能的堆叠,而是工作方式的转变,让我能够从随性的 “Vibe Coding” 转向更严谨的 “Spec-Driven Development” (规格驱动开发)。
Core Principles:为什么需要 Subagents?
在软件团队中,我们不会让一个人既做产品经理,又做后端架构师,还兼职前端切图。专业分工是提高效率的根本。
Subagent 的核心逻辑也是如此:将复杂任务解耦,分配给拥有特定上下文和工具的专家。
单体 vs 多智能体
| 维度 | 单体 Agent (Generalist) | 多智能体系统 (Subagents) |
|---|---|---|
| 上下文 | 试图装入整个项目的所有细节 | 独立上下文窗口(每个 Agent 可达 200k Tokens),互不污染 |
| Prompt | 冗长的通用指令 | 精简的专用指令(Expert Persona) |
| 工具集 | 访问所有工具(风险高) | 仅访问特定工具(如 DB Agent 只能用 SQL 工具) |
| 执行模式 | 串行阻塞 | 支持 并行/后台执行 (Ctrl + B) |
Architecture:编排与分发
在 Claude Code 的 Subagent 架构中,我观察到它采用的是 Orchestrator-Workers(指挥官-工兵) 模式。
graph TD
User["我"] --> Main["主 Agent Orchestrator"]
Main -- 任务分发 --> FE["前端专家 Subagent A"]
Main -- 任务分发 --> BE["后端专家 Subagent B"]
Main -- 任务分发 --> QA["测试专家 Subagent C"]
subgraph Context_A["前端上下文"]
FE --> React["React 组件库"]
FE --> CSS["Tailwind 配置"]
end
subgraph Context_B["后端上下文"]
BE --> DB["Schema 定义"]
BE --> API["Controller 代码"]
end
FE -- 交付代码 --> Main
BE -- 交付接口 --> Main
QA -- 交付报告 --> Main
Main -- 最终整合 --> User
- Main Agent:作为入口,它负责理解我的高层意图(Intent),规划任务路径,并决定调用哪个 Subagent。它就像是一个 Technical Lead。
- Subagent:作为执行者,它们拥有独立的 System Prompt 和 Context Window。它们看不见彼此的工作细节,只通过 Main Agent 交换必要的信息。
Practical Implementation:定义我的专家团队
Claude Code 允许我通过配置文件定义 Subagent。
目录结构
通常我会建立 .claude/agents/ 目录:
1
2
3
4
.claude/agents/
├── sql-optimizer.md # SQL 优化专家
├── frontend-dev.md # 前端开发专家
└── design-enforcer.md # 设计系统执行者
定义专家 1: SQL Optimizer (特定领域专家)
在 sql-optimizer.md 中,我这样定义:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
---
name: sql-expert
description: 专门负责 SQL 查询优化和 Schema 设计的专家
model: claude-3-opus-20240229
tools: [read_file, execute_sql] # 限制只能用这些工具
---
你是一个经验丰富的数据库管理员 (DBA)。
你的任务是分析慢查询并提供优化建议。
## 核心原则
1. **索引优先**:总是检查 WHERE 子句中的列是否有索引。
2. **避免全表扫描**:严禁 SELECT *。
3. **执行计划**:在修改前,必须先使用 EXPLAIN 分析。
## 上下文
只关注 `src/database/schema.sql` 和 `src/queries/` 目录。
示例Game Performance Profiler (游戏性能分析专家)
性能优化是游戏开发的核心需求,这个 Subagent 专门用于分析 Unity Profiler 数据,定位性能瓶颈。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
---
name: game-profiler
description: 游戏性能分析专家,分析 Unity Profiler 数据,定位 CPU/GPU/内存瓶颈。
使用场景:帧率下降、内存泄漏、CPU 占用过高、GC 过于频繁。
model: opus
color: red
tools: [Read, Write, Edit, Bash]
---
你是一位游戏性能优化专家,熟悉 Unity Profiler 各模块的使用。
**Core Responsibilities:**
1. CPU 分析
- 识别高耗时函数(超过 1ms/帧)
- 检查 Physics.FixedUpdate 频率
- 分析脚本执行时间分布
2. Rendering 分析
- 识别 Draw Calls 和 SetPass Calls
- 检查 Overdraw(透明物体重叠渲染)
- 分析 Shadow cascade 配置
3. Memory 分析
- 识别内存泄漏(持续增长的 Texture/Mesh 数量)
- 分析 GC Alloc 来源
- 检查 Mono Heap 使用情况
4. Physics 分析
- 识别碰撞体过多的问题
- 检查 Rigidbody 设置是否合理
- 分析物理计算开销
**Analysis Process:**
1. 读取 Profiler 导出数据(.csv 或 .json)
2. 识别性能异常区间
3. 按类型(CPU/GPU/Memory)分类问题
4. 提供优化建议
**Output Format:**
1. 性能摘要(平均 FPS、最低 FPS、主要瓶颈)
2. 问题列表(按严重程度排序)
3. 优化建议(具体到代码/资源修改)
4. 预估性能提升幅度
**Critical Rules:**
- NEVER 建议使用 #pragma warning disable 来隐藏警告
- ALWAYS 先验证优化不会破坏功能
- 对于复杂的优化,建议分步骤实施
<example>
Context: Game drops to 15 FPS on mid-range devices
user: "帮我分析一下为什么帧率这么低"
assistant: "I'll use the game-profiler agent to analyze the performance data and identify the bottlenecks."
</example>
调用流程
当我在主对话框中输入:
“User 表的查询变慢了,请优化一下。”
Main Agent 会分析这个请求,识别到关键词 “查询” 和 “User 表”,然后:
- 挂起当前状态。
- 唤醒
sql-expert。 - 将任务传递给
sql-expert。 sql-expert加载它的专用 Prompt,读取数据库文件,给出优化方案。sql-expert退出,将结果返回给 Main Agent。- Main Agent 向我汇报:”已优化 User 表查询,添加了联合索引…”
如何主动触发 Subagent Main Agent 的调度是语义驱动的,而非关键词匹配。要让它正确调用你的 Agent:
- 在
description中使用场景化描述而非简单列表- 包含典型对话示例(
<example>块)- 明确 Agent 的输入输出契约
Step-by-Step:如何创建一个 Subagent
在深入实战应用之前,让我先梳理一下 Subagent 的完整创建流程。经过多次实践,我发现创建一个高质量的 Subagent 其实非常直观——它本质上就是一个 Markdown 文件。
文件结构解析
Claude Code 的 Subagent 定义非常简洁:一个 Markdown 文件,包含 YAML Frontmatter 和 System Prompt 两部分。
1
2
.claude/agents/
└── my-specialist.md
Anatomy of an Agent(Agent 解剖学)
让我们从一个完整的例子开始,拆解每个部分的作用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
---
name: code-refactor-master
description: 专门负责代码重构的专家,用于重组文件结构、拆分大组件、更新导入路径等
model: opus
color: cyan
---
You are the Code Refactor Master, a specialist in code organization...
## Core Responsibilities
1. File Organization & Structure
2. Dependency Tracking & Import Management
3. Component Refactoring
## Your Refactoring Process
1. Discovery Phase
2. Planning Phase
3. Execution Phase
4. Verification Phase
## Critical Rules
- NEVER move a file without first documenting ALL its importers
- ALWAYS maintain backward compatibility
Frontmatter:配置元数据
YAML Frontmatter 定义了 Agent 的基本身份和能力:
| 字段 | 必填 | 说明 | 示例 |
|---|---|---|---|
name | ✅ | Agent 的唯一标识符,用于在对话中引用 | code-refactor-master |
description | ✅ | 详细描述 Agent 的用途和适用场景,包含使用示例 | 用于帮助主 Agent 识别何时调用此 Agent |
model | ❌ | 指定使用的模型 | opus, sonnet, haiku, 或 inherit(继承主 Agent 模型) |
color | ❌ | UI 中显示的颜色标识 | cyan, blue, green |
tools | ❌ | 限制可用的工具列表 | [Read, Write, Edit, Bash] |
实践心得:description 字段至关重要,它不仅是给人类看的,更是主 Agent 决策的依据。我在编写时会刻意包含 <example> 块,描述典型的使用场景和触发条件。
编写有效的 Agent Description 一个好的
description应该回答三个问题:
- 这个 Agent 做什么?(核心职责)
- 什么时候调用它?(触发条件)
- 和其他 Agent 有什么区别?(边界界定)
System Prompt:塑造 Agent 的行为
这是 Agent 的行为定义,决定了它如何思考和执行。一个高质量的 System Prompt 通常包含以下结构:
角色定义(Persona)
1
2
You are the Code Refactor Master, a specialist in code organization,
architecture improvement, and refactoring.
明确 Agent 的身份,使用专业术语来界定其能力边界。
核心职责(Core Responsibilities)
1
2
3
4
5
6
7
8
9
10
**Core Responsibilities:**
1. File Organization & Structure
- Analyze existing file structures
- Create logical directory hierarchies
- Establish clear naming conventions
2. Dependency Tracking & Import Management
- Document every single import before moving files
- Update all import paths systematically
使用嵌套列表结构,清晰地定义 Agent 的能力范围。
工作流程(Process)
这是 Agent 执行任务的流程定义,确保它按照正确的方式工作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
**Your Refactoring Process:**
1. Discovery Phase
- Analyze current file structure
- Map all dependencies
- Document anti-patterns
2. Planning Phase
- Design new organizational structure
- Create dependency update matrix
3. Execution Phase
- Execute in atomic steps
- Update imports immediately
4. Verification Phase
- Verify all imports resolve
- Ensure no functionality broken
关键规则(Critical Rules)
使用明确的约束词(NEVER, ALWAYS)来强调不可违背的规则:
1
2
3
4
**Critical Rules:**
- NEVER move a file without first documenting ALL its importers
- NEVER leave broken imports in the codebase
- ALWAYS maintain backward compatibility
约束的设计 Agent 的约束清晰度决定了其可靠性:
- NEVER 用于安全边界(防止破坏性操作)
- ALWAYS 用于质量底线(确保输出一致性)
- 避免过度约束,否则会降低 Agent 的灵活性
输出格式(Output Format)
定义 Agent 返回结果的标准格式:
1
2
3
4
5
6
**Output Format:**
When presenting refactoring plans, you provide:
1. Current structure analysis
2. Proposed new structure
3. Complete dependency map
4. Step-by-step migration plan
定义明确的交付契约 Agent 的输出格式决定了它是否能无缝集成到你的工作流:
- 结构化输出优于自然语言(JSON/表格 > 段落)
- 明确可执行步骤而非模糊建议
- 提供验证标准(如何判断成功)
- 包含回滚方案(高风险操作必选)
好的输出 = 主 Agent 可以直接执行,无需进一步澄清
创建流程:从零到一
让我用一个实际案例来演示完整的创建过程。
场景:我需要一个”文档编写专家”
我发现自己经常需要为新功能编写文档,但主 Agent 的文档质量不稳定——有时太简略,有时又太冗长。我决定创建一个专门的 documentation-architect。
Step 1:定位存放位置
1
mkdir -p .claude/agents
Step 2:编写 Frontmatter
1
2
3
4
5
6
7
8
---
name: documentation-architect
description: Use this agent when you need to create, update, or enhance documentation
for any part of the codebase. This includes developer documentation, README files,
API documentation, data flow diagrams, testing documentation, or architectural overviews.
model: sonnet
color: blue
---
Step 3:设计 System Prompt
我开始思考:什么样的文档才是好文档?
- 需要理解完整的上下文,不只是刚修改的文件
- 应该查阅现有的文档,保持风格一致
- 要考虑目标读者的需求
- 需要包含代码示例和故障排除
基于这些思考,我写出了 System Prompt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
You are a documentation architect specializing in creating
developer-focused documentation for complex software systems.
**Core Responsibilities:**
1. Context Gathering:
- Check memory MCP for stored knowledge
- Examine /documentation/ directory
- Analyze source files beyond current session
2. Documentation Creation:
- Developer guides with code examples
- README files with setup/troubleshooting
- API documentation with endpoints and examples
- Data flow diagrams and architectural overviews
**Methodology:**
1. Discovery Phase:
- Query memory MCP for relevant information
- Scan /documentation/ and subdirectories
- Identify all related source files
2. Analysis Phase:
- Understand complete implementation
- Identify key concepts needing explanation
- Recognize patterns and edge cases
3. Documentation Phase:
- Structure content logically
- Write concise yet comprehensive
- Include practical code examples
Step 4:添加约束和输出格式
1
2
3
4
5
6
7
8
9
10
11
12
13
**Documentation Standards:**
- Use clear technical language
- Include table of contents for longer documents
- Provide both quick start and detailed sections
- Cross-reference related documentation
**Output Format:**
1. Explain documentation strategy before creating files
2. Provide summary of context gathered
3. Suggest documentation structure and get confirmation
4. Create documentation that developers can easily understand
Step 5:测试和迭代
在主对话中测试:
“Use the documentation-architect agent to document the new authentication flow”
观察返回结果,如果发现:
- 文档太泛泛 → 在 Prompt 中增加 “Include specific code examples” 约束
- 文档风格不一致 → 添加 “Match existing documentation style in /docs/”
- 缺少重要信息 → 在 Discovery Phase 中增加检查点
Agent 的迭代过程 第一个版本很难做到完善,迭代是必经之路: | 迭代阶段 | 关注点 | 典型调整 | |———-|——–|———-| | V1 | 基本可用 | 修复明显错误,补充遗漏职责 | | V2 | 稳定性 | 添加约束,优化输出格式 | | V3 | 鲁棒性 | 处理边缘情况,完善错误处理 |
每次迭代后记录变化,这样可以追踪 Agent 的改进过程。
Advanced Patterns:高级技巧
技巧 1:使用 Example 块引导主 Agent
在 description 中嵌入示例,帮助主 Agent 识别调用时机:
1
2
3
4
5
6
7
8
9
10
description: Use this agent when you need to document features.
<example>
Context: User just implemented JWT authentication.
user: "I've finished implementing the auth flow. Can you document this?"
assistant: "I'll use the documentation-architect agent to create comprehensive docs."
<commentary>
Since the user needs documentation for a newly implemented feature, use the documentation-architect agent.
</commentary>
</example>
技巧 2:工具限制与安全
对于敏感操作,显式限制可用工具:
1
2
3
4
5
---
name: read-only-auditor
description: Read-only code quality checker
tools: [Read, Grep, Glob] # 限制为只读工具
---
最小权限原则 Agent 的工具访问范围应遵循最小必要原则:
- 只读 Agent:
[Read, Grep, Glob]- 代码审查 Agent:
[Read](完全不能写)- 数据库 Agent:仅限 SQL 执行工具
工具越少,失误的风险越小。宁可多做几次确认,也不要给一个 Agent 赋予过高的权限。
技巧 3:版本特定的知识
如果 Agent 需要了解特定版本的技术栈,在 Prompt 中明确:
1
2
3
4
You are an expert in React 19 with TypeScript and TanStack Router.
- Use React 19's new hooks (use, useOptimistic)
- Follow TanStack Router's file-based routing patterns
- Apply MUI v7/v8 sx prop patterns
技巧 4:返回父进程的协议
对于需要审批的 Agent,定义返回给主 Agent 的协议:
1
2
3
4
5
**Return to Parent Process:**
- Inform parent: "Code review saved to: ./dev/active/[task-name]/code-review.md"
- Include brief summary of critical findings
- IMPORTANT: Explicitly state "Please review findings and approve before I proceed"
- Do NOT implement fixes automatically
设计清晰的交接协议 Subagent 与主 Agent 之间的接口定义是协作效率的关键:
- 摘要层:高层总结(3-5 句话)
- 详细层:分项列出(表格/列表)
- 证据层:引用具体文件和代码位置
好的交接 = 主 Agent 能在 10 秒内理解结果并继续工作
模板速查表
为了快速上手,我总结了一个通用模板:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
---
name: [agent-name]
description: [Detailed description with usage examples]
model: [opus|sonnet|haiku|inherit]
color: [cyan|blue|green|yellow]
tools: [Read, Write, Edit, Bash] # Optional
---
You are a [role], a specialist in [domain].
**Core Responsibilities:**
1. [Responsibility 1]
- Detail A
- Detail B
2. [Responsibility 2]
- Detail A
**Your Process:**
1. [Phase Name]
- Step 1
- Step 2
2. [Phase Name]
- Step 1
**Critical Rules:**
- NEVER [prohibited action]
- ALWAYS [required action]
**Output Format:**
When completing tasks, provide:
1. [Output type 1]
2. [Output type 2]
创建 Subagent 的本质是:将领域知识、工作流程和质量标准封装成一个可复用的指令集。写好一个专家 Agent 后,它就像一个随时可调用的专业工具。
实战心得:什么时候用 Subagent?
并不是所有任务都需要 Subagent。经过多次实践,我总结了以下标准:
Subagent 判定矩阵 在决定是否创建 Subagent 前,问自己: | 维度 | 低复杂度任务 | 高复杂度任务 | |——|————-|————-| | 领域专精 | 通用模型足以应对 | 需要领域专家知识 | | 安全风险 | 操作可撤销 | 有破坏性后果 | | 上下文密度 | 单文件/局部修改 | 全局依赖分析 | | 可复用性 | 一次性需求 | 将重复使用 |
满足 2+ 项?→ 创建 Subagent 全部否决?→ 直接让主 Agent 处理
- ❌ 不用 Subagent:
- 简单的 Bug 修复。
- 单文件的逻辑修改。
- 跨度很小的任务。
- 理由:切换 Agent 有上下文切换成本(Context Switching Cost),简单任务无需复杂处理。
- ✅ 使用 Subagent:
- 独立性强的模块:如完全独立的微服务,或与业务逻辑分离的 UI 组件库。
- 高风险操作:如数据库迁移,我希望限制 Agent 只能运行只读命令,不能运行 DROP TABLE。通过 Subagent 的权限管控可以有效实现。
- 特定领域知识:如编写复杂的正则,或撰写符合特定法律法规的条款。
- 上下文密集型任务:如”重构整个项目目录结构”,这类任务需要大量搜索和依赖分析,如果放在主对话中会快速消耗上下文。Subagent 在独立环境中运行,只返回最终报告。
Advanced Configuration:深度定制
除了基础的 Prompt 定义,Claude Code 还支持更高级的配置:
权限与安全模型 (Security Model)
在 CLI 环境中,安全至关重要。我们可以通过 permissionMode 精确控制 Subagent 的行为边界:
default:标准模式,敏感操作(写文件、Shell 命令)会请求用户批准。bypassPermissions:谨慎使用。跳过所有权限检查,适合完全受信任的自动化脚本。readOnly模式:通过disallowedTools: [Write, Edit]强制创建一个只读的”审计员” Agent。
记忆与学习 (Persistent Memory)
通过 memory 字段,我们可以让 Agent 记住跨 Session 的知识。
工作原理
Persistent Memory 的机制是”自动加载,主动保存”:
1
memory: project # 将记忆存储在 .claude/projects/.../memory/ 下
读取(自动):当 Agent 启动时,系统会将 MEMORY.md 的内容自动注入到它的 System Prompt 中。这就像给 Agent 提供了一份之前经验的参考。
保存(主动):Agent 需要通过 Write 或 Edit 工具显式地更新 MEMORY.md。如果没有在 Prompt 中告诉它”把学到的东西记下来”,它可能本次会话知道但下次就忘了。
实践配置
在 System Prompt 中添加指令:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
name: sql-expert
description: SQL 优化专家
memory: project
---
你是一个数据库专家。每次你学到新的优化经验或发现特定的数据库特性时,
请将总结写入 `MEMORY.md` 文件,以便下次会话时使用。
**记忆格式示例:**
## Project-specific Knowledge
### User Table Optimization
- User 表的 email 列查询频繁,确保有索引
- 避免在 User 表上使用 JOIN,考虑分表策略
重要提醒:Memory 不是自动记录所有对话的日志。它是 Agent 的笔记——需要明确告诉 Agent “把这条信息记下来”。
让 Agent 学会”记笔记” Persistent Memory 的价值取决于记录质量:
- 使用结构化格式(标题、分类、要点)
- 记录反模式和陷阱(比正确方案更有用)
- 包含可执行的具体信息(而非抽象总结)
- 定期回顾和清理过时知识
Agent 的效果取决于提示质量和记录内容的实用性
记忆存储位置
1
2
3
4
5
.claude/
└── projects/
└── [project-id]/
└── memory/
└── MEMORY.md
这意味着如果 sql-expert 昨天学到了”User 表不能用这个索引”,今天它依然记得——前提是昨天的对话中它把这条经验写进了 MEMORY.md。这对于长期维护的项目至关重要。
生命周期钩子 (Lifecycle Hooks)
我们可以定义 PreToolUse 钩子来做更细粒度的控制。例如,在执行任何 SQL 之前,先运行一个脚本检查是否包含 DROP 或 TRUNCATE 关键字:
自动化验证层 Hooks 是 Agent 的安全检查点,可用于:
- PreToolUse:操作前验证(如 SQL 语法检查)
- PostToolUse:操作后审计(如记录文件修改)
- PreAgentLaunch:Agent 启动前环境检查
Hook 不应该替代 Prompt 约束,而是作为补充的安全网。
1
2
3
4
5
6
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-sql-safety.sh"
生产力技巧 (Pro Tips)
- 后台执行:通过
Ctrl + B可以让 Subagent 在后台运行。这对于运行耗时的测试套件或全库扫描非常有用,你可以继续在主线程做其他事情。 - 自然语言配置:你可以直接告诉 Claude “创建一个专门写文档的 Agent”,它会帮你生成配置文件,无需手动编写 YAML。
Case Study: 隔离式 Bug 修复
这是 Subagent 的典型使用场景之一:将”调试过程”封装在子线程,只将”修复结果”返回给主线程。这既能节省 Token,又能保持主上下文的整洁。
场景描述
我在主 Agent 中开发一个新功能,遇到了一个复杂的报错。如果让主 Agent 直接尝试修复,可能会花费多轮对话在试错上,而且这些试错记录会污染主上下文,让后续对话变得臃肿。
解决方案:委托给专门的 Subagent
我创建了一个 auto-error-resolver 专门处理 TypeScript 编译错误:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
---
name: auto-error-resolver
description: Automatically fix TypeScript compilation errors
tools: Read, Write, Edit, MultiEdit, Bash
---
You are a specialized TypeScript error resolution agent.
## Your Process:
1. **Check for error information**:
- Read error cache at: `~/.claude/tsc-cache/[session_id]/last-errors.txt`
- Get TSC commands at: `~/.claude/tsc-cache/[session_id]/tsc-commands.txt`
2. **Analyze the errors**:
- Group by type (missing imports, type mismatches, etc.)
- Prioritize errors that might cascade
3. **Fix errors**:
- Start with import errors
- Then fix type errors
- Use MultiEdit for similar issues
4. **Verify**:
- Run the correct tsc command after changes
- Report success when all resolved
## Return Protocol:
- Summarize what was fixed (file + issue type)
- Do NOT include detailed debug steps in return message
- Just report: "Fixed 5 type errors in src/components/*.tsx"
执行流程
graph LR
A["主 Agent 开发功能"] --> B["遇到 Bug"]
B --> C["调用 auto-error-resolver Subagent"]
C --> D["Subagent 独立调试"]
D --> E["多轮试错与修复"]
E --> F["Subagent 完成任务"]
F --> G["返回简短结果给主 Agent"]
G --> H["主 Agent 继续开发"]
style D fill:#ff9999
style E fill:#ffcccc
style G fill:#99ff99
实际对话
在主对话中:
我:这个新功能有个 TypeScript 报错,请用 auto-error-resolver agent 去修复它,不要在当前会话中尝试。
主 Agent:I’ll use the auto-error-resolver agent to fix these TypeScript errors.
[主 Agent 调用 Task 工具,进入等待状态]
在 Subagent 对话中(独立上下文):
Subagent:Found 12 TypeScript errors in frontend service…
- Error 1: Property ‘onClick’ does not exist…
- Error 2: Module not found… [Subagent 进行搜索、分析、修改、验证,可能需要多轮对话]
Subagent:Fixed all errors. Modified 5 files:
- src/components/Button.tsx: Added onClick to ButtonProps
- src/services/api.ts: Fixed import path
回到主对话:
主 Agent:auto-error-resolver has completed. Fixed 5 type errors in the frontend service. The build now passes.
我:好的,继续完成这个功能的 UI 部分。
关键优势
| 维度 | 主 Agent 直接修复 | Subagent 委托修复 |
|---|---|---|
| Token 消耗 | 试错过程全部进入主上下文,持续累积 | 试错过程留在 Subagent,主上下文只有一行调用 |
| 上下文污染 | 大量报错和试错记录影响后续对话 | 主上下文保持干净,只保留最终结果 |
| 注意力聚焦 | 主 Agent 需要频繁切换任务模式 | 主 Agent 专注于高层逻辑,Subagent 专注调试 |
| 可追溯性 | 难以区分哪些是开发内容,哪些是调试过程 | 调试历史独立记录,便于回顾 |
返回协议设计
对于这种用例,Subagent 的返回格式至关重要。我建议遵循以下原则:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
**Return Protocol:**
DO:
- Summarize what was fixed (high-level)
- List affected files
- Confirm verification passed
DON'T:
- Include detailed error messages
- Show step-by-step debug process
- Return raw tsc output
Example Return:
"Fixed 5 type errors:
- src/components/Button.tsx: Added missing onClick property
- src/utils/helpers.ts: Fixed import path
Build verified with: npx tsc --noEmit ✓"
这样,主 Agent 收到的是一条简洁的”任务完成通知”,而不是整个调试过程的转储。
Case Study: The “Refactor Master”
让我们看一个复杂案例:Code Refactor Master。重构是 LLM 较有挑战性的场景之一,因为它需要全局视野和较高的严谨性。
我定义了一个基于 Opus 模型的重构专家,它的工作流被严格限制为四步:
- Discovery:扫描依赖,建立引用图谱(Dependency Map)。
- Planning:输出详细的迁移计划,包含所有受影响的文件列表。
- Execution:原子化操作,移动一个文件立即更新所有 Import。
- Verification:运行构建检查,确保无悬挂引用。
这比直接让主 Agent “把这个文件夹整理一下” 更可靠,因为它的 System Prompt 里明确规定:”NEVER move a file without first documenting ALL its importers“。
结语
Subagents 是 AI 多智能体协作的第一步。通过构建这套分工体系,我实际上是在组建一个分布式的开发团队。
在这个团队中,我不再是唯一的编码者,而是架构师和决策者。我定义每个 Agent 的职责边界(Role)和交互协议(Protocol),让它们协同工作,从而更好地管理上下文。