关于 orchestrating-swarms
orchestrating-swarms 是面向 Claude Code 的多 Agent 编排技能,介绍 TeammateTool 与 Task 系统的协作方式。它涵盖团队生命周期、任务分配、消息通信以及不同 Agent 类型和启动方式。
主要功能
- 01区分短期子 Agent 与团队成员
- 02创建团队并分配共享任务
- 03通过收件箱消息协调成员
- 04介绍内置及插件 Agent 类型
- 05涵盖团队操作与生命周期
适用场景
- 01将复杂工作拆分给多个 Agent
- 02并行开展持续协作任务
- 03安排代码探索或审查工作
- 04协调团队成员并结束任务
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ everyinc/ compound-engineering-plugin --skill orchestrating-swarms安装后在 Claude Code 中输入/orchestrating-swarms确认已加载。
详细介绍
Claude Code 群体编排
掌握使用 Claude Code 的 TeammateTool 和 Task 系统进行多 Agent 编排。
基础要素
| 基础要素 | 含义 | 文件位置 |
|---|---|---|
| Agent | 可以使用工具的 Claude 实例。你就是一个 Agent。子 Agent 是你启动的 Agent。 | N/A(进程) |
| 团队 | 一组协同工作的命名 Agent。由一名负责人和多名队友组成。 | ~/.claude/teams/{name}/config.json |
| 队友 | 加入团队的 Agent。拥有名称、颜色和收件箱。通过带有 team_name + name 的 Task 启动。 | 列于团队配置中 |
| 负责人 | 创建团队的 Agent。接收队友消息,并批准计划和关闭请求。 | 配置中的第一位成员 |
| 任务 | 包含主题、描述、状态、负责人和依赖项的工作项。 | ~/.claude/tasks/{team}/N.json |
| 收件箱 | Agent 接收队友消息的 JSON 文件。 | ~/.claude/teams/{name}/inboxes/{agent}.json |
| 消息 | Agent 之间传递的 JSON 对象。可以是文本,也可以是结构化内容(shutdown_request、idle_notification 等)。 | 存储在收件箱文件中 |
| 后端 | 队友的运行方式。自动检测:in-process(相同的 Node.js 进程,不可见)、tmux(独立窗格,可见)、iterm2(iTerm2 中的分屏窗格)。参见启动后端。 | 根据环境自动检测 |
它们如何连接
flowchart TB
subgraph TEAM[TEAM]
Leader[Leader - you]
T1[Teammate 1]
T2[Teammate 2]
Leader <-->|messages via inbox| T1
Leader <-->|messages via inbox| T2
T1 <-.->|can message| T2
end
subgraph TASKS[TASK LIST]
Task1["#1 completed: Research<br/>owner: teammate1"]
Task2["#2 in_progress: Implement<br/>owner: teammate2"]
Task3["#3 pending: Test<br/>blocked by #2"]
end
T1 --> Task1
T2 --> Task2
Task2 -.->|unblocks| Task3
生命周期
flowchart LR
A[1. Create Team] --> B[2. Create Tasks]
B --> C[3. Spawn Teammates]
C --> D[4. Work]
D --> E[5. Coordinate]
E --> F[6. Shutdown]
F --> G[7. Cleanup]
消息流
sequenceDiagram
participant L as Leader
participant T1 as Teammate 1
participant T2 as Teammate 2
participant Tasks as Task List
L->>Tasks: TaskCreate (3 tasks)
L->>T1: spawn with prompt
L->>T2: spawn with prompt
T1->>Tasks: claim task #1
T2->>Tasks: claim task #2
T1->>Tasks: complete #1
T1->>L: send findings (inbox)
Note over Tasks: #3 auto-unblocks
T2->>Tasks: complete #2
T2->>L: send findings (inbox)
L->>T1: requestShutdown
T1->>L: approveShutdown
L->>T2: requestShutdown
T2->>L: approveShutdown
L->>L: cleanup
目录
核心架构
群体如何工作
一个群体由以下部分组成:
- 负责人(你)——创建团队、启动工作 Agent、协调工作
- 队友(启动的 Agent)——执行任务并汇报结果
- 任务列表——包含依赖项的共享工作队列
- 收件箱——用于 Agent 间消息传递的 JSON 文件
文件结构
~/.claude/teams/{team-name}/
├── config.json # Team metadata and member list
└── inboxes/
├── team-lead.json # Leader's inbox
├── worker-1.json # Worker 1's inbox
└── worker-2.json # Worker 2's inbox
~/.claude/tasks/{team-name}/
├── 1.json # Task #1
├── 2.json # Task #2
└── 3.json # Task #3
团队配置结构
{
"name": "my-project",
"description": "Working on feature X",
"leadAgentId": "team-lead@my-project",
"createdAt": 1706000000000,
"members": [
{
"agentId": "team-lead@my-project",
"name": "team-lead",
"agentType": "team-lead",
"color": "#4A90D9",
"joinedAt": 1706000000000,
"backendType": "in-process"
},
{
"agentId": "worker-1@my-project",
"name": "worker-1",
"agentType": "Explore",
"model": "haiku",
"prompt": "Analyze the codebase structure...",
"color": "#D94A4A",
"planModeRequired": false,
"joinedAt": 1706000001000,
"tmuxPaneId": "in-process",
"cwd": "/Users/me/project",
"backendType": "in-process"
}
]
}
启动 Agent 的两种方式
方法 1:Task 工具(子 Agent)
对于短期、目标明确且需要返回结果的工作,使用 Task:
Task({
subagent_type: "Explore",
description: "Find auth files",
prompt: "Find all authentication-related files in this codebase",
model: "haiku" // Optional: haiku, sonnet, opus
})
特点:
- 同步运行(阻塞直到完成),或通过
run_in_background: true异步运行 - 直接向你返回结果
- 无需加入团队
- 适用于:搜索、分析、针对性研究
**权限模式:**除非需要 mode: "plan" 之类的特定模式,否则省略 mode 参数。传入 mode: "auto" 会覆盖用户配置的权限设置(例如 bypassPermissions)。省略该参数可让用户自己的 defaultMode 生效。
方法 2:Task 工具 + team_name + name(队友)
使用带有 team_name 和 name 的 Task 来启动持久队友:
// First create a team
Teammate({ operation: "spawnTeam", team_name: "my-project" })
// Then spawn a teammate into that team
Task({
team_name: "my-project", // Required: which team to join
name: "security-reviewer", // Required: teammate's name
subagent_type: "security-sentinel",
prompt: "Review all authentication code for vulnerabilities. Send findings to team-lead via Teammate write.",
run_in_background: true // Teammates usually run in background
})
特点:
- 加入团队,并显示在
config.json中 - 通过收件箱消息进行通信
- 可以从共享任务列表中认领任务
- 持续运行,直到关闭
- 适用于:并行工作、持续协作、流水线阶段
主要区别
| 方面 | Task(子 Agent) | Task + team_name + name(队友) |
|---|---|---|
| 生命周期 | 直到任务完成 | 直到收到关闭请求 |
| 通信方式 | 返回值 | 收件箱消息 |
| 任务访问 | 无 | 共享任务列表 |
| 团队成员身份 | 否 | 是 |
| 协调方式 | 一次性 | 持续进行 |
内置 Agent 类型
这些类型始终可用,无需安装插件:
Bash
Task({
subagent_type: "Bash",
description: "Run git commands",
prompt: "Check git status and show recent commits"
})
- 工具: 仅 Bash
- 模型: 继承自父级
- 最适合: Git 操作、命令执行、系统任务
Explore
Task({
subagent_type: "Explore",
description: "Find API endpoints",
prompt: "Find all API endpoints in this codebase. Be very thorough.",
model: "haiku" // Fast and cheap
})
- 工具: 所有只读工具(不包括 Edit、Write、NotebookEdit、Task)
- 模型: Haiku(针对速度进行了优化)
- 最适合: 代码库探索、文件搜索、理解代码
- 深入程度: “quick”、“medium”、“very thorough”
Plan
Task({
subagent_type: "Plan",
description: "Design auth system",
prompt: "Create an implementation plan for adding OAuth2 authentication"
})
- 工具: 所有只读工具
- 模型: 继承自父级
- 最适合: 架构规划、实施策略
general-purpose
Task({
subagent_type: "general-purpose",
description: "Research and implement",
prompt: "Research React Query best practices and implement caching for the user API"
})
- 工具: 所有工具(*)
- 模型: 继承自父级
- 最适合: 多步骤任务、研究与行动的组合
claude-code-guide
Task({
subagent_type: "claude-code-guide",
description: "Help with Claude Code",
prompt: "How do I configure MCP servers?"
})
- 工具: 只读工具 + WebFetch + WebSearch
- 最适合: 关于 Claude Code、Agent SDK、Anthropic API 的问题
statusline-setup
Task({
subagent_type: "statusline-setup",
description: "Configure status line",
prompt: "Set up a status line showing git branch and node version"
})
- 工具: 仅 Read、Edit
- 模型: Sonnet
- 最适合: 配置 Claude Code 状态行
插件 Agent 类型
来自 compound-engineering 插件(示例):
Review Agent
// Security review
Task({
subagent_type: "compound-engineering:review:security-sentinel",
description: "Security audit",
prompt: "Audit this PR for security vulnerabilities"
})
// Performance review
Task({
subagent_type: "compound-engineering:review:performance-oracle",
description: "Performance check",
prompt: "Analyze this code for performance bottlenecks"
})
// Rails code review
Task({
subagent_type: "compound-engineering:review:kieran-rails-reviewer",
description: "Rails review",
prompt: "Review this Rails code for best practices"
})
// Architecture review
Task({
subagent_type: "compound-engineering:review:architecture-strategist",
description: "Architecture review",
prompt: "Review the system architecture of the authentication module"
})
// Code simplicity
Task({
subagent_type: "compound-engineering:review:code-simplicity-reviewer",
description: "Simplicity check",
prompt: "Check if this implementation can be simplified"
})
compound-engineering 中的所有 Review Agent:
agent-native-reviewer- 确保功能也能为 Agent 使用architecture-strategist- 架构合规性code-simplicity-reviewer- YAGNI 原则与极简主义data-integrity-guardian- 数据库与数据安全data-migration-expert- 迁移验证deployment-verification-agent- 部署前检查清单dhh-rails-reviewer- DHH/37signals Rails 风格julik-frontend-races-reviewer- JavaScript 竞态条件kieran-python-reviewer- Python 最佳实践kieran-rails-reviewer- Rails 最佳实践kieran-typescript-reviewer- TypeScript 最佳实践pattern-recognition-specialist- 设计模式与反模式performance-oracle- 性能分析security-sentinel- 安全漏洞
Research Agent
// Best practices research
Task({
subagent_type: "compound-engineering:research:best-practices-researcher",
description: "Research auth best practices",
prompt: "Research current best practices for JWT authentication in Rails 2024-2026"
})
// Framework documentation
Task({
subagent_type: "compound-engineering:research:framework-docs-researcher",
description: "Research Active Storage",
prompt: "Gather comprehensive documentation about Active Storage file uploads"
})
// Git history analysis
Task({
subagent_type: "compound-engineering:research:git-history-analyzer",
description: "Analyze auth history",
prompt: "Analyze the git history of the authentication module to understand its evolution"
})
所有 Research Agent:
best-practices-researcher- 外部最佳实践framework-docs-researcher- 框架文档git-history-analyzer- 代码考古learnings-researcher- 搜索 docs/solutions/repo-research-analyst- 仓库模式
Design Agent
Task({
subagent_type: "compound-engineering:design:figma-design-sync",
description: "Sync with Figma",
prompt: "Compare implementation with Figma design at [URL]"
})
Workflow Agent
Task({
subagent_type: "compound-engineering:workflow:bug-reproduction-validator",
description: "Validate bug",
prompt: "Reproduce and validate this reported bug: [description]"
})
TeammateTool 操作
1. spawnTeam - 创建团队
Teammate({
operation: "spawnTeam",
team_name: "feature-auth",
description: "Implementing OAuth2 authentication"
})
创建:
~/.claude/teams/feature-auth/config.json~/.claude/tasks/feature-auth/目录- 你将成为团队负责人
2. discoverTeams - 列出可用团队
Teammate({ operation: "discoverTeams" })
返回: 你可以加入的团队列表(不包括你已加入的团队)
3. requestJoin - 请求加入团队
Teammate({
operation: "requestJoin",
team_name: "feature-auth",
proposed_name: "helper",
capabilities: "I can help with code review and testing"
})
4. approveJoin - 接受加入请求(仅限负责人)
收到 join_request 消息时:
{"type": "join_request", "proposedName": "helper", "requestId": "join-123", ...}
批准请求:
Teammate({
operation: "approveJoin",
target_agent_id: "helper",
request_id: "join-123"
})
5. rejectJoin - 拒绝加入请求(仅限负责人)
Teammate({
operation: "rejectJoin",
target_agent_id: "helper",
request_id: "join-123",
reason: "Team is at capacity"
})
6. write - 向一名队友发送消息
Teammate({
operation: "write",
target_agent_id: "security-reviewer",
value: "Please prioritize the authentication module. The deadline is tomorrow."
})
队友请注意: 你的文本输出对团队不可见。你必须使用 write 进行沟通。
7. broadcast - 向所有队友发送消息
Teammate({
operation: "broadcast",
name: "team-lead", // Your name
value: "Status check: Please report your progress"
})
警告: 广播开销很大——有 N 名队友时会分别发送 N 条消息。请优先使用 write 向特定队友发送消息。
适合广播的情况:
- 需要立即关注的关键问题
- 影响所有人的重要公告
不适合广播的情况:
- 回复一名队友
- 普通的来回交流
- 仅与部分队友相关的信息
8. requestShutdown - 请求队友退出(仅限负责人)
Teammate({
operation: "requestShutdown",
target_agent_id: "security-reviewer",
reason: "All tasks complete, wrapping up"
})
9. approveShutdown - 接受关闭请求(仅限队友)
收到 shutdown_request 消息时:
{"type": "shutdown_request", "requestId": "shutdown-123", "from": "team-lead", "reason": "Done"}
必须调用:
Teammate({
operation: "approveShutdown",
request_id: "shutdown-123"
})
此操作会发送确认并终止你的进程。
10. rejectShutdown - 拒绝关闭请求(仅限队友)
Teammate({
operation: "rejectShutdown",
request_id: "shutdown-123",
reason: "Still working on task #3, need 5 more minutes"
})
11. approvePlan - 批准队友的计划(仅限负责人)
当启用了 plan_mode_required 的队友发送计划时:
{"type": "plan_approval_request", "from": "architect", "requestId": "plan-456", ...}
批准:
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-456"
})
12. rejectPlan - 拒绝计划并提供反馈(仅限 Leader)
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-456",
feedback: "Please add error handling for the API calls and consider rate limiting"
})
13. cleanup - 移除团队资源
Teammate({ operation: "cleanup" })
移除:
~/.claude/teams/{team-name}/目录~/.claude/tasks/{team-name}/目录
重要: 如果队友仍处于活动状态,此操作会失败。请先使用 requestShutdown。
任务系统集成
TaskCreate - 创建工作项
TaskCreate({
subject: "Review authentication module",
description: "Review all files in app/services/auth/ for security vulnerabilities",
activeForm: "Reviewing auth module..." // Shown in spinner when in_progress
})
TaskList - 查看所有任务
TaskList()
返回:
#1 [completed] Analyze codebase structure
#2 [in_progress] Review authentication module (owner: security-reviewer)
#3 [pending] Generate summary report [blocked by #2]
TaskGet - 获取任务详情
TaskGet({ taskId: "2" })
返回包含描述、状态、blockedBy 等信息的完整任务。
TaskUpdate - 更新任务状态
// Claim a task
TaskUpdate({ taskId: "2", owner: "security-reviewer" })
// Start working
TaskUpdate({ taskId: "2", status: "in_progress" })
// Mark complete
TaskUpdate({ taskId: "2", status: "completed" })
// Set up dependencies
TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] })
任务依赖关系
当阻塞任务完成后,被阻塞的任务会自动解除阻塞:
// Create pipeline
TaskCreate({ subject: "Step 1: Research" }) // #1
TaskCreate({ subject: "Step 2: Implement" }) // #2
TaskCreate({ subject: "Step 3: Test" }) // #3
TaskCreate({ subject: "Step 4: Deploy" }) // #4
// Set up dependencies
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) // #2 waits for #1
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] }) // #3 waits for #2
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] }) // #4 waits for #3
// When #1 completes, #2 auto-unblocks
// When #2 completes, #3 auto-unblocks
// etc.
任务文件结构
~/.claude/tasks/{team-name}/1.json:
{
"id": "1",
"subject": "Review authentication module",
"description": "Review all files in app/services/auth/...",
"status": "in_progress",
"owner": "security-reviewer",
"activeForm": "Reviewing auth module...",
"blockedBy": [],
"blocks": ["3"],
"createdAt": 1706000000000,
"updatedAt": 1706000001000
}
消息格式
普通消息
{
"from": "team-lead",
"text": "Please prioritize the auth module",
"timestamp": "2026-01-25T23:38:32.588Z",
"read": false
}
结构化消息(文本字段中的 JSON)
关闭请求
{
"type": "shutdown_request",
"requestId": "shutdown-abc123@worker-1",
"from": "team-lead",
"reason": "All tasks complete",
"timestamp": "2026-01-25T23:38:32.588Z"
}
已批准关闭
{
"type": "shutdown_approved",
"requestId": "shutdown-abc123@worker-1",
"from": "worker-1",
"paneId": "%5",
"backendType": "in-process",
"timestamp": "2026-01-25T23:39:00.000Z"
}
空闲通知(队友停止时自动发送)
{
"type": "idle_notification",
"from": "worker-1",
"timestamp": "2026-01-25T23:40:00.000Z",
"completedTaskId": "2",
"completedStatus": "completed"
}
任务已完成
{
"type": "task_completed",
"from": "worker-1",
"taskId": "2",
"taskSubject": "Review authentication module",
"timestamp": "2026-01-25T23:40:00.000Z"
}
计划审批请求
{
"type": "plan_approval_request",
"from": "architect",
"requestId": "plan-xyz789",
"planContent": "# Implementation Plan\n\n1. ...",
"timestamp": "2026-01-25T23:41:00.000Z"
}
加入请求
{
"type": "join_request",
"proposedName": "helper",
"requestId": "join-abc123",
"capabilities": "Code review and testing",
"timestamp": "2026-01-25T23:42:00.000Z"
}
权限请求(针对沙箱/工具权限)
{
"type": "permission_request",
"requestId": "perm-123",
"workerId": "worker-1@my-project",
"workerName": "worker-1",
"workerColor": "#4A90D9",
"toolName": "Bash",
"toolUseId": "toolu_abc123",
"description": "Run npm install",
"input": {"command": "npm install"},
"permissionSuggestions": ["Bash(npm *)"],
"createdAt": 1706000000000
}
编排模式
模式 1:并行专家(Leader 模式)
多位专家同时审查代码:
// 1. Create team
Teammate({ operation: "spawnTeam", team_name: "code-review" })
// 2. Spawn specialists in parallel (single message, multiple Task calls)
Task({
team_name: "code-review",
name: "security",
subagent_type: "compound-engineering:review:security-sentinel",
prompt: "Review the PR for security vulnerabilities. Focus on: SQL injection, XSS, auth bypass. Send findings to team-lead.",
run_in_background: true
})
Task({
team_name: "code-review",
name: "performance",
subagent_type: "compound-engineering:review:performance-oracle",
prompt: "Review the PR for performance issues. Focus on: N+1 queries, memory leaks, slow algorithms. Send findings to team-lead.",
run_in_background: true
})
Task({
team_name: "code-review",
name: "simplicity",
subagent_type: "compound-engineering:review:code-simplicity-reviewer",
prompt: "Review the PR for unnecessary complexity. Focus on: over-engineering, premature abstraction, YAGNI violations. Send findings to team-lead.",
run_in_background: true
})
// 3. Wait for results (check inbox)
// cat ~/.claude/teams/code-review/inboxes/team-lead.json
// 4. Synthesize findings and cleanup
Teammate({ operation: "requestShutdown", target_agent_id: "security" })
Teammate({ operation: "requestShutdown", target_agent_id: "performance" })
Teammate({ operation: "requestShutdown", target_agent_id: "simplicity" })
// Wait for approvals...
Teammate({ operation: "cleanup" })
模式 2:流水线(顺序依赖)
每个阶段都依赖于前一阶段:
// 1. Create team and task pipeline
Teammate({ operation: "spawnTeam", team_name: "feature-pipeline" })
TaskCreate({ subject: "Research", description: "Research best practices for the feature", activeForm: "Researching..." })
TaskCreate({ subject: "Plan", description: "Create implementation plan based on research", activeForm: "Planning..." })
TaskCreate({ subject: "Implement", description: "Implement the feature according to plan", activeForm: "Implementing..." })
TaskCreate({ subject: "Test", description: "Write and run tests for the implementation", activeForm: "Testing..." })
TaskCreate({ subject: "Review", description: "Final code review before merge", activeForm: "Reviewing..." })
// Set up sequential dependencies
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] })
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] })
TaskUpdate({ taskId: "5", addBlockedBy: ["4"] })
// 2. Spawn workers that claim and complete tasks
Task({
team_name: "feature-pipeline",
name: "researcher",
subagent_type: "compound-engineering:research:best-practices-researcher",
prompt: "Claim task #1, research best practices, complete it, send findings to team-lead. Then check for more work.",
run_in_background: true
})
Task({
team_name: "feature-pipeline",
name: "implementer",
subagent_type: "general-purpose",
prompt: "Poll TaskList every 30 seconds. When task #3 unblocks, claim it and implement. Then complete and notify team-lead.",
run_in_background: true
})
// Tasks auto-unblock as dependencies complete
模式 3:群体(自组织)
工作者从任务池中领取可用任务:
// 1. Create team and task pool
Teammate({ operation: "spawnTeam", team_name: "file-review-swarm" })
// Create many independent tasks (no dependencies)
for (const file of ["auth.rb", "user.rb", "api_controller.rb", "payment.rb"]) {
TaskCreate({
subject: `Review ${file}`,
description: `Review ${file} for security and code quality issues`,
activeForm: `Reviewing ${file}...`
})
}
// 2. Spawn worker swarm
Task({
team_name: "file-review-swarm",
name: "worker-1",
subagent_type: "general-purpose",
prompt: `
You are a swarm worker. Your job:
1. Call TaskList to see available tasks
2. Find a task with status 'pending' and no owner
3. Claim it with TaskUpdate (set owner to your name)
4. Do the work
5. Mark it completed with TaskUpdate
6. Send findings to team-lead via Teammate write
7. Repeat until no tasks remain
`,
run_in_background: true
})
Task({
team_name: "file-review-swarm",
name: "worker-2",
subagent_type: "general-purpose",
prompt: `[Same prompt as worker-1]`,
run_in_background: true
})
Task({
team_name: "file-review-swarm",
name: "worker-3",
subagent_type: "general-purpose",
prompt: `[Same prompt as worker-1]`,
run_in_background: true
})
// Workers race to claim tasks, naturally load-balance
模式 4:研究 + 实现
先研究,再实现:
// 1. Research phase (synchronous, returns results)
const research = await Task({
subagent_type: "compound-engineering:research:best-practices-researcher",
description: "Research caching patterns",
prompt: "Research best practices for implementing caching in Rails APIs. Include: cache invalidation strategies, Redis vs Memcached, cache key design."
})
// 2. Use research to guide implementation
Task({
subagent_type: "general-purpose",
description: "Implement caching",
prompt: `
Implement API caching based on this research:
${research.content}
Focus on the user_controller.rb endpoints.
`
})
模式 5:计划审批工作流
实现前要求审批计划:
// 1. Create team
Teammate({ operation: "spawnTeam", team_name: "careful-work" })
// 2. Spawn architect with plan_mode_required
Task({
team_name: "careful-work",
name: "architect",
subagent_type: "Plan",
prompt: "Design an implementation plan for adding OAuth2 authentication",
mode: "plan", // Requires plan approval
run_in_background: true
})
// 3. Wait for plan approval request
// You'll receive: {"type": "plan_approval_request", "from": "architect", "requestId": "plan-xxx", ...}
// 4. Review and approve/reject
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-xxx"
})
// OR
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-xxx",
feedback: "Please add rate limiting considerations"
})
模式 6:协调式多文件重构
// 1. Create team for coordinated refactoring
Teammate({ operation: "spawnTeam", team_name: "refactor-auth" })
// 2. Create tasks with clear file boundaries
TaskCreate({
subject: "Refactor User model",
description: "Extract authentication methods to AuthenticatableUser concern",
activeForm: "Refactoring User model..."
})
TaskCreate({
subject: "Refactor Session controller",
description: "Update to use new AuthenticatableUser concern",
activeForm: "Refactoring Sessions..."
})
TaskCreate({
subject: "Update specs",
description: "Update all authentication specs for new structure",
activeForm: "Updating specs..."
})
// Dependencies: specs depend on both refactors completing
TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] })
// 3. Spawn workers for each task
Task({
team_name: "refactor-auth",
name: "model-worker",
subagent_type: "general-purpose",
prompt: "Claim task #1, refactor the User model, complete when done",
run_in_background: true
})
Task({
team_name: "refactor-auth",
name: "controller-worker",
subagent_type: "general-purpose",
prompt: "Claim task #2, refactor the Session controller, complete when done",
run_in_background: true
})
Task({
team_name: "refactor-auth",
name: "spec-worker",
subagent_type: "general-purpose",
prompt: "Wait for task #3 to unblock (when #1 and #2 complete), then update specs",
run_in_background: true
})
环境变量
生成的队友会自动获得这些变量:
CLAUDE_CODE_TEAM_NAME="my-project"
CLAUDE_CODE_AGENT_ID="worker-1@my-project"
CLAUDE_CODE_AGENT_NAME="worker-1"
CLAUDE_CODE_AGENT_TYPE="Explore"
CLAUDE_CODE_AGENT_COLOR="#4A90D9"
CLAUDE_CODE_PLAN_MODE_REQUIRED="false"
CLAUDE_CODE_PARENT_SESSION_ID="session-xyz"
在提示词中使用:
Task({
team_name: "my-project",
name: "worker",
subagent_type: "general-purpose",
prompt: "Your name is $CLAUDE_CODE_AGENT_NAME. Use it when sending messages to team-lead."
})
生成后端
后端决定队友 Claude 实例的实际运行方式。Claude Code 支持三种后端,并会根据你的环境自动检测最佳选项。
后端比较
| 后端 | 工作方式 | 可见性 | 持久性 | 速度 |
|---|---|---|---|---|
| in-process | 与 Leader 位于同一 Node.js 进程 | 隐藏(后台) | 随 Leader 退出而终止 | 最快 |
| tmux | 在 tmux 会话中的独立终端运行 | 在 tmux 中可见 | Leader 退出后仍会运行 | 中等 |
| iterm2 | 在 iTerm2 窗口中拆分窗格 | 并排可见 | 随窗口关闭而终止 | 中等 |
自动检测逻辑
Claude Code 会根据以下决策树自动选择后端:
flowchart TD
A[Start] --> B{Running inside tmux?}
B -->|Yes| C[Use tmux backend]
B -->|No| D{Running in iTerm2?}
D -->|No| E{tmux available?}
E -->|Yes| F[Use tmux - external session]
E -->|No| G[Use in-process]
D -->|Yes| H{it2 CLI installed?}
H -->|Yes| I[Use iterm2 backend]
H -->|No| J{tmux available?}
J -->|Yes| K[Use tmux - prompt to install it2]
J -->|No| L[Error: Install tmux or it2]
检测项:
$TMUX环境变量 → 位于 tmux 中$TERM_PROGRAM === "iTerm.app"或$ITERM_SESSION_ID→ 位于 iTerm2 中which tmux→ tmux 可用which it2→ 已安装 it2 CLI
in-process(非 tmux 环境下的默认选项)
队友作为异步任务在同一 Node.js 进程中运行。
工作方式:
- 不会启动新进程
- 队友共享同一个 Node.js 事件循环
- 通过内存队列通信(速度快)
- 你无法直接看到队友的输出
使用场景:
- 未在 tmux 会话中运行
- 非交互模式(CI、脚本)
- 通过
CLAUDE_CODE_SPAWN_BACKEND=in-process显式设置
特性:
┌─────────────────────────────────────────┐
│ Node.js Process │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Leader │ │Worker 1 │ │Worker 2 │ │
│ │ (main) │ │ (async) │ │ (async) │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────┘
优点:
- 启动最快(无需启动进程)
- 开销最低
- 适用于所有环境
缺点:
- 无法实时查看队友的输出
- Leader 退出时所有队友都会终止
- 调试更困难
// in-process is automatic when not in tmux
Task({
team_name: "my-project",
name: "worker",
subagent_type: "general-purpose",
prompt: "...",
run_in_background: true
})
// Force in-process explicitly
// export CLAUDE_CODE_SPAWN_BACKEND=in-process
tmux
队友以独立的 Claude 实例运行在 tmux 窗格/窗口中。
工作原理:
- 每个队友都有自己的 tmux 窗格
- 每个队友都是独立进程
- 你可以切换窗格查看队友的输出
- 通过收件箱文件进行通信
使用条件:
- 在 tmux 会话中运行(已设置
$TMUX) - tmux 可用,且不在 iTerm2 中
- 通过
CLAUDE_CODE_SPAWN_BACKEND=tmux显式设置
布局模式:
- **在 tmux 中(原生):**拆分当前窗口
┌─────────────────┬─────────────────┐
│ │ Worker 1 │
│ Leader ├─────────────────┤
│ (your pane) │ Worker 2 │
│ ├─────────────────┤
│ │ Worker 3 │
└─────────────────┴─────────────────┘
- **在 tmux 外(外部会话):**创建名为
claude-swarm的新 tmux 会话
# Your terminal stays as-is
# Workers run in separate tmux session
# View workers:
tmux attach -t claude-swarm
优点:
- 实时查看队友的输出
- 即使领导者退出,队友仍会继续运行
- 可以连接和分离会话
- 适用于 CI/无头环境
缺点:
- 启动较慢(生成进程)
- 需要安装 tmux
- 资源占用更多
# Start tmux session first
tmux new-session -s claude
# Or force tmux backend
export CLAUDE_CODE_SPAWN_BACKEND=tmux
实用的 tmux 命令:
# List all panes in current window
tmux list-panes
# Switch to pane by number
tmux select-pane -t 1
# Kill a specific pane
tmux kill-pane -t %5
# View swarm session (if external)
tmux attach -t claude-swarm
# Rebalance pane layout
tmux select-layout tiled
iterm2(仅限 macOS)
队友以分屏窗格的形式运行在你的 iTerm2 窗口中。
工作原理:
- 通过
it2CLI 使用 iTerm2 的 Python API - 将当前窗口拆分为多个窗格
- 每个队友并排显示
- 通过收件箱文件进行通信
使用条件:
- 在 iTerm2 中运行(
$TERM_PROGRAM === "iTerm.app") - 已安装且可正常使用
it2CLI - 已在 iTerm2 偏好设置中启用 Python API
布局:
┌─────────────────┬─────────────────┐
│ │ Worker 1 │
│ Leader ├─────────────────┤
│ (your pane) │ Worker 2 │
│ ├─────────────────┤
│ │ Worker 3 │
└─────────────────┴─────────────────┘
优点:
- 可视化调试——查看所有队友
- 原生 macOS 体验
- 无需 tmux
- 自动管理窗格
缺点:
- 仅限 macOS + iTerm2
- 需要进行设置(it2 CLI + Python API)
- 窗口关闭时窗格也会退出
设置:
# 1. Install it2 CLI
uv tool install it2
# OR
pipx install it2
# OR
pip install --user it2
# 2. Enable Python API in iTerm2
# iTerm2 → Settings → General → Magic → Enable Python API
# 3. Restart iTerm2
# 4. Verify
it2 --version
it2 session list
如果设置失败: 首次生成队友时,Claude Code 会提示你设置 it2。你可以选择:
- 立即安装 it2(引导式设置)
- 改用 tmux
- 取消
强制指定后端
# Force in-process (fastest, no visibility)
export CLAUDE_CODE_SPAWN_BACKEND=in-process
# Force tmux (visible panes, persistent)
export CLAUDE_CODE_SPAWN_BACKEND=tmux
# Auto-detect (default)
unset CLAUDE_CODE_SPAWN_BACKEND
团队配置中的后端
后端类型会按队友记录在 config.json 中:
{
"members": [
{
"name": "worker-1",
"backendType": "in-process",
"tmuxPaneId": "in-process"
},
{
"name": "worker-2",
"backendType": "tmux",
"tmuxPaneId": "%5"
}
]
}
后端故障排除
| 问题 | 原因 | 解决方案 |
|---|---|---|
| "No pane backend available" | tmux 和 iTerm2 均不可用 | 安装 tmux:brew install tmux |
| "it2 CLI not installed" | 在 iTerm2 中运行,但缺少 it2 | 运行 uv tool install it2 |
| "Python API not enabled" | it2 无法与 iTerm2 通信 | 在 iTerm2 Settings → General → Magic 中启用 |
| Worker 不可见 | 正在使用进程内后端 | 在 tmux 或 iTerm2 中启动 |
| Worker 意外退出 | 在 tmux 外运行,且领导者已退出 | 使用 tmux 以保持进程运行 |
检查当前后端
# See what backend was detected
cat ~/.claude/teams/{team}/config.json | jq '.members[].backendType'
# Check if inside tmux
echo $TMUX
# Check if in iTerm2
echo $TERM_PROGRAM
# Check tmux availability
which tmux
# Check it2 availability
which it2
错误处理
常见错误
| 错误 | 原因 | 解决方案 |
|---|---|---|
| "Cannot cleanup with active members" | 队友仍在运行 | 先对所有队友调用 requestShutdown,并等待批准 |
| "Already leading a team" | 团队已存在 | 先调用 cleanup,或使用其他团队名称 |
| "Agent not found" | 队友名称错误 | 检查 config.json 中的实际名称 |
| "Team does not exist" | 尚未创建团队 | 先调用 spawnTeam |
| "team_name is required" | 缺少团队上下文 | 提供 team_name 参数 |
| "Agent type not found" | subagent_type 无效 | 使用正确前缀检查可用的 Agent |
正常关闭流程
始终按以下顺序操作:
// 1. Request shutdown for all teammates
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
Teammate({ operation: "requestShutdown", target_agent_id: "worker-2" })
// 2. Wait for shutdown approvals
// Check for {"type": "shutdown_approved", ...} messages
// 3. Verify no active members
// Read ~/.claude/teams/{team}/config.json
// 4. Only then cleanup
Teammate({ operation: "cleanup" })
处理崩溃的队友
队友的心跳超时时间为 5 分钟。如果队友崩溃:
- 超时后会自动标记为非活动状态
- 其任务仍会保留在任务列表中
- 其他队友可以认领这些任务
- 超时后即可执行清理
调试
# Check team config
cat ~/.claude/teams/{team}/config.json | jq '.members[] | {name, agentType, backendType}'
# Check teammate inboxes
cat ~/.claude/teams/{team}/inboxes/{agent}.json | jq '.'
# List all teams
ls ~/.claude/teams/
# Check task states
cat ~/.claude/tasks/{team}/*.json | jq '{id, subject, status, owner, blockedBy}'
# Watch for new messages
tail -f ~/.claude/teams/{team}/inboxes/team-lead.json
完整工作流
工作流 1:由并行专家完成的完整代码审查
// === STEP 1: Setup ===
Teammate({ operation: "spawnTeam", team_name: "pr-review-123", description: "Reviewing PR #123" })
// === STEP 2: Spawn reviewers in parallel ===
// (Send all these in a single message for parallel execution)
Task({
team_name: "pr-review-123",
name: "security",
subagent_type: "compound-engineering:review:security-sentinel",
prompt: `Review PR #123 for security vulnerabilities.
Focus on:
- SQL injection
- XSS vulnerabilities
- Authentication/authorization bypass
- Sensitive data exposure
When done, send your findings to team-lead using:
Teammate({ operation: "write", target_agent_id: "team-lead", value: "Your findings here" })`,
run_in_background: true
})
Task({
team_name: "pr-review-123",
name: "perf",
subagent_type: "compound-engineering:review:performance-oracle",
prompt: `Review PR #123 for performance issues.
Focus on:
- N+1 queries
- Missing indexes
- Memory leaks
- Inefficient algorithms
Send findings to team-lead when done.`,
run_in_background: true
})
Task({
team_name: "pr-review-123",
name: "arch",
subagent_type: "compound-engineering:review:architecture-strategist",
prompt: `Review PR #123 for architectural concerns.
Focus on:
- Design pattern adherence
- SOLID principles
- Separation of concerns
- Testability
Send findings to team-lead when done.`,
run_in_background: true
})
// === STEP 3: Monitor and collect results ===
// Poll inbox or wait for idle notifications
// cat ~/.claude/teams/pr-review-123/inboxes/team-lead.json
// === STEP 4: Synthesize findings ===
// Combine all reviewer findings into a cohesive report
// === STEP 5: Cleanup ===
Teammate({ operation: "requestShutdown", target_agent_id: "security" })
Teammate({ operation: "requestShutdown", target_agent_id: "perf" })
Teammate({ operation: "requestShutdown", target_agent_id: "arch" })
// Wait for approvals...
Teammate({ operation: "cleanup" })
工作流 2:研究 → 计划 → 实现 → 测试流水线
// === SETUP ===
Teammate({ operation: "spawnTeam", team_name: "feature-oauth" })
// === CREATE PIPELINE ===
TaskCreate({ subject: "Research OAuth providers", description: "Research OAuth2 best practices and compare providers (Google, GitHub, Auth0)", activeForm: "Researching OAuth..." })
TaskCreate({ subject: "Create implementation plan", description: "Design OAuth implementation based on research findings", activeForm: "Planning..." })
TaskCreate({ subject: "Implement OAuth", description: "Implement OAuth2 authentication according to plan", activeForm: "Implementing OAuth..." })
TaskCreate({ subject: "Write tests", description: "Write comprehensive tests for OAuth implementation", activeForm: "Writing tests..." })
TaskCreate({ subject: "Final review", description: "Review complete implementation for security and quality", activeForm: "Final review..." })
// Set dependencies
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] })
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] })
TaskUpdate({ taskId: "5", addBlockedBy: ["4"] })
// === SPAWN SPECIALIZED WORKERS ===
Task({
team_name: "feature-oauth",
name: "researcher",
subagent_type: "compound-engineering:research:best-practices-researcher",
prompt: "Claim task #1. Research OAuth2 best practices, compare providers, document findings. Mark task complete and send summary to team-lead.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "planner",
subagent_type: "Plan",
prompt: "Wait for task #2 to unblock. Read research from task #1. Create detailed implementation plan. Mark complete and send plan to team-lead.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "implementer",
subagent_type: "general-purpose",
prompt: "Wait for task #3 to unblock. Read plan from task #2. Implement OAuth2 authentication. Mark complete when done.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "tester",
subagent_type: "general-purpose",
prompt: "Wait for task #4 to unblock. Write comprehensive tests for the OAuth implementation. Run tests. Mark complete with results.",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "reviewer",
subagent_type: "compound-engineering:review:security-sentinel",
prompt: "Wait for task #5 to unblock. Review the complete OAuth implementation for security. Send final assessment to team-lead.",
run_in_background: true
})
// Pipeline auto-progresses as each stage completes
工作流 3:自组织代码审查集群
// === SETUP ===
Teammate({ operation: "spawnTeam", team_name: "codebase-review" })
// === CREATE TASK POOL (all independent, no dependencies) ===
const filesToReview = [
"app/models/user.rb",
"app/models/payment.rb",
"app/controllers/api/v1/users_controller.rb",
"app/controllers/api/v1/payments_controller.rb",
"app/services/payment_processor.rb",
"app/services/notification_service.rb",
"lib/encryption_helper.rb"
]
for (const file of filesToReview) {
TaskCreate({
subject: `Review ${file}`,
description: `Review ${file} for security vulnerabilities, code quality, and performance issues`,
activeForm: `Reviewing ${file}...`
})
}
// === SPAWN WORKER SWARM ===
const swarmPrompt = `
You are a swarm worker. Your job is to continuously process available tasks.
LOOP:
1. Call TaskList() to see available tasks
2. Find a task that is:
- status: 'pending'
- no owner
- not blocked
3. If found:
- Claim it: TaskUpdate({ taskId: "X", owner: "YOUR_NAME" })
- Start it: TaskUpdate({ taskId: "X", status: "in_progress" })
- Do the review work
- Complete it: TaskUpdate({ taskId: "X", status: "completed" })
- Send findings to team-lead via Teammate write
- Go back to step 1
4. If no tasks available:
- Send idle notification to team-lead
- Wait 30 seconds
- Try again (up to 3 times)
- If still no tasks, exit
Replace YOUR_NAME with your actual agent name from $CLAUDE_CODE_AGENT_NAME.
`
// Spawn 3 workers
Task({ team_name: "codebase-review", name: "worker-1", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true })
Task({ team_name: "codebase-review", name: "worker-2", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true })
Task({ team_name: "codebase-review", name: "worker-3", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true })
// Workers self-organize: race to claim tasks, naturally load-balance
// Monitor progress with TaskList() or by reading inbox
最佳实践
1. 始终清理
不要留下孤立的团队。完成后务必调用 cleanup。
2. 使用有意义的名称
// Good
name: "security-reviewer"
name: "oauth-implementer"
name: "test-writer"
// Bad
name: "worker-1"
name: "agent-2"
3. 编写清晰的提示词
明确告诉 Worker 要做什么:
// Good
prompt: `
1. Review app/models/user.rb for N+1 queries
2. Check all ActiveRecord associations have proper includes
3. Document any issues found
4. Send findings to team-lead via Teammate write
`
// Bad
prompt: "Review the code"
4. 使用任务依赖关系
让系统管理解除阻塞:
// Good: Auto-unblocking
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
// Bad: Manual polling
"Wait until task #1 is done, check every 30 seconds..."
5. 检查收件箱中的结果
工作者会将结果发送到你的收件箱。请检查:
cat ~/.claude/teams/{team}/inboxes/team-lead.json | jq '.'
6. 处理工作者故障
- 工作者的心跳超时为 5 分钟
- 崩溃工作者的任务可以被重新认领
- 在工作者提示词中加入重试逻辑
7. 优先使用 write,而非 broadcast
broadcast 会为 N 位队友发送 N 条消息。使用 write 进行定向通信。
8. 根据任务匹配 Agent 类型
- Explore 用于搜索/阅读
- Plan 用于架构设计
- general-purpose 用于实现
- Specialized reviewers 用于特定类型的审查
快速参考
启动子 Agent(无团队)
Task({ subagent_type: "Explore", description: "Find files", prompt: "..." })
启动队友(有团队)
Teammate({ operation: "spawnTeam", team_name: "my-team" })
Task({ team_name: "my-team", name: "worker", subagent_type: "general-purpose", prompt: "...", run_in_background: true })
向队友发送消息
Teammate({ operation: "write", target_agent_id: "worker-1", value: "..." })
创建任务流水线
TaskCreate({ subject: "Step 1", description: "..." })
TaskCreate({ subject: "Step 2", description: "..." })
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
关闭团队
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
// Wait for approval...
Teammate({ operation: "cleanup" })
基于 Claude Code v2.1.19 - 已于 2026-01-25 测试并验证