首页 › tutorials › Claude Code多Agent编排:Subagent到Team全实战

Claude Code多Agent编排实战:从Subagent到Agent Team全链路

概述

本教程面向已掌握Claude Code基础操作的开发者,系统讲解三大并行编排机制——Subagent(子代理)、Worktree(工作树隔离)、Agent Team(代理团队)——的原理、选型决策与实战模式。通过五个递进案例,你将掌握如何将单个AI编程会话扩展为一支可并行、可协调、可扩展的AI开发团队。适用人群:日常使用Claude Code的中高级开发者、技术负责人、DevOps工程师。

前置条件

条件 说明
Claude Code版本 ≥ v2.1.32(Agent Team需要),Agent View需要 ≥ v2.1.139
基础知识 熟悉Claude Code基本交互、Git操作
运行环境 macOS / Linux终端,可选tmux(分屏模式)
订阅计划 建议Max 5x及以上,并行Agent消耗配额成倍增加
项目要求 必须是Git仓库(Worktree功能依赖Git)

核心架构:三层并行体系

Claude Code在2025-2026年间逐步构建了一套三层并行架构,每一层解决不同规模的协作问题:

graph TB
    subgraph "Layer 3: Agent Team 团队协作"
        LT[Team Lead<br/>协调者] --> T1[Teammate 1<br/>前端]
        LT --> T2[Teammate 2<br/>后端]
        LT --> T3[Teammate 3<br/>测试]
        T1 <-->|直接通信| T2
        T2 <-->|直接通信| T3
    end

    subgraph "Layer 2: Subagent 任务委派"
        PA[Parent Agent<br/>父代理] --> SA1[Explore Agent<br/>代码探索]
        PA --> SA2[General Agent<br/>通用任务]
        PA --> SA3[Custom Agent<br/>自定义]
        SA1 -.->|返回结果| PA
        SA2 -.->|返回结果| PA
        SA3 -.->|返回结果| PA
    end

    subgraph "Layer 1: Worktree 文件隔离"
        W1[Worktree A<br/>feature-auth]
        W2[Worktree B<br/>bugfix-123]
        W3[Worktree C<br/>pr-456]
        W1 --- W2 --- W3
        W1 ---|共享Git历史| MAIN[Main Branch]
        W2 ---|共享Git历史| MAIN
        W3 ---|共享Git历史| MAIN
    end

关键区别: - Subagent 在同一会话内工作,父代理调度、子代理执行、结果回流到父上下文 - Worktree 解决文件隔离问题,每个会话在独立目录工作,不冲突 - Agent Team 多个独立会话组成团队,成员之间可直接通信,共享任务列表


第一步:掌握内置Subagent类型

Claude Code内置三种Subagent类型,每种有明确的设计意图:

内置Subagent一览

类型 模型 工具权限 典型场景
Explore Haiku(低成本) 只读(Read/Grep/Glob) 代码搜索、文件发现、架构理解
Plan 继承父会话模型 只读 Plan模式下收集上下文
General-purpose 继承父会话模型 全部工具 复杂多步骤任务、代码修改

深度:Explore Agent的thoroughness等级

Explore Agent接受三种搜索深度参数,这直接影响Token消耗和搜索质量:

quick       → 精准查找,适合定位特定函数/文件(约30秒)
medium      → 平衡探索,适合理解模块间关系(约1-2分钟)
very thorough → 全面扫描,适合新项目上手或架构分析(约3-5分钟)

实际操作:在Claude Code会话中,你不需要手动选择Subagent类型。Claude会根据任务自动选择:

> 帮我搜索项目中所有的数据库查询函数

Claude会自动委派给Explore Agent(Haiku模型),搜索完成后只返回摘要到主上下文。

当你需要明确指定时:

> Use the Task tool with an Explore subagent set to "very thorough" to map out 
> all the API endpoints in this codebase. Return a structured list with method, 
> path, handler function, and middleware for each endpoint.

预期结果

Claude会显示类似输出:

