Subagents
使用 Claude Code subagents 隔离上下文、并行处理专门任务,并构建可复用 specialist workers。
Subagents 是什么
Subagents 是主会话派生出的独立 Claude workers。每个 subagent 有自己的上下文窗口、指令、工具权限和权限行为。主会话委托任务,subagent 独立工作,最后把结果摘要返回。
当一个任务会产生大量搜索结果、日志、测试输出或文件内容,而这些噪声又不值得长期留在主对话里时,就适合用 subagent。
内置 Subagents
Claude Code 内置了一些可自动使用的 subagents:
| Subagent | 典型职责 | 工具形态 |
|---|---|---|
| Explore | 快速搜索和分析代码库 | 只读 |
| Plan | 在 plan mode 中做研究 | 只读 |
| General-purpose | 复杂多步骤任务 | 继承更广工具 |
通常不需要精确点名。自然语言即可:
Use a subagent to inspect the auth module and report the likely root cause.
Keep the main conversation clean; return only findings and relevant files.前台与后台
Subagents 可以前台运行,也可以后台运行。
- 前台:主对话等待 subagent 完成。需要权限审批时会弹给你。
- 后台:你继续工作,subagent 在旁边运行。它只能使用已授权权限,会自动拒绝需要新审批的动作。
明确要求后台运行:
Run a background subagent to execute the full test suite.
Report only failing tests and error messages.如果后台 subagent 因为需要审批失败,就改成前台重试。
自定义 Subagents
用 /agents,或在 .claude/agents/ / ~/.claude/agents/ 下写 Markdown 文件。
---
name: security-reviewer
description: Use after API or auth changes to review for security risks.
tools: Read, Grep, Glob, Bash
model: sonnet
permissionMode: plan
---
You are a security reviewer. Inspect the changed files and nearby code.
Focus on auth bypass, missing validation, injection risks, secrets, and unsafe logging.
Return findings with file paths, severity, and a concrete fix.description 很重要。Claude 会用它判断什么时候应该调用这个 subagent。
工具与权限边界
Subagents 默认继承工具,但你可以收窄权限。更安全的 worker 通常这样设计:
- Review 类 worker 只给只读工具。
- 分析 agent 用
permissionMode: plan。 - 用
disallowedTools去掉高风险能力。 - 如果只需要一个外部系统,就只开放对应 MCP server。
- 用
maxTurns限制后台任务范围。
这样 subagent 更像一个专门进程,而不是一段泛泛 prompt。
Worktree 隔离
并行编辑时,只有上下文隔离不够,还需要文件隔离。
给自定义 subagent 设置 isolation: worktree,或要求 Claude 为 agents 使用 worktrees:
---
name: test-fixer
description: Fixes isolated test failures without touching unrelated code.
tools: Read, Edit, Bash
isolation: worktree
---
Claude Code 会为 subagent 创建临时 git worktree。没有改动时可以自动清理;有改动时会保留 worktree,供人 review。
Nested Subagents
当前 Claude Code 支持固定深度内的 nested subagents。谨慎使用。它适合被委托任务本身还能自然拆分时,比如 review subagent 针对多个发现再派 verifier subagents。
日常任务不要过度嵌套。它会增加启动成本、token 成本和协调成本。
什么时候不要用 Subagent
这些情况留在主对话更好:
- 任务需要频繁来回确认。
- 实现和 review 依赖同一份实时上下文。
- 改动很小、定位很准。
- 延迟比上下文卫生更重要。
如果你只是需要可复用指令,而不是上下文隔离,用 skill 更合适。
Subagents vs Agent Teams
| 问题 | 用 subagents | 用 agent teams |
|---|---|---|
| worker 只需要向 parent 汇报吗? | 是 | 否 |
| worker 需要彼此发消息吗? | 否 | 是 |
| 主要是在隔离上下文吗? | 是 | 有时 |
| 协调成本值得吗? | 通常低 | 只适合复杂工作 |
Subagents 是日常并行工具。Agent teams 是更重的协作模式。
Subagents vs Dynamic Workflows
需要一个专门 worker 时用 subagent。需要 Claude 写 orchestration script,并通过可重复 phases 调度大量 agents 时,用 dynamic workflow。
| 需求 | 使用 |
|---|---|
| 检查一个 subsystem 并总结 | Subagent |
| 运行大量独立检查并交叉验证 findings | Dynamic workflow |
| 把中间结果留在主上下文外 | Dynamic workflow |
| 定义可复用 specialist worker | Custom subagent |
官方参考
- Create custom subagents
- Run agents in parallel
- Dynamic workflows
- Run parallel sessions with worktrees
继续实践
Subagents 的核心概念已经读完
如果你想把理解变成可复用的能力,可以到 AgentWay 继续练习