Dispatching Explore agent (very thorough)...
  Scanning src/routes/... 
  Scanning src/api/...
  Found 23 endpoints across 4 route files

  Summary:
  ├── src/api/auth.ts     → 5 endpoints (register, login, logout, refresh, me)
  ├── src/api/users.ts    → 8 endpoints (CRUD + search + profile)
  ├── src/api/todos.ts    → 7 endpoints (CRUD + filtering + sharing)
  └── src/api/admin.ts    → 3 endpoints (stats, export, health)

常见问题

Q: 为什么Explore Agent没有找到我期望的文件? A: Explore Agent默认搜索当前工作目录。如果文件在--add-dir添加的目录中,Explore不会扫描那些目录的文件模式。解决:直接告诉Claude文件的大致位置。

Q: Subagent能嵌套调用吗? A: 不能。Subagent不能再创建自己的Subagent,这是设计限制,防止无限递归。


第二步:创建自定义Subagent

当内置Subagent无法满足需求时,你可以定义自己的专用代理。

方法一:使用 /agents 命令(推荐)

在Claude Code中运行:

/agents

切换到 Library 标签 → Create new agent → Personal(保存到~/.claude/agents/)。

以创建一个"安全审计Agent"为例,描述如下:

A security audit agent that scans source code for OWASP Top 10 
vulnerabilities. It should check for: SQL injection, XSS, CSRF, 
authentication flaws, and insecure dependencies. Return a severity-
ranked report with file paths, line numbers, and remediation suggestions.

选择工具:只勾选Read-only tools(审计不需要写文件)。 选择模型:Sonnet 4.6(平衡能力和成本)。

方法二:手动创建Markdown文件

在项目根目录创建.claude/agents/目录,添加Markdown文件:

---
name: security-auditor
description: Scans code for OWASP Top 10 vulnerabilities
model: claude-sonnet-4-6
tools:
  - Read
  - Grep
  - Glob
  - Bash
---

You are a security code auditor. Analyze the codebase for these vulnerability categories:

1. **Injection** (SQL, NoSQL, Command, LDAP)
2. **Broken Authentication**
3. **Sensitive Data Exposure**
4. **XML External Entities (XXE)**
5. **Broken Access Control**
6. **Security Misconfiguration**
7. **Cross-Site Scripting (XSS)**
8. **Insecure Deserialization**
9. **Using Components with Known Vulnerabilities**
10. **Insufficient Logging & Monitoring**

For each finding, provide:
- Severity: Critical / High / Medium / Low
- File path and line number
- Vulnerable code snippet
- Remediation recommendation with code example

Output as a structured markdown table sorted by severity.

方法三:CLI标志定义(临时)

claude --agents '[
  {
    "name": "perf-profiler",
    "description": "Profiles React components for unnecessary re-renders",
    "model": "claude-sonnet-4-6",
    "tools": ["Read", "Grep", "Glob"]
  }
]'

Subagent作用域与优先级

优先级从高到低:
1. Managed Settings  → 组织级,管理员部署
2. --agents CLI标志  → 当前会话
3. .claude/agents/   → 当前项目(可提交Git共享)
4. ~/.claude/agents/ → 用户级,所有项目可用
5. 插件 agents/     → 插件提供

同名Subagent,高优先级覆盖低优先级。

预期结果

保存后立即可用:

> Use the security-auditor agent to scan the src/auth/ directory

Claude会委派给你的自定义Subagent,它将用你定义的提示词和安全审计视角扫描代码。

常见问题

Q: 自定义Subagent能访问MCP服务器吗? A: 可以。Subagent继承父会话的MCP服务器配置。但如果在tools字段中限制了工具,MCP工具也会被过滤。

Q: 项目级和用户级Subagent应该放哪里? A: 项目级放.claude/agents/(可提交Git,团队共享),用户级放~/.claude/agents/(个人工具,跨项目复用)。


第三步:Worktree隔离——并行会话不冲突

当多个Agent同时修改文件时,Worktree提供物理隔离。

3.1 启动Worktree会话

# 方式一:指定名称
claude --worktree feature-auth

# 方式二:简写
claude -w bugfix-123

# 方式三:自动命名(如 bright-running-fox)
claude --worktree

# 方式四:基于PR创建
claude --worktree "#142"

每个Worktree创建在.claude/worktrees/<name>/下,独立分支worktree-<name>。

3.2 配置.baseRef

默认从origin/HEAD(远程默认分支)创建。修改配置可从本地HEAD创建:

// ~/.claude/settings.json
{
  "worktree": {
    "baseRef": "head"
  }
}

"head"适用于Subagent需要基于你当前进行中的工作分支操作。"fresh"(默认)确保干净起点。

3.3 复制环境文件

Worktree是全新checkout,.env等gitignored文件不会出现。创建.worktreeinclude文件自动复制:

# .worktreeinclude(使用.gitignore语法)
.env
.env.local
config/secrets.json

仅复制同时匹配.worktreeinclude模式且被Git忽略的文件,已跟踪文件不会被重复。

3.4 Subagent使用Worktree隔离

在自定义Subagent定义中添加isolation: worktree:

---
name: parallel-refactorer
description: Refactors a module in isolation
isolation: worktree
---

You are a code refactoring specialist. ...

或在会话中指示:

> Use worktrees for your subagents when parallelizing this refactoring

3.5 清理规则

情况 行为
无修改、无未跟踪文件 Worktree和分支自动删除
有未提交修改/新commit 提示保留或删除
-p非交互模式 不自动清理,需手动git worktree remove
Subagent/Background创建的Worktree 超过cleanupPeriodDays后自动清理(前提:无未提交修改)

重要:将.claude/worktrees/添加到.gitignore。


第四步:Agent Team——多会话协调

Agent Team是最高级的并行模式,适合需要多Agent相互交流的复杂任务。

4.1 启用Agent Team

// ~/.claude/settings.json
{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}

或在shell中:

export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
claude

4.2 创建第一个Team

> I'm building a real-time chat application. Create an agent team with:
> - One teammate for the WebSocket backend (Node.js + Socket.io)
> - One teammate for the React frontend (chat UI, message list, typing indicators)
> - One teammate for writing integration tests
> All three should work in parallel. The backend and frontend can start simultaneously;
> tests should wait until both are done.

Claude会: 1. 创建Team Lead(协调者) 2. 生成三个Teammate,分配任务 3. 管理任务依赖(frontend/backend并行,tests等前两者完成)

4.3 显示模式

// ~/.claude/settings.json
{
  "teammateMode": "in-process"  // 或 "tmux", "auto"
}
模式 说明 要求
in-process 所有Teammate在主终端内,Shift+Down切换 无
tmux 每个Teammate独立分屏 需安装tmux
auto 检测到tmux则用tmux,否则in-process 默认

4.4 控制Teammate

# 直接与Teammate交互
> Ask the backend teammate to also add rate limiting to the WebSocket connections

# 要求计划审批
> Spawn an architect teammate to refactor the auth module. 
> Require plan approval before they make any changes.

# 关闭Teammate
> Ask the researcher teammate to shut down

# 清理Team
> Clean up the team

4.5 Subagent定义作为Teammate

你可以将自定义Subagent定义复用为Teammate:

> Spawn a teammate using the security-reviewer agent type to audit the auth module.

Teammate会继承该Subagent定义的tools白名单和model选择。

4.6 Hooks质量门禁

在Team工作流中用Hooks强制质量标准:

{
  "hooks": {
    "TeammateIdle": [{
      "type": "command",
      "command": "bash -c 'npm test 2>&1 || exit 2'"
    }],
    "TaskCompleted": [{
      "type": "command",
      "command": "bash -c 'npx eslint $(cat stdin | jq -r .files[].path) 2>&1 || exit 2'"
    }]
  }
}

exit 2表示拒绝并发送反馈,Teammate必须继续工作修复问题。


第五步:选型决策矩阵

这是最关键的章节。选错模式不仅浪费Token,还会产生更差的结果。

flowchart TD
    START[需要并行工作] --> Q1{任务之间<br/>需要通信吗?}
    Q1 -->|否| Q2{每个任务<br/>需要修改文件吗?}
    Q1 -->|是| TEAM[Agent Team<br/>多会话协调]
    Q2 -->|否| Q3{只是搜索/<br/>分析代码?}
    Q2 -->|是| Q4{修改同一文件/<br/>有依赖关系?}
    Q3 -->|是| SUB_EXPLORE[Explore Subagent<br/>Haiku只读]
    Q3 -->|否| SUB_PLAN[Plan Subagent<br/>只读规划]
    Q4 -->|是| SEQUENTIAL[单会话顺序执行<br/>不要并行]
    Q4 -->|否| Q5{需要物理<br/>文件隔离?}
    Q5 -->|是| WORKTREE[Worktree + Subagent<br/>隔离执行]
    Q5 -->|否| SUB_GENERAL[General-purpose Subagent<br/>同一目录并行]

三大模式对比

维度 Subagent Agent Team Worktree
Token成本 低(结果摘要回流) 高(每会话独立上下文) 同Subagent
通信方式 单向:子→父 双向:成员间直接通信 N/A(隔离层)
上下文 共享父会话上下文 各自独立上下文 取决于使用方式
适用规模 3-8个并行任务 2-6个协调者 无限制
典型场景 并行搜索、批量生成 架构评审、竞争假设调试 多人/多Agent并行开发
设置复杂度 零配置 需启用实验标志 需Git仓库

什么时候不该用并行

  1. 顺序依赖任务:规划→编码→测试→提交,每步需要上一步结果
  2. 简单任务:30秒内能完成的工作不值得3-5秒的Subagent启动开销
  3. 修改同一文件:并行Agent修改同一文件必然冲突,必须顺序执行
  4. 共享状态需求:Agent A的中间结果需要实时影响Agent B的行为

实战案例:全栈特性开发的AI并行工作流

场景描述

你需要为一个SaaS应用添加"团队工作区"功能,涉及: - 数据库Schema设计 - API路由实现(5个端点) - React前端组件(3个页面) - 集成测试 - API文档

执行策略

gantt
    title 团队工作区功能开发时间线
    dateFormat X
    axisFormat %s分钟

    section Phase 1 - 并行探索
    Explore DB层          :a1, 0, 3min
    Explore API层         :a2, 0, 3min
    Explore 前端层        :a3, 0, 3min

    section Phase 2 - 并行实现
    Schema设计            :b1, 3, 8min
    API路由实现           :b2, 8, 18min
    前端组件开发          :b3, 8, 20min

    section Phase 3 - 验证
    集成测试编写          :c1, 18, 28min
    API文档生成           :c2, 18, 23min
    端到端验证            :c3, 28, 33min

Step 1: 并行探索(4分钟)

> I need to add a "Team Workspace" feature to this SaaS app. 
> Use the Task tool to spawn 4 Explore subagents in parallel:
> 1. Explore the database layer: find all Prisma models, migration patterns, relations
> 2. Explore the API layer: find route patterns, middleware, auth decorators, error handling
> 3. Explore the frontend: find component structure, state management, routing patterns
> 4. Explore the test suite: find test frameworks, fixtures, integration test patterns
> 
> Each should return a 200-word summary with key files and patterns identified.

为什么用Subagent而不是Agent Team? 探索是独立任务,不需要Agent之间通信,Subagent成本更低(Explore用Haiku)。

Step 2: Schema设计(5分钟)

> Based on the exploration results, design a Prisma schema for workspaces. 
> Include: Workspace, WorkspaceMember, WorkspaceInvite models.
> Follow the existing model patterns. Write the migration file.

这一步用主会话直接执行,因为需要引用Step 1的探索结果。

Step 3: 并行实现(12分钟)

> Now implement in parallel using 3 Subagents with worktree isolation:
> 
> Subagent A (in worktree): Implement 5 API routes for workspaces:
>   POST /workspaces, GET /workspaces/:id, PUT /workspaces/:id, 
>   DELETE /workspaces/:id, POST /workspaces/:id/members
>   Follow the route patterns from exploration. Use the schema from Step 2.
> 
> Subagent B (in worktree): Build 3 React pages:
>   WorkspaceList, WorkspaceSettings, InviteMembers
>   Follow the component patterns from exploration. Use existing UI library.
> 
> Subagent C (in worktree): Generate OpenAPI docs for all new endpoints.
>   Follow existing doc format.
> 
> Return a summary of files created/modified for each.

为什么用Worktree隔离? 三个Agent分别修改不同的文件集,Worktree确保零冲突。

Step 4: 测试与验证(10分钟)

> Write integration tests for all workspace API routes.
> Cover: CRUD operations, member management, permission checks, 
> error cases. Follow the test patterns from exploration.
> After writing tests, run the full test suite and fix any failures.

测试需要等API路由完成,所以顺序执行。

Step 5: 合并与清理

# 查看Worktree状态
git worktree list

# 切到各Worktree审查修改
cd .claude/worktrees/<name> && git diff

# 合并分支
git checkout main
git merge worktree-subagent-a
git merge worktree-subagent-b
git merge worktree-subtree-c

# 清理Worktree
git worktree remove .claude/worktrees/<name>

成本估算

阶段 Agent数 模型 预估Token 预估成本
Phase 1 探索 4 Haiku ~200K in / 15K out ~$0.30
Phase 2 Schema 1 Sonnet ~80K in / 5K out ~$0.32
Phase 3 实现 3 Sonnet ~600K in / 40K out ~$2.40
Phase 4 测试 1 Sonnet ~150K in / 10K out ~$0.60
Phase 5 合并 1 Sonnet ~50K in / 3K out ~$0.20
合计 ~1.08M / 73K ~$3.82

对比顺序执行:~25-40分钟 vs 并行执行的~33分钟实际墙钟时间(但大量时间被并行化,实际等待时间约15分钟)。Token总量因为并行而增加约60%,但墙钟时间节省50%。


进阶技巧:Subagent模板复用

将常用的Subagent调度模式保存为模板,在CLAUDE.md或笔记中复用。

模板一:代码库架构速览

Spawn N sub-agents, one per directory in this list: {directories}.
Each sub-agent reads its directory, identifies the 3 most important files,
and returns a 100-word summary covering: purpose, key patterns, dependencies.
Aggregate into a 500-word architecture brief.

模板二:批量测试生成

Spawn N sub-agents, one per module in this list: {modules}.
Each sub-agent reads its module + existing test patterns from /tests,
then writes one test file matching the existing patterns.
Return only the test file content, not implementation changes.

模板三:多方案对比

Spawn 3 sub-agents. Each one researches a different approach to {problem}:
(a) library-based, (b) custom code, (c) external service.
Each returns a 200-word comparison of pros, cons, and rough cost/complexity.
Synthesize into a recommendation.

模板四:竞争假设调试

Spawn 5 agent teammates to investigate different hypotheses about {bug}.
Have them talk to each other to disprove each other's theories,
like a scientific debate. Update the findings doc with whatever 
consensus emerges.

注意:模板四使用Agent Team而非Subagent,因为需要Agent之间互相辩论。


成本优化策略

并行Agent的Token消耗是线性的——N个并行Agent = N倍Token消耗。以下是控制成本的关键策略。

模型选择

角色 推荐模型 理由
父代理/协调者 Opus 4.6 需要最强推理能力做决策
代码探索 Haiku 只读任务,速度优先
代码生成 Sonnet 4.6 平衡能力和成本
测试编写 Sonnet 4.6 足够处理测试逻辑
代码审查 Sonnet 4.6 不需要最强推理

并发控制

API Tier 1: 最多 ~5 并发(超出会排队,失去并行优势)
API Tier 4: 可支持 ~20+ 并发

最佳ROI: 4个并行Subagent

提示词精简

Subagent提示词应控制在100-300字。超过这个范围,你不是在"专门化"——你是在把同样的上下文塞进每个新窗口。

结果聚合

始终让父代理综合Subagent的结果。如果你生成6个Subagent却只是把它们的结果首尾相接粘贴,你就浪费了隔离的意义。


调试Subagent问题

问题一:Subagent没有产出预期结果

诊断:让父代理在委派前打印Subagent的提示词。

> Before spawning the subagent, output the prompt you are about to use.
> Let me review it first.

90%的Subagent失败源于糟糕的提示词。

问题二:Subagent执行超慢

诊断:检查是否触发了API限速。

# 查看当前API使用量
# 登录 console.anthropic.com 查看 Usage 页面

如果Tier 1上超过5个并发,Subagent会排队变串行。

问题三:Worktree合并冲突

诊断:手动检查Worktree中的修改。

git worktree list
cd .claude/worktrees/<name>
git diff --name-only

解决:如果多个Worktree修改了相同文件,需要手动合并。

问题四:Agent Team成员通信异常

诊断:使用Ctrl+T切换到任务列表视图,查看各成员状态。

解决:确保Team Lead正常工作。如果Lead崩溃,整个团队协调会中断。


完整工作流架构图

flowchart LR
    subgraph "开发者终端"
        USER[开发者指令]
    end

    subgraph "Claude Code主会话"
        ORCH[主代理<br/>Orchestrator]
        CM[CLAUDE.md<br/>项目配置]
        ORCH --- CM
    end

    subgraph "Subagent池"
        direction TB
        E1[Explore<br/>Haiku/只读]
        E2[Explore<br/>Haiku/只读]
        GP1[General<br/>Sonnet/全工具]
        GP2[General<br/>Sonnet/全工具]
        CUST[Custom Agent<br/>自定义]
    end

    subgraph "Agent Team"
        direction TB
        TL[Team Lead]
        TM1[Teammate 1]
        TM2[Teammate 2]
        TM1 <-->|Mailbox| TM2
        TL -->|任务分配| TM1
        TL -->|任务分配| TM2
    end

    subgraph "Worktree隔离层"
        direction TB
        WT1[/worktree-a/]
        WT2[/worktree-b/]
        WT3[/worktree-c/]
    end

    USER --> ORCH
    ORCH -->|Task Tool| E1
    ORCH -->|Task Tool| E2
    ORCH -->|Task Tool| GP1
    ORCH -->|Task Tool| GP2
    ORCH -->|Task Tool| CUST

    ORCH -->|Team创建| TL

    GP1 -.->|isolation: worktree| WT1
    GP2 -.->|isolation: worktree| WT2
    CUST -.->|isolation: worktree| WT3

    E1 & E2 & GP1 & GP2 & CUST -.->|结果返回| ORCH

训练营适用性评估

训练营类型 适配度 预计时长 建议安排
Claude Code进阶训练营 极高 4-5小时 Step 1-3为核心,Step 4-5可选
AI辅助开发工作坊 高 3小时 聚焦Subagent模式+Worktree
团队效能提升培训 高 2-3小时 聚焦Agent Team协作模式
DevOps/平台工程培训 中 2小时 聚焦并行流水线+成本优化
零基础入门营 低 — 建议先完成基础教程

实验环境要求: - 每位学员一个独立Git仓库 - 建议使用Max 5x计划(避免API限速影响体验) - 预装tmux(分屏模式演示) - 示例项目建议:中型Next.js全栈应用(包含前端、API、数据库、测试)


参考来源

  1. Run parallel sessions with worktrees - Claude Code Docs — Anthropic官方Worktree文档,完整CLI参考和配置说明
  2. Orchestrate teams of Claude Code sessions - Claude Code Docs — Agent Team官方文档,架构、控制和最佳实践
  3. Create custom subagents - Claude Code Docs — Subagent自定义配置、作用域和内置类型参考
  4. Claude Code Agents In 2026: Views, Subagents, Teams & Costs - CloudZero — 并行Agent成本分析和选型对比
  5. Subagent-Driven Development – Claude Code Skill Guide - Jonathan's Blog — Subagent编排模式和实战案例

[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。

51学通信知识星球海报-扫码加入