orchestrating-swarms
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Code Swarm Orchestration
Claude Code 多智能体集群编排
Master multi-agent orchestration using Claude Code's TeammateTool and Task system.
掌握使用Claude Code的TeammateTool和Task系统进行多智能体编排的方法。
Primitives
核心组件
| Primitive | What It Is | File Location |
|---|---|---|
| Agent | A Claude instance that can use tools. You are an agent. Subagents are agents you spawn. | N/A (process) |
| Team | A named group of agents working together. One leader, multiple teammates. | |
| Teammate | An agent that joined a team. Has a name, color, inbox. Spawned via Task with | Listed in team config |
| Leader | The agent that created the team. Receives teammate messages, approves plans/shutdowns. | First member in config |
| Task | A work item with subject, description, status, owner, and dependencies. | |
| Inbox | JSON file where an agent receives messages from teammates. | |
| Message | A JSON object sent between agents. Can be text or structured (shutdown_request, idle_notification, etc). | Stored in inbox files |
| Backend | How teammates run. Auto-detected: | Auto-detected based on environment |
| 组件 | 说明 | 文件位置 |
|---|---|---|
| Agent | 可使用工具的Claude实例。你本身就是一个Agent,子Agent是你生成的Agent。 | N/A (进程内) |
| Team | 协同工作的Agent命名组。包含一个Leader和多个Teammate。 | |
| Teammate | 加入Team的Agent,拥有名称、颜色和收件箱。通过带 | 列在团队配置文件中 |
| Leader | 创建Team的Agent,接收Teammate的消息,批准计划/关闭请求。 | 配置文件中的第一个成员 |
| Task | 包含主题、描述、状态、所有者和依赖关系的工作项。 | |
| Inbox | Agent接收Teammate消息的JSON文件。 | |
| Message | Agent之间发送的JSON对象,可包含文本或结构化内容(如shutdown_request、idle_notification等)。 | 存储在收件箱文件中 |
| Backend | Teammate的运行方式,自动检测: | 根据环境自动检测 |
How They Connect
组件关联关系
mermaid
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| Task3mermaid
flowchart TB
subgraph TEAM[TEAM]
Leader[Leader - 你]
T1[Teammate 1]
T2[Teammate 2]
Leader <-->|通过收件箱发送消息| T1
Leader <-->|通过收件箱发送消息| T2
T1 <-.->|可发送消息| T2
end
subgraph TASKS[任务列表]
Task1["#1 已完成: 调研<br/>所有者: teammate1"]
Task2["#2 进行中: 实现<br/>所有者: teammate2"]
Task3["#3 待处理: 测试<br/>被#2阻塞"]
end
T1 --> Task1
T2 --> Task2
Task2 -.->|完成后解除阻塞| Task3Lifecycle
生命周期
mermaid
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]mermaid
flowchart LR
A[1. 创建Team] --> B[2. 创建任务]
B --> C[3. 生成Teammate]
C --> D[4. 执行工作]
D --> E[5. 协同协作]
E --> F[6. 关闭集群]
F --> G[7. 清理资源]Message Flow
消息流转
mermaid
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: cleanupmermaid
sequenceDiagram
participant L as Leader
participant T1 as Teammate 1
participant T2 as Teammate 2
participant Tasks as 任务列表
L->>Tasks: TaskCreate (创建3个任务)
L->>T1: 生成Agent并附带提示词
L->>T2: 生成Agent并附带提示词
T1->>Tasks: 认领任务#1
T2->>Tasks: 认领任务#2
T1->>Tasks: 完成任务#1
T1->>L: 发送调研结果至收件箱
Note over Tasks: #3自动解除阻塞
T2->>Tasks: 完成任务#2
T2->>L: 发送实现结果至收件箱
L->>T1: 发送关闭请求
T1->>L: 批准关闭请求
L->>T2: 发送关闭请求
T2->>L: 批准关闭请求
L->>L: 清理资源Table of Contents
目录
Core Architecture
核心架构
How Swarms Work
集群工作原理
A swarm consists of:
- Leader (you) - Creates team, spawns workers, coordinates work
- Teammates (spawned agents) - Execute tasks, report back
- Task List - Shared work queue with dependencies
- Inboxes - JSON files for inter-agent messaging
一个集群包含:
- Leader(你):创建Team、生成Worker、协调工作
- Teammates(生成的Agent):执行任务、反馈结果
- 任务列表:带依赖关系的共享工作队列
- 收件箱:用于Agent间通信的JSON文件
File Structure
文件结构
~/.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~/.claude/teams/{team-name}/
├── config.json # Team元数据和成员列表
└── inboxes/
├── team-lead.json # Leader的收件箱
├── worker-1.json # Worker 1的收件箱
└── worker-2.json # Worker 2的收件箱
~/.claude/tasks/{team-name}/
├── 1.json # 任务#1
├── 2.json # 任务#2
└── 3.json # 任务#3Team Config Structure
Team配置结构
json
{
"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"
}
]
}json
{
"name": "my-project",
"description": "开发功能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": "分析代码库结构...",
"color": "#D94A4A",
"planModeRequired": false,
"joinedAt": 1706000001000,
"tmuxPaneId": "in-process",
"cwd": "/Users/me/project",
"backendType": "in-process"
}
]
}Two Ways to Spawn Agents
两种Agent生成方式
Method 1: Task Tool (Subagents)
方式1:Task工具(子Agent)
Use Task for short-lived, focused work that returns a result:
javascript
Task({
subagent_type: "Explore",
description: "Find auth files",
prompt: "Find all authentication-related files in this codebase",
model: "haiku" // Optional: haiku, sonnet, opus
})Characteristics:
- Runs synchronously (blocks until complete) or async with
run_in_background: true - Returns result directly to you
- No team membership required
- Best for: searches, analysis, focused research
使用Task创建短期、聚焦型工作的Agent,完成后返回结果:
javascript
Task({
subagent_type: "Explore",
description: "查找认证相关文件",
prompt: "查找此代码库中所有与认证相关的文件",
model: "haiku" // 可选:haiku, sonnet, opus
})特点:
- 同步运行(阻塞直到完成)或通过异步运行
run_in_background: true - 直接向你返回结果
- 无需加入Team
- 最佳场景:搜索、分析、聚焦型调研
Method 2: Task Tool + team_name + name (Teammates)
方式2:Task工具 + team_name + name(Teammate)
Use Task with and to spawn persistent teammates:
team_namenamejavascript
// 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
})Characteristics:
- Joins team, appears in
config.json - Communicates via inbox messages
- Can claim tasks from shared task list
- Persists until shutdown
- Best for: parallel work, ongoing collaboration, pipeline stages
使用带和参数的Task创建持久化Teammate:
team_namenamejavascript
// 先创建Team
Teammate({ operation: "spawnTeam", team_name: "my-project" })
// 然后生成Teammate加入该Team
Task({
team_name: "my-project", // 必填:要加入的Team名称
name: "security-reviewer", // 必填:Teammate的名称
subagent_type: "security-sentinel",
prompt: "审查所有认证代码的漏洞,通过Teammate write将结果发送给team-lead。",
run_in_background: true // Teammate通常在后台运行
})特点:
- 加入Team,信息出现在中
config.json - 通过收件箱消息通信
- 可从共享任务列表中认领任务
- 持续运行直到被关闭
- 最佳场景:并行工作、持续协作、流水线阶段任务
Key Difference
核心差异
| Aspect | Task (subagent) | Task + team_name + name (teammate) |
|---|---|---|
| Lifespan | Until task complete | Until shutdown requested |
| Communication | Return value | Inbox messages |
| Task access | None | Shared task list |
| Team membership | No | Yes |
| Coordination | One-off | Ongoing |
| 维度 | Task(子Agent) | Task + team_name + name(Teammate) |
|---|---|---|
| 生命周期 | 任务完成即结束 | 直到收到关闭请求 |
| 通信方式 | 返回值直接传递 | 收件箱消息 |
| 任务访问权限 | 无 | 共享任务列表 |
| Team成员身份 | 无 | 有 |
| 协作模式 | 一次性任务 | 持续协作 |
Built-in Agent Types
内置Agent类型
These are always available without plugins:
无需插件即可使用的内置Agent:
Bash
Bash
javascript
Task({
subagent_type: "Bash",
description: "Run git commands",
prompt: "Check git status and show recent commits"
})- Tools: Bash only
- Model: Inherits from parent
- Best for: Git operations, command execution, system tasks
javascript
Task({
subagent_type: "Bash",
description: "执行Git命令",
prompt: "检查Git状态并显示最近提交记录"
})- 工具: 仅Bash
- 模型: 继承自父Agent
- 最佳场景: Git操作、命令执行、系统任务
Explore
Explore
javascript
Task({
subagent_type: "Explore",
description: "Find API endpoints",
prompt: "Find all API endpoints in this codebase. Be very thorough.",
model: "haiku" // Fast and cheap
})- Tools: All read-only tools (no Edit, Write, NotebookEdit, Task)
- Model: Haiku (optimized for speed)
- Best for: Codebase exploration, file searches, code understanding
- Thoroughness levels: "quick", "medium", "very thorough"
javascript
Task({
subagent_type: "Explore",
description: "查找API端点",
prompt: "彻底查找此代码库中所有API端点。",
model: "haiku" // 快速且低成本
})- 工具: 所有只读工具(不包含Edit、Write、NotebookEdit、Task)
- 模型: Haiku(优化速度)
- 最佳场景: 代码库探索、文件搜索、代码理解
- ** thoroughness级别:** "quick", "medium", "very thorough"
Plan
Plan
javascript
Task({
subagent_type: "Plan",
description: "Design auth system",
prompt: "Create an implementation plan for adding OAuth2 authentication"
})- Tools: All read-only tools
- Model: Inherits from parent
- Best for: Architecture planning, implementation strategies
javascript
Task({
subagent_type: "Plan",
description: "设计认证系统",
prompt: "创建添加OAuth2认证的实现方案"
})- 工具: 所有只读工具
- 模型: 继承自父Agent
- 最佳场景: 架构规划、实现策略设计
general-purpose
general-purpose
javascript
Task({
subagent_type: "general-purpose",
description: "Research and implement",
prompt: "Research React Query best practices and implement caching for the user API"
})- Tools: All tools (*)
- Model: Inherits from parent
- Best for: Multi-step tasks, research + action combinations
javascript
Task({
subagent_type: "general-purpose",
description: "调研与实现",
prompt: "调研React Query最佳实践并为用户API实现缓存"
})- 工具: 所有工具 (*)
- 模型: 继承自父Agent
- 最佳场景: 多步骤任务、调研+操作组合任务
claude-code-guide
claude-code-guide
javascript
Task({
subagent_type: "claude-code-guide",
description: "Help with Claude Code",
prompt: "How do I configure MCP servers?"
})- Tools: Read-only + WebFetch + WebSearch
- Best for: Questions about Claude Code, Agent SDK, Anthropic API
javascript
Task({
subagent_type: "claude-code-guide",
description: "Claude Code使用帮助",
prompt: "如何配置MCP服务器?"
})- 工具: 只读工具 + WebFetch + WebSearch
- 最佳场景: 关于Claude Code、Agent SDK、Anthropic API的问题
statusline-setup
statusline-setup
javascript
Task({
subagent_type: "statusline-setup",
description: "Configure status line",
prompt: "Set up a status line showing git branch and node version"
})- Tools: Read, Edit only
- Model: Sonnet
- Best for: Configuring Claude Code status line
javascript
Task({
subagent_type: "statusline-setup",
description: "配置状态行",
prompt: "设置显示Git分支和Node版本的状态行"
})- 工具: 仅Read、Edit
- 模型: Sonnet
- 最佳场景: 配置Claude Code状态行
Plugin Agent Types
插件Agent类型
From the plugin (examples):
compound-engineering来自插件的Agent示例:
compound-engineeringReview Agents
审查类Agent
javascript
// 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"
})All review agents from compound-engineering:
- - Ensures features work for agents too
agent-native-reviewer - - Architectural compliance
architecture-strategist - - YAGNI and minimalism
code-simplicity-reviewer - - Database and data safety
data-integrity-guardian - - Migration validation
data-migration-expert - - Pre-deploy checklists
deployment-verification-agent - - DHH/37signals Rails style
dhh-rails-reviewer - - JavaScript race conditions
julik-frontend-races-reviewer - - Python best practices
kieran-python-reviewer - - Rails best practices
kieran-rails-reviewer - - TypeScript best practices
kieran-typescript-reviewer - - Design patterns and anti-patterns
pattern-recognition-specialist - - Performance analysis
performance-oracle - - Security vulnerabilities
security-sentinel
javascript
// 安全审查
Task({
subagent_type: "compound-engineering:review:security-sentinel",
description: "安全审计",
prompt: "审计此PR中的安全漏洞"
})
// 性能审查
Task({
subagent_type: "compound-engineering:review:performance-oracle",
description: "性能检查",
prompt: "分析此代码的性能瓶颈"
})
// Rails代码审查
Task({
subagent_type: "compound-engineering:review:kieran-rails-reviewer",
description: "Rails代码审查",
prompt: "审查此Rails代码是否符合最佳实践"
})
// 架构审查
Task({
subagent_type: "compound-engineering:review:architecture-strategist",
description: "架构审查",
prompt: "审查认证模块的系统架构"
})
// 代码简洁性审查
Task({
subagent_type: "compound-engineering:review:code-simplicity-reviewer",
description: "简洁性检查",
prompt: "检查此实现是否可以简化"
})compound-engineering提供的所有审查类Agent:
- - 确保功能对Agent同样适用
agent-native-reviewer - - 架构合规性审查
architecture-strategist - - YAGNI原则与极简主义审查
code-simplicity-reviewer - - 数据库与数据安全性审查
data-integrity-guardian - - 迁移验证
data-migration-expert - - 部署前检查清单
deployment-verification-agent - - DHH/37signals风格Rails代码审查
dhh-rails-reviewer - - JavaScript竞态条件审查
julik-frontend-races-reviewer - - Python最佳实践审查
kieran-python-reviewer - - Rails最佳实践审查
kieran-rails-reviewer - - TypeScript最佳实践审查
kieran-typescript-reviewer - - 设计模式与反模式识别
pattern-recognition-specialist - - 性能分析
performance-oracle - - 安全漏洞审查
security-sentinel
Research Agents
调研类Agent
javascript
// 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"
})All research agents:
- - External best practices
best-practices-researcher - - Framework documentation
framework-docs-researcher - - Code archaeology
git-history-analyzer - - Search docs/solutions/
learnings-researcher - - Repository patterns
repo-research-analyst
javascript
// 最佳实践调研
Task({
subagent_type: "compound-engineering:research:best-practices-researcher",
description: "认证最佳实践调研",
prompt: "调研2024-2026年Rails中JWT认证的当前最佳实践"
})
// 框架文档调研
Task({
subagent_type: "compound-engineering:research:framework-docs-researcher",
description: "Active Storage调研",
prompt: "收集关于Active Storage文件上传的全面文档"
})
// Git历史分析
Task({
subagent_type: "compound-engineering:research:git-history-analyzer",
description: "认证模块历史分析",
prompt: "分析认证模块的Git历史以了解其演变过程"
})所有调研类Agent:
- - 外部最佳实践调研
best-practices-researcher - - 框架文档调研
framework-docs-researcher - - 代码溯源分析
git-history-analyzer - - 文档/解决方案搜索
learnings-researcher - - 仓库模式分析
repo-research-analyst
Design Agents
设计类Agent
javascript
Task({
subagent_type: "compound-engineering:design:figma-design-sync",
description: "Sync with Figma",
prompt: "Compare implementation with Figma design at [URL]"
})javascript
Task({
subagent_type: "compound-engineering:design:figma-design-sync",
description: "与Figma同步",
prompt: "对比实现代码与[URL]中的Figma设计"
})Workflow Agents
工作流类Agent
javascript
Task({
subagent_type: "compound-engineering:workflow:bug-reproduction-validator",
description: "Validate bug",
prompt: "Reproduce and validate this reported bug: [description]"
})javascript
Task({
subagent_type: "compound-engineering:workflow:bug-reproduction-validator",
description: "Bug验证",
prompt: "复现并验证此上报的Bug:[描述]"
})TeammateTool Operations
TeammateTool操作
1. spawnTeam - Create a Team
1. spawnTeam - 创建Team
javascript
Teammate({
operation: "spawnTeam",
team_name: "feature-auth",
description: "Implementing OAuth2 authentication"
})Creates:
~/.claude/teams/feature-auth/config.json- directory
~/.claude/tasks/feature-auth/ - You become the team leader
javascript
Teammate({
operation: "spawnTeam",
team_name: "feature-auth",
description: "实现OAuth2认证"
})创建内容:
~/.claude/teams/feature-auth/config.json- 目录
~/.claude/tasks/feature-auth/ - 你将成为Team的Leader
2. discoverTeams - List Available Teams
2. discoverTeams - 列出可用Team
javascript
Teammate({ operation: "discoverTeams" })Returns: List of teams you can join (not already a member of)
javascript
Teammate({ operation: "discoverTeams" })返回: 你可加入的Team列表(非当前成员的Team)
3. requestJoin - Request to Join Team
3. requestJoin - 请求加入Team
javascript
Teammate({
operation: "requestJoin",
team_name: "feature-auth",
proposed_name: "helper",
capabilities: "I can help with code review and testing"
})javascript
Teammate({
operation: "requestJoin",
team_name: "feature-auth",
proposed_name: "helper",
capabilities: "我可协助代码审查和测试"
})4. approveJoin - Accept Join Request (Leader Only)
4. approveJoin - 批准加入请求(仅Leader可用)
When you receive a message:
join_requestjson
{"type": "join_request", "proposedName": "helper", "requestId": "join-123", ...}Approve it:
javascript
Teammate({
operation: "approveJoin",
target_agent_id: "helper",
request_id: "join-123"
})当你收到消息时:
join_requestjson
{"type": "join_request", "proposedName": "helper", "requestId": "join-123", ...}批准请求:
javascript
Teammate({
operation: "approveJoin",
target_agent_id: "helper",
request_id: "join-123"
})5. rejectJoin - Decline Join Request (Leader Only)
5. rejectJoin - 拒绝加入请求(仅Leader可用)
javascript
Teammate({
operation: "rejectJoin",
target_agent_id: "helper",
request_id: "join-123",
reason: "Team is at capacity"
})javascript
Teammate({
operation: "rejectJoin",
target_agent_id: "helper",
request_id: "join-123",
reason: "Team成员已满"
})6. write - Message One Teammate
6. write - 向单个Teammate发送消息
javascript
Teammate({
operation: "write",
target_agent_id: "security-reviewer",
value: "Please prioritize the authentication module. The deadline is tomorrow."
})Important for teammates: Your text output is NOT visible to the team. You MUST use to communicate.
writejavascript
Teammate({
operation: "write",
target_agent_id: "security-reviewer",
value: "请优先处理认证模块,截止日期为明天。"
})重要提示: 你的文本输出不会被Team成员看到,必须使用进行通信。
write7. broadcast - Message ALL Teammates
7. broadcast - 向所有Teammate发送消息
javascript
Teammate({
operation: "broadcast",
name: "team-lead", // Your name
value: "Status check: Please report your progress"
})WARNING: Broadcasting is expensive - sends N separate messages for N teammates. Prefer to specific teammates.
writeWhen to broadcast:
- Critical issues requiring immediate attention
- Major announcements affecting everyone
When NOT to broadcast:
- Responding to one teammate
- Normal back-and-forth
- Information relevant to only some teammates
javascript
Teammate({
operation: "broadcast",
name: "team-lead", // 你的名称
value: "进度检查:请汇报当前工作进展"
})警告: 广播会向N个Teammate发送N条独立消息,优先使用与特定Teammate通信。
write适合广播的场景:
- 需要立即关注的关键问题
- 影响所有成员的重大公告
不适合广播的场景:
- 回复单个Teammate
- 日常来回沟通
- 仅与部分成员相关的信息
8. requestShutdown - Ask Teammate to Exit (Leader Only)
8. requestShutdown - 请求Teammate退出(仅Leader可用)
javascript
Teammate({
operation: "requestShutdown",
target_agent_id: "security-reviewer",
reason: "All tasks complete, wrapping up"
})javascript
Teammate({
operation: "requestShutdown",
target_agent_id: "security-reviewer",
reason: "所有任务已完成,准备收尾"
})9. approveShutdown - Accept Shutdown (Teammate Only)
9. approveShutdown - 批准关闭请求(仅Teammate可用)
When you receive a message:
shutdown_requestjson
{"type": "shutdown_request", "requestId": "shutdown-123", "from": "team-lead", "reason": "Done"}MUST call:
javascript
Teammate({
operation: "approveShutdown",
request_id: "shutdown-123"
})This sends confirmation and terminates your process.
当你收到消息时:
shutdown_requestjson
{"type": "shutdown_request", "requestId": "shutdown-123", "from": "team-lead", "reason": "任务完成"}必须调用:
javascript
Teammate({
operation: "approveShutdown",
request_id: "shutdown-123"
})此操作会发送确认信息并终止进程。
10. rejectShutdown - Decline Shutdown (Teammate Only)
10. rejectShutdown - 拒绝关闭请求(仅Teammate可用)
javascript
Teammate({
operation: "rejectShutdown",
request_id: "shutdown-123",
reason: "Still working on task #3, need 5 more minutes"
})javascript
Teammate({
operation: "rejectShutdown",
request_id: "shutdown-123",
reason: "仍在处理任务#3,还需5分钟"
})11. approvePlan - Approve Teammate's Plan (Leader Only)
11. approvePlan - 批准Teammate的计划(仅Leader可用)
When teammate with sends a plan:
plan_mode_requiredjson
{"type": "plan_approval_request", "from": "architect", "requestId": "plan-456", ...}Approve:
javascript
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-456"
})当设置了的Teammate发送计划时:
plan_mode_requiredjson
{"type": "plan_approval_request", "from": "architect", "requestId": "plan-456", ...}批准计划:
javascript
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-456"
})12. rejectPlan - Reject Plan with Feedback (Leader Only)
12. rejectPlan - 拒绝计划并提供反馈(仅Leader可用)
javascript
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-456",
feedback: "Please add error handling for the API calls and consider rate limiting"
})javascript
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-456",
feedback: "请添加API调用的错误处理,并考虑限流机制"
})13. cleanup - Remove Team Resources
13. cleanup - 清理Team资源
javascript
Teammate({ operation: "cleanup" })Removes:
- directory
~/.claude/teams/{team-name}/ - directory
~/.claude/tasks/{team-name}/
IMPORTANT: Will fail if teammates are still active. Use first.
requestShutdownjavascript
Teammate({ operation: "cleanup" })清理内容:
- 目录
~/.claude/teams/{team-name}/ - 目录
~/.claude/tasks/{team-name}/
重要提示: 如果Teammate仍在运行,清理会失败。需先使用关闭所有Teammate。
requestShutdownTask System Integration
任务系统集成
TaskCreate - Create Work Items
TaskCreate - 创建工作项
javascript
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
})javascript
TaskCreate({
subject: "审查认证模块",
description: "审查app/services/auth/目录下所有文件的安全漏洞",
activeForm: "正在审查认证模块..." // 任务进行中时显示在加载动画中
})TaskList - See All Tasks
TaskList - 查看所有任务
javascript
TaskList()Returns:
#1 [completed] Analyze codebase structure
#2 [in_progress] Review authentication module (owner: security-reviewer)
#3 [pending] Generate summary report [blocked by #2]javascript
TaskList()返回示例:
#1 [已完成] 分析代码库结构
#2 [进行中] 审查认证模块(所有者:security-reviewer)
#3 [待处理] 生成总结报告 [被#2阻塞]TaskGet - Get Task Details
TaskGet - 获取任务详情
javascript
TaskGet({ taskId: "2" })Returns full task with description, status, blockedBy, etc.
javascript
TaskGet({ taskId: "2" })返回包含描述、状态、阻塞依赖等的完整任务信息。
TaskUpdate - Update Task Status
TaskUpdate - 更新任务状态
javascript
// 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"] })javascript
// 认领任务
TaskUpdate({ taskId: "2", owner: "security-reviewer" })
// 开始工作
TaskUpdate({ taskId: "2", status: "in_progress" })
// 标记完成
TaskUpdate({ taskId: "2", status: "completed" })
// 设置依赖关系
TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] })Task Dependencies
任务依赖关系
When a blocking task is completed, blocked tasks are automatically unblocked:
javascript
// 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.当阻塞任务完成时,被阻塞任务会自动解除阻塞:
javascript
// 创建流水线任务
TaskCreate({ subject: "步骤1:调研" }) // #1
TaskCreate({ subject: "步骤2:实现" }) // #2
TaskCreate({ subject: "步骤3:测试" }) // #3
TaskCreate({ subject: "步骤4:部署" }) // #4
// 设置依赖关系
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) // #2等待#1完成
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] }) // #3等待#2完成
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] }) // #4等待#3完成
// 当#1完成时,#2自动解除阻塞
// 当#2完成时,#3自动解除阻塞
// 以此类推Task File Structure
任务文件结构
~/.claude/tasks/{team-name}/1.jsonjson
{
"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
}~/.claude/tasks/{team-name}/1.jsonjson
{
"id": "1",
"subject": "审查认证模块",
"description": "审查app/services/auth/目录下所有文件...",
"status": "in_progress",
"owner": "security-reviewer",
"activeForm": "正在审查认证模块...",
"blockedBy": [],
"blocks": ["3"],
"createdAt": 1706000000000,
"updatedAt": 1706000001000
}Message Formats
消息格式
Regular Message
普通消息
json
{
"from": "team-lead",
"text": "Please prioritize the auth module",
"timestamp": "2026-01-25T23:38:32.588Z",
"read": false
}json
{
"from": "team-lead",
"text": "请优先处理认证模块",
"timestamp": "2026-01-25T23:38:32.588Z",
"read": false
}Structured Messages (JSON in text field)
结构化消息(text字段为JSON)
Shutdown Request
关闭请求
json
{
"type": "shutdown_request",
"requestId": "shutdown-abc123@worker-1",
"from": "team-lead",
"reason": "All tasks complete",
"timestamp": "2026-01-25T23:38:32.588Z"
}json
{
"type": "shutdown_request",
"requestId": "shutdown-abc123@worker-1",
"from": "team-lead",
"reason": "所有任务已完成",
"timestamp": "2026-01-25T23:38:32.588Z"
}Shutdown Approved
关闭批准
json
{
"type": "shutdown_approved",
"requestId": "shutdown-abc123@worker-1",
"from": "worker-1",
"paneId": "%5",
"backendType": "in-process",
"timestamp": "2026-01-25T23:39:00.000Z"
}json
{
"type": "shutdown_approved",
"requestId": "shutdown-abc123@worker-1",
"from": "worker-1",
"paneId": "%5",
"backendType": "in-process",
"timestamp": "2026-01-25T23:39:00.000Z"
}Idle Notification (auto-sent when teammate stops)
空闲通知(Teammate停止工作时自动发送)
json
{
"type": "idle_notification",
"from": "worker-1",
"timestamp": "2026-01-25T23:40:00.000Z",
"completedTaskId": "2",
"completedStatus": "completed"
}json
{
"type": "idle_notification",
"from": "worker-1",
"timestamp": "2026-01-25T23:40:00.000Z",
"completedTaskId": "2",
"completedStatus": "completed"
}Task Completed
任务完成通知
json
{
"type": "task_completed",
"from": "worker-1",
"taskId": "2",
"taskSubject": "Review authentication module",
"timestamp": "2026-01-25T23:40:00.000Z"
}json
{
"type": "task_completed",
"from": "worker-1",
"taskId": "2",
"taskSubject": "审查认证模块",
"timestamp": "2026-01-25T23:40:00.000Z"
}Plan Approval Request
计划批准请求
json
{
"type": "plan_approval_request",
"from": "architect",
"requestId": "plan-xyz789",
"planContent": "# Implementation Plan\n\n1. ...",
"timestamp": "2026-01-25T23:41:00.000Z"
}json
{
"type": "plan_approval_request",
"from": "architect",
"requestId": "plan-xyz789",
"planContent": "# 实现方案\n\n1. ...",
"timestamp": "2026-01-25T23:41:00.000Z"
}Join Request
加入请求
json
{
"type": "join_request",
"proposedName": "helper",
"requestId": "join-abc123",
"capabilities": "Code review and testing",
"timestamp": "2026-01-25T23:42:00.000Z"
}json
{
"type": "join_request",
"proposedName": "helper",
"requestId": "join-abc123",
"capabilities": "代码审查和测试",
"timestamp": "2026-01-25T23:42:00.000Z"
}Permission Request (for sandbox/tool permissions)
权限请求(沙箱/工具权限)
json
{
"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
}json
{
"type": "permission_request",
"requestId": "perm-123",
"workerId": "worker-1@my-project",
"workerName": "worker-1",
"workerColor": "#4A90D9",
"toolName": "Bash",
"toolUseId": "toolu_abc123",
"description": "执行npm install",
"input": {"command": "npm install"},
"permissionSuggestions": ["Bash(npm *)"],
"createdAt": 1706000000000
}Orchestration Patterns
编排模式
Pattern 1: Parallel Specialists (Leader Pattern)
模式1:并行专家模式(Leader模式)
Multiple specialists review code simultaneously:
javascript
// 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" })多个专家同时审查代码:
javascript
// 1. 创建Team
Teammate({ operation: "spawnTeam", team_name: "code-review" })
// 2. 并行生成专家(单条消息中发送多个Task调用)
Task({
team_name: "code-review",
name: "security",
subagent_type: "compound-engineering:review:security-sentinel",
prompt: "审查PR中的安全漏洞,重点关注:SQL注入、XSS、认证绕过。将结果发送给team-lead。",
run_in_background: true
})
Task({
team_name: "code-review",
name: "performance",
subagent_type: "compound-engineering:review:performance-oracle",
prompt: "审查PR中的性能问题,重点关注:N+1查询、内存泄漏、慢算法。将结果发送给team-lead。",
run_in_background: true
})
Task({
team_name: "code-review",
name: "simplicity",
subagent_type: "compound-engineering:review:code-simplicity-reviewer",
prompt: "审查PR中的不必要复杂度,重点关注:过度工程、过早抽象、YAGNI原则违反。将结果发送给team-lead。",
run_in_background: true
})
// 3. 等待结果(检查收件箱)
// cat ~/.claude/teams/code-review/inboxes/team-lead.json
// 4. 整合结果并清理资源
Teammate({ operation: "requestShutdown", target_agent_id: "security" })
Teammate({ operation: "requestShutdown", target_agent_id: "performance" })
Teammate({ operation: "requestShutdown", target_agent_id: "simplicity" })
// 等待批准...
Teammate({ operation: "cleanup" })Pattern 2: Pipeline (Sequential Dependencies)
模式2:流水线模式(顺序依赖)
Each stage depends on the previous:
javascript
// 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每个阶段依赖前一阶段完成:
javascript
// 1. 创建Team和任务流水线
Teammate({ operation: "spawnTeam", team_name: "feature-pipeline" })
TaskCreate({ subject: "调研", description: "调研功能的最佳实践", activeForm: "调研中..." })
TaskCreate({ subject: "规划", description: "基于调研结果创建实现方案", activeForm: "规划中..." })
TaskCreate({ subject: "实现", description: "根据方案实现功能", activeForm: "实现中..." })
TaskCreate({ subject: "测试", description: "编写并运行测试用例", activeForm: "测试中..." })
TaskCreate({ subject: "最终审查", description: "合并前的最终代码审查", activeForm: "审查中..." })
// 设置顺序依赖
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] })
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] })
TaskUpdate({ taskId: "5", addBlockedBy: ["4"] })
// 2. 生成Worker认领并完成任务
Task({
team_name: "feature-pipeline",
name: "researcher",
subagent_type: "compound-engineering:research:best-practices-researcher",
prompt: "认领任务#1,调研最佳实践,完成后将结果发送给team-lead,然后检查是否有更多工作。",
run_in_background: true
})
Task({
team_name: "feature-pipeline",
name: "implementer",
subagent_type: "general-purpose",
prompt: "每30秒调用一次TaskList,当任务#3解除阻塞时认领并实现,完成后通知team-lead。",
run_in_background: true
})
// 任务会随着依赖完成自动解除阻塞Pattern 3: Swarm (Self-Organizing)
模式3:集群模式(自组织)
Workers grab available tasks from a pool:
javascript
// 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-balanceWorker从任务池中获取可用任务:
javascript
// 1. 创建Team和任务池
Teammate({ operation: "spawnTeam", team_name: "file-review-swarm" })
// 创建多个独立任务(无依赖)
for (const file of ["auth.rb", "user.rb", "api_controller.rb", "payment.rb"]) {
TaskCreate({
subject: `审查${file}`,
description: `审查${file}的安全和代码质量问题`,
activeForm: `正在审查${file}...`
})
}
// 2. 生成Worker集群
Task({
team_name: "file-review-swarm",
name: "worker-1",
subagent_type: "general-purpose",
prompt: `
你是集群Worker,工作流程:
1. 调用TaskList查看可用任务
2. 找到状态为'pending'且无所有者的任务
3. 认领任务:TaskUpdate({ taskId: "X", owner: "你的名称" })
4. 执行审查工作
5. 标记任务完成:TaskUpdate({ taskId: "X", status: "completed" })
6. 通过Teammate write将结果发送给team-lead
7. 重复步骤1直到无任务
`,
run_in_background: true
})
Task({
team_name: "file-review-swarm",
name: "worker-2",
subagent_type: "general-purpose",
prompt: `[与worker-1相同的提示词]`,
run_in_background: true
})
Task({
team_name: "file-review-swarm",
name: "worker-3",
subagent_type: "general-purpose",
prompt: `[与worker-1相同的提示词]`,
run_in_background: true
})
// Worker会竞争认领任务,自然实现负载均衡Pattern 4: Research + Implementation
模式4:调研+实现模式
Research first, then implement:
javascript
// 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.
`
})先调研再实现:
javascript
// 1. 调研阶段(同步执行,返回结果)
const research = await Task({
subagent_type: "compound-engineering:research:best-practices-researcher",
description: "调研缓存模式",
prompt: "调研Rails API中实现缓存的最佳实践,包括:缓存失效策略、Redis vs Memcached、缓存键设计。"
})
// 2. 基于调研结果实现
Task({
subagent_type: "general-purpose",
description: "实现缓存",
prompt: `
基于以下调研结果实现API缓存:
${research.content}
重点关注user_controller.rb的接口。
`
})Pattern 5: Plan Approval Workflow
模式5:计划批准工作流
Require plan approval before implementation:
javascript
// 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"
})实现前需批准计划:
javascript
// 1. 创建Team
Teammate({ operation: "spawnTeam", team_name: "careful-work" })
// 2. 生成需要计划批准的Architect
Task({
team_name: "careful-work",
name: "architect",
subagent_type: "Plan",
prompt: "设计添加OAuth2认证的实现方案",
mode: "plan", // 需要计划批准
run_in_background: true
})
// 3. 等待计划批准请求
// 你将收到:{"type": "plan_approval_request", "from": "architect", "requestId": "plan-xxx", ...}
// 4. 审查并批准/拒绝
Teammate({
operation: "approvePlan",
target_agent_id: "architect",
request_id: "plan-xxx"
})
// 或
Teammate({
operation: "rejectPlan",
target_agent_id: "architect",
request_id: "plan-xxx",
feedback: "请添加API调用的错误处理,并考虑限流机制"
})Pattern 6: Coordinated Multi-File Refactoring
模式6:多文件协同重构
javascript
// 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
})javascript
// 1. 创建用于协同重构的Team
Teammate({ operation: "spawnTeam", team_name: "refactor-auth" })
// 2. 创建清晰文件边界的任务
TaskCreate({
subject: "重构User模型",
description: "将认证方法提取到AuthenticatableUser concern中",
activeForm: "正在重构User模型..."
})
TaskCreate({
subject: "重构Session控制器",
description: "更新为使用新的AuthenticatableUser concern",
activeForm: "正在重构Session控制器..."
})
TaskCreate({
subject: "更新测试用例",
description: "更新所有认证相关测试用例以适配新结构",
activeForm: "正在更新测试用例..."
})
// 依赖关系:测试任务依赖前两个重构任务完成
TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] })
// 3. 为每个任务生成Worker
Task({
team_name: "refactor-auth",
name: "model-worker",
subagent_type: "general-purpose",
prompt: "认领任务#1,重构User模型,完成后标记任务完成",
run_in_background: true
})
Task({
team_name: "refactor-auth",
name: "controller-worker",
subagent_type: "general-purpose",
prompt: "认领任务#2,重构Session控制器,完成后标记任务完成",
run_in_background: true
})
Task({
team_name: "refactor-auth",
name: "spec-worker",
subagent_type: "general-purpose",
prompt: "等待任务#3解除阻塞(当#1和#2完成时),然后更新测试用例",
run_in_background: true
})Environment Variables
环境变量
Spawned teammates automatically receive these:
bash
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"Using in prompts:
javascript
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."
})生成的Teammate会自动接收以下环境变量:
bash
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"在提示词中使用:
javascript
Task({
team_name: "my-project",
name: "worker",
subagent_type: "general-purpose",
prompt: "你的名称是$CLAUDE_CODE_AGENT_NAME,发送消息给team-lead时使用此名称。"
})Spawn Backends
Spawn Backends
A backend determines how teammate Claude instances actually run. Claude Code supports three backends, and auto-detects the best one based on your environment.
Backend决定Teammate Claude实例的实际运行方式。Claude Code支持三种Backend,并会根据环境自动检测最佳选项。
Backend Comparison
Backend对比
| Backend | How It Works | Visibility | Persistence | Speed |
|---|---|---|---|---|
| in-process | Same Node.js process as leader | Hidden (background) | Dies with leader | Fastest |
| tmux | Separate terminal in tmux session | Visible in tmux | Survives leader exit | Medium |
| iterm2 | Split panes in iTerm2 window | Visible side-by-side | Dies with window | Medium |
| Backend | 工作方式 | 可见性 | 持久性 | 速度 |
|---|---|---|---|---|
| in-process | 与Leader同Node.js进程 | 隐藏(后台) | 随Leader进程终止而结束 | 最快 |
| tmux | 在tmux会话中作为独立终端运行 | 在tmux中可见 | Leader退出后仍可存活 | 中等 |
| iterm2 | 在iTerm2窗口中作为分栏面板运行 | 并排可见 | 随窗口关闭而结束 | 中等 |
Auto-Detection Logic
自动检测逻辑
Claude Code automatically selects a backend using this decision tree:
mermaid
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]Detection checks:
- environment variable → inside tmux
$TMUX - or
$TERM_PROGRAM === "iTerm.app"→ in iTerm2$ITERM_SESSION_ID - → tmux available
which tmux - → it2 CLI installed
which it2
Claude Code通过以下决策树自动选择Backend:
mermaid
flowchart TD
A[开始] --> B{是否在tmux中运行?}
B -->|是| C[使用tmux backend]
B -->|否| D{是否在iTerm2中运行?}
D -->|否| E{是否安装了tmux?}
E -->|是| F[使用tmux - 外部会话]
E -->|否| G[使用in-process]
D -->|是| H{是否安装了it2 CLI?}
H -->|是| I[使用iterm2 backend]
H -->|否| J{是否安装了tmux?}
J -->|是| K[使用tmux - 提示安装it2]
J -->|否| L[错误:安装tmux或it2]检测检查项:
- 环境变量 → 是否在tmux中
$TMUX - 或
$TERM_PROGRAM === "iTerm.app"→ 是否在iTerm2中$ITERM_SESSION_ID - → 是否安装了tmux
which tmux - → 是否安装了it2 CLI
which it2
in-process (Default for non-tmux)
in-process(非tmux环境默认选项)
Teammates run as async tasks within the same Node.js process.
How it works:
- No new process spawned
- Teammates share the same Node.js event loop
- Communication via in-memory queues (fast)
- You don't see teammate output directly
When it's used:
- Not running inside tmux session
- Non-interactive mode (CI, scripts)
- Explicitly set via
CLAUDE_CODE_SPAWN_BACKEND=in-process
Characteristics:
┌─────────────────────────────────────────┐
│ Node.js Process │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Leader │ │Worker 1 │ │Worker 2 │ │
│ │ (main) │ │ (async) │ │ (async) │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────┘Pros:
- Fastest startup (no process spawn)
- Lowest overhead
- Works everywhere
Cons:
- Can't see teammate output in real-time
- All die if leader dies
- Harder to debug
javascript
// 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-processTeammate作为异步任务在同一Node.js进程中运行。
工作原理:
- 不生成新进程
- Teammate共享同一Node.js事件循环
- 通过内存队列通信(速度快)
- 无法直接看到Teammate的输出
适用场景:
- 不在tmux会话中运行
- 非交互式模式(CI、脚本)
- 通过显式指定
CLAUDE_CODE_SPAWN_BACKEND=in-process
架构图:
┌─────────────────────────────────────────┐
│ Node.js进程 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Leader │ │Worker 1 │ │Worker 2 │ │
│ │ (主进程)│ │(异步任务)│ │(异步任务)│ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────┘优点:
- 启动最快(无需生成进程)
- 资源开销最低
- 所有环境都支持
缺点:
- 无法实时查看Teammate输出
- Leader进程终止后所有Teammate都会结束
- 调试难度大
javascript
// 不在tmux中时自动使用in-process
Task({
team_name: "my-project",
name: "worker",
subagent_type: "general-purpose",
prompt: "...",
run_in_background: true
})
// 显式强制使用in-process
// export CLAUDE_CODE_SPAWN_BACKEND=in-processtmux
tmux
Teammates run as separate Claude instances in tmux panes/windows.
How it works:
- Each teammate gets its own tmux pane
- Separate process per teammate
- You can switch panes to see teammate output
- Communication via inbox files
When it's used:
- Running inside a tmux session (is set)
$TMUX - tmux available and not in iTerm2
- Explicitly set via
CLAUDE_CODE_SPAWN_BACKEND=tmux
Layout modes:
- Inside tmux (native): Splits your current window
┌─────────────────┬─────────────────┐
│ │ Worker 1 │
│ Leader ├─────────────────┤
│ (your pane) │ Worker 2 │
│ ├─────────────────┤
│ │ Worker 3 │
└─────────────────┴─────────────────┘- Outside tmux (external session): Creates a new tmux session called
claude-swarm
bash
undefinedTeammate作为独立Claude实例在tmux面板/窗口中运行。
工作原理:
- 每个Teammate拥有独立的tmux面板
- 每个Teammate对应独立进程
- 可切换面板查看Teammate输出
- 通过收件箱文件通信
适用场景:
- 在tmux会话中运行(已设置)
$TMUX - 安装了tmux且不在iTerm2中
- 通过显式指定
CLAUDE_CODE_SPAWN_BACKEND=tmux
布局模式:
- tmux内部(原生): 拆分当前窗口
┌─────────────────┬─────────────────┐
│ │ Worker 1 │
│ Leader ├─────────────────┤
│ (你的面板) │ Worker 2 │
│ ├─────────────────┤
│ │ Worker 3 │
└─────────────────┴─────────────────┘- tmux外部(外部会话): 创建名为的新tmux会话
claude-swarm
bash
undefinedYour terminal stays as-is
你的终端保持不变
Workers run in separate tmux session
Worker在独立tmux会话中运行
View workers:
查看Worker:
tmux attach -t claude-swarm
**Pros:**
- See teammate output in real-time
- Teammates survive leader exit
- Can attach/detach sessions
- Works in CI/headless environments
**Cons:**
- Slower startup (process spawn)
- Requires tmux installed
- More resource usage
```bashtmux attach -t claude-swarm
**优点:**
- 可实时查看Teammate输出
- Leader退出后Teammate仍可存活
- 可连接/断开会话
- 在CI/无头环境中可用
**缺点:**
- 启动较慢(需生成进程)
- 需要安装tmux
- 资源占用较高
```bashStart tmux session first
先启动tmux会话
tmux new-session -s claude
tmux new-session -s claude
Or force tmux backend
或强制使用tmux backend
export CLAUDE_CODE_SPAWN_BACKEND=tmux
**Useful tmux commands:**
```bashexport CLAUDE_CODE_SPAWN_BACKEND=tmux
**实用tmux命令:**
```bashList all panes in current window
列出当前窗口的所有面板
tmux list-panes
tmux list-panes
Switch to pane by number
切换到指定编号的面板
tmux select-pane -t 1
tmux select-pane -t 1
Kill a specific pane
关闭指定面板
tmux kill-pane -t %5
tmux kill-pane -t %5
View swarm session (if external)
查看集群会话(外部会话时)
tmux attach -t claude-swarm
tmux attach -t claude-swarm
Rebalance pane layout
重新平衡面板布局
tmux select-layout tiled
undefinedtmux select-layout tiled
undefinediterm2 (macOS only)
iterm2(仅macOS)
Teammates run as split panes within your iTerm2 window.
How it works:
- Uses iTerm2's Python API via CLI
it2 - Splits your current window into panes
- Each teammate visible side-by-side
- Communication via inbox files
When it's used:
- Running in iTerm2 ()
$TERM_PROGRAM === "iTerm.app" - CLI is installed and working
it2 - Python API enabled in iTerm2 preferences
Layout:
┌─────────────────┬─────────────────┐
│ │ Worker 1 │
│ Leader ├─────────────────┤
│ (your pane) │ Worker 2 │
│ ├─────────────────┤
│ │ Worker 3 │
└─────────────────┴─────────────────┘Pros:
- Visual debugging - see all teammates
- Native macOS experience
- No tmux needed
- Automatic pane management
Cons:
- macOS + iTerm2 only
- Requires setup (it2 CLI + Python API)
- Panes die with window
Setup:
bash
undefinedTeammate作为分栏面板在iTerm2窗口中运行。
工作原理:
- 通过CLI使用iTerm2的Python API
it2 - 拆分当前窗口为多个面板
- 所有Teammate并排可见
- 通过收件箱文件通信
适用场景:
- 在iTerm2中运行()
$TERM_PROGRAM === "iTerm.app" - 已安装并配置CLI
it2 - 在iTerm2偏好设置中启用了Python API
布局:
┌─────────────────┬─────────────────┐
│ │ Worker 1 │
│ Leader ├─────────────────┤
│ (你的面板) │ Worker 2 │
│ ├─────────────────┤
│ │ Worker 3 │
└─────────────────┴─────────────────┘优点:
- 可视化调试 - 可查看所有Teammate
- 原生macOS体验
- 无需tmux
- 自动面板管理
缺点:
- 仅支持macOS + iTerm2
- 需要配置(it2 CLI + Python API)
- 随窗口关闭而结束
配置步骤:
bash
undefined1. Install it2 CLI
1. 安装it2 CLI
uv tool install it2
uv tool install it2
OR
或
pipx install it2
pipx install it2
OR
或
pip install --user it2
pip install --user it2
2. Enable Python API in iTerm2
2. 在iTerm2中启用Python API
iTerm2 → Settings → General → Magic → Enable Python API
iTerm2 → 设置 → 通用 → 魔法 → 启用Python API
3. Restart iTerm2
3. 重启iTerm2
4. Verify
4. 验证
it2 --version
it2 session list
**If setup fails:**
Claude Code will prompt you to set up it2 when you first spawn a teammate. You can choose to:
1. Install it2 now (guided setup)
2. Use tmux instead
3. Cancelit2 --version
it2 session list
**配置失败时:**
当你首次生成Teammate时,Claude Code会提示你配置it2,你可选择:
1. 立即安装it2(引导式配置)
2. 使用tmux替代
3. 取消操作Forcing a Backend
强制指定Backend
bash
undefinedbash
undefinedForce in-process (fastest, no visibility)
强制使用in-process(最快,无可见性)
export CLAUDE_CODE_SPAWN_BACKEND=in-process
export CLAUDE_CODE_SPAWN_BACKEND=in-process
Force tmux (visible panes, persistent)
强制使用tmux(可见面板,持久化)
export CLAUDE_CODE_SPAWN_BACKEND=tmux
export CLAUDE_CODE_SPAWN_BACKEND=tmux
Auto-detect (default)
自动检测(默认)
unset CLAUDE_CODE_SPAWN_BACKEND
undefinedunset CLAUDE_CODE_SPAWN_BACKEND
undefinedBackend in Team Config
Team配置中的Backend
The backend type is recorded per-teammate in :
config.jsonjson
{
"members": [
{
"name": "worker-1",
"backendType": "in-process",
"tmuxPaneId": "in-process"
},
{
"name": "worker-2",
"backendType": "tmux",
"tmuxPaneId": "%5"
}
]
}Backend类型会记录在的每个Teammate信息中:
config.jsonjson
{
"members": [
{
"name": "worker-1",
"backendType": "in-process",
"tmuxPaneId": "in-process"
},
{
"name": "worker-2",
"backendType": "tmux",
"tmuxPaneId": "%5"
}
]
}Troubleshooting Backends
Backend故障排除
| Issue | Cause | Solution |
|---|---|---|
| "No pane backend available" | Neither tmux nor iTerm2 available | Install tmux: |
| "it2 CLI not installed" | In iTerm2 but missing it2 | Run |
| "Python API not enabled" | it2 can't communicate with iTerm2 | Enable in iTerm2 Settings → General → Magic |
| Workers not visible | Using in-process backend | Start inside tmux or iTerm2 |
| Workers dying unexpectedly | Outside tmux, leader exited | Use tmux for persistence |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| "No pane backend available" | 未安装tmux或iTerm2 | 安装tmux: |
| "it2 CLI not installed" | 在iTerm2中但未安装it2 | 运行 |
| "Python API not enabled" | it2无法与iTerm2通信 | 在iTerm2设置 → 通用 → 魔法中启用Python API |
| Workers不可见 | 使用in-process Backend | 在tmux或iTerm2中启动 |
| Workers意外终止 | 不在tmux中,Leader已退出 | 使用tmux以实现持久化 |
Checking Current Backend
检查当前Backend
bash
undefinedbash
undefinedSee what backend was detected
查看检测到的Backend
cat ~/.claude/teams/{team}/config.json | jq '.members[].backendType'
cat ~/.claude/teams/{team}/config.json | jq '.members[].backendType'
Check if inside tmux
检查是否在tmux中
echo $TMUX
echo $TMUX
Check if in iTerm2
检查是否在iTerm2中
echo $TERM_PROGRAM
echo $TERM_PROGRAM
Check tmux availability
检查tmux是否可用
which tmux
which tmux
Check it2 availability
检查it2是否可用
which it2
---which it2
---Error Handling
错误处理
Common Errors
常见错误
| Error | Cause | Solution |
|---|---|---|
| "Cannot cleanup with active members" | Teammates still running | |
| "Already leading a team" | Team already exists | |
| "Agent not found" | Wrong teammate name | Check |
| "Team does not exist" | No team created | Call |
| "team_name is required" | Missing team context | Provide |
| "Agent type not found" | Invalid subagent_type | Check available agents with proper prefix |
| 错误 | 原因 | 解决方案 |
|---|---|---|
| "Cannot cleanup with active members" | Teammate仍在运行 | 先对所有Teammate调用 |
| "Already leading a team" | Team已存在 | 先清理现有Team,或使用不同的Team名称 |
| "Agent not found" | Teammate名称错误 | 查看 |
| "Team does not exist" | 未创建Team | 先调用 |
| "team_name is required" | 缺少Team上下文 | 提供 |
| "Agent type not found" | 无效的subagent_type | 检查带正确前缀的可用Agent类型 |
Graceful Shutdown Sequence
优雅关闭流程
Always follow this sequence:
javascript
// 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" })请始终遵循此流程:
javascript
// 1. 请求所有Teammate关闭
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
Teammate({ operation: "requestShutdown", target_agent_id: "worker-2" })
// 2. 等待关闭批准
// 检查是否收到{"type": "shutdown_approved", ...}消息
// 3. 验证无活跃成员
// 查看~/.claude/teams/{team}/config.json
// 4. 执行清理
Teammate({ operation: "cleanup" })Handling Crashed Teammates
处理崩溃的Teammate
Teammates have a 5-minute heartbeat timeout. If a teammate crashes:
- They'll be automatically marked as inactive after timeout
- Their tasks remain in the task list
- Another teammate can claim their tasks
- Cleanup will work after timeout expires
Teammate有5分钟的心跳超时。如果Teammate崩溃:
- 超时后会自动标记为非活跃状态
- 其任务仍保留在任务列表中
- 其他Teammate可认领这些任务
- 超时后清理操作可正常执行
Debugging
调试方法
bash
undefinedbash
undefinedCheck team config
查看Team配置
cat ~/.claude/teams/{team}/config.json | jq '.members[] | {name, agentType, backendType}'
cat ~/.claude/teams/{team}/config.json | jq '.members[] | {name, agentType, backendType}'
Check teammate inboxes
查看Teammate收件箱
cat ~/.claude/teams/{team}/inboxes/{agent}.json | jq '.'
cat ~/.claude/teams/{team}/inboxes/{agent}.json | jq '.'
List all teams
列出所有Team
ls ~/.claude/teams/
ls ~/.claude/teams/
Check task states
查看任务状态
cat ~/.claude/tasks/{team}/*.json | jq '{id, subject, status, owner, blockedBy}'
cat ~/.claude/tasks/{team}/*.json | jq '{id, subject, status, owner, blockedBy}'
Watch for new messages
监控新消息
tail -f ~/.claude/teams/{team}/inboxes/team-lead.json
---tail -f ~/.claude/teams/{team}/inboxes/team-lead.json
---Complete Workflows
完整工作流
Workflow 1: Full Code Review with Parallel Specialists
工作流1:并行专家全代码审查
javascript
// === 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" })javascript
// === 步骤1:设置 ===
Teammate({ operation: "spawnTeam", team_name: "pr-review-123", description: "审查PR #123" })
// === 步骤2:并行生成审查者 ===
// (在单条消息中发送所有调用以实现并行执行)
Task({
team_name: "pr-review-123",
name: "security",
subagent_type: "compound-engineering:review:security-sentinel",
prompt: `审查PR #123的安全漏洞。
重点关注:
- SQL注入
- XSS漏洞
- 认证/授权绕过
- 敏感数据泄露
完成后,使用以下命令将结果发送给team-lead:
Teammate({ operation: "write", target_agent_id: "team-lead", value: "你的结果" })`,
run_in_background: true
})
Task({
team_name: "pr-review-123",
name: "perf",
subagent_type: "compound-engineering:review:performance-oracle",
prompt: `审查PR #123的性能问题。
重点关注:
- N+1查询
- 缺少索引
- 内存泄漏
- 低效算法
完成后将结果发送给team-lead。`,
run_in_background: true
})
Task({
team_name: "pr-review-123",
name: "arch",
subagent_type: "compound-engineering:review:architecture-strategist",
prompt: `审查PR #123的架构问题。
重点关注:
- 设计模式遵循情况
- SOLID原则
- 关注点分离
- 可测试性
完成后将结果发送给team-lead。`,
run_in_background: true
})
// === 步骤3:监控并收集结果 ===
// 轮询收件箱或等待空闲通知
// cat ~/.claude/teams/pr-review-123/inboxes/team-lead.json
// === 步骤4:整合结果 ===
// 将所有审查者的结果整合成连贯的报告
// === 步骤5:清理资源 ===
Teammate({ operation: "requestShutdown", target_agent_id: "security" })
Teammate({ operation: "requestShutdown", target_agent_id: "perf" })
Teammate({ operation: "requestShutdown", target_agent_id: "arch" })
// 等待批准...
Teammate({ operation: "cleanup" })Workflow 2: Research → Plan → Implement → Test Pipeline
工作流2:调研→规划→实现→测试流水线
javascript
// === 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 completesjavascript
// === 设置 ===
Teammate({ operation: "spawnTeam", team_name: "feature-oauth" })
// === 创建流水线 ===
TaskCreate({ subject: "调研OAuth提供商", description: "调研OAuth2最佳实践并对比提供商(Google、GitHub、Auth0)", activeForm: "调研OAuth中..." })
TaskCreate({ subject: "创建实现方案", description: "基于调研结果设计OAuth实现方案", activeForm: "规划中..." })
TaskCreate({ subject: "实现OAuth", description: "根据方案实现OAuth2认证", activeForm: "实现OAuth中..." })
TaskCreate({ subject: "编写测试用例", description: "为OAuth实现编写全面的测试用例", activeForm: "编写测试中..." })
TaskCreate({ subject: "最终审查", description: "审查完整实现的安全性和质量", activeForm: "最终审查中..." })
// 设置依赖关系
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
TaskUpdate({ taskId: "3", addBlockedBy: ["2"] })
TaskUpdate({ taskId: "4", addBlockedBy: ["3"] })
TaskUpdate({ taskId: "5", addBlockedBy: ["4"] })
// === 生成专业Worker ===
Task({
team_name: "feature-oauth",
name: "researcher",
subagent_type: "compound-engineering:research:best-practices-researcher",
prompt: "认领任务#1,调研OAuth2最佳实践,对比提供商,记录结果。标记任务完成并将摘要发送给team-lead。",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "planner",
subagent_type: "Plan",
prompt: "等待任务#2解除阻塞,查看任务#1的调研结果,创建详细的实现方案。标记完成并将方案发送给team-lead。",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "implementer",
subagent_type: "general-purpose",
prompt: "等待任务#3解除阻塞,查看任务#2的方案,实现OAuth2认证。完成后标记任务完成。",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "tester",
subagent_type: "general-purpose",
prompt: "等待任务#4解除阻塞,为OAuth实现编写全面的测试用例,运行测试。完成后标记任务完成并提交结果。",
run_in_background: true
})
Task({
team_name: "feature-oauth",
name: "reviewer",
subagent_type: "compound-engineering:review:security-sentinel",
prompt: "等待任务#5解除阻塞,审查完整的OAuth实现的安全性。将最终评估发送给team-lead。",
run_in_background: true
})
// 每个阶段完成后流水线自动推进Workflow 3: Self-Organizing Code Review Swarm
工作流3:自组织代码审查集群
javascript
// === 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 inboxjavascript
// === 设置 ===
Teammate({ operation: "spawnTeam", team_name: "codebase-review" })
// === 创建任务池(所有任务独立,无依赖) ===
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: `审查${file}`,
description: `审查${file}的安全漏洞、代码质量和性能问题`,
activeForm: `审查${file}中...`
})
}
// === 生成Worker集群 ===
const swarmPrompt = `
你是集群Worker,工作是持续处理可用任务。
循环:
1. 调用TaskList()查看可用任务
2. 找到满足以下条件的任务:
- 状态: 'pending'
- 无所有者
- 未被阻塞
3. 如果找到:
- 认领任务:TaskUpdate({ taskId: "X", owner: "你的名称" })
- 开始任务:TaskUpdate({ taskId: "X", status: "in_progress" })
- 执行审查工作
- 完成任务:TaskUpdate({ taskId: "X", status: "completed" })
- 通过Teammate write将结果发送给team-lead
- 返回步骤1
4. 如果无可用任务:
- 向team-lead发送空闲通知
- 等待30秒
- 重试(最多3次)
- 如果仍无任务,退出
替换YOUR_NAME为$CLAUDE_CODE_AGENT_NAME中的实际Agent名称。
`
// 生成3个Worker
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会自组织:竞争认领任务,自然实现负载均衡
// 通过TaskList()或查看收件箱监控进度Best Practices
最佳实践
1. Always Cleanup
1. 始终清理资源
Don't leave orphaned teams. Always call when done.
cleanup不要留下孤立的Team,完成后务必调用。
cleanup2. Use Meaningful Names
2. 使用有意义的名称
javascript
// Good
name: "security-reviewer"
name: "oauth-implementer"
name: "test-writer"
// Bad
name: "worker-1"
name: "agent-2"javascript
// 推荐
name: "security-reviewer"
name: "oauth-implementer"
name: "test-writer"
// 不推荐
name: "worker-1"
name: "agent-2"3. Write Clear Prompts
3. 编写清晰的提示词
Tell workers exactly what to do:
javascript
// 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"明确告诉Worker要做什么:
javascript
// 推荐
prompt: `
1. 审查app/models/user.rb中的N+1查询问题
2. 检查所有ActiveRecord关联是否有合适的includes
3. 记录发现的问题
4. 通过Teammate write将结果发送给team-lead
`
// 不推荐
prompt: "审查代码"4. Use Task Dependencies
4. 使用任务依赖
Let the system manage unblocking:
javascript
// Good: Auto-unblocking
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
// Bad: Manual polling
"Wait until task #1 is done, check every 30 seconds..."让系统自动管理阻塞与解除阻塞:
javascript
// 推荐:自动解除阻塞
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })
// 不推荐:手动轮询
"等待任务#1完成,每30秒检查一次..."5. Check Inboxes for Results
5. 检查收件箱获取结果
Workers send results to your inbox. Check it:
bash
cat ~/.claude/teams/{team}/inboxes/team-lead.json | jq '.'Worker会将结果发送到你的收件箱,请定期检查:
bash
cat ~/.claude/teams/{team}/inboxes/team-lead.json | jq '.'6. Handle Worker Failures
6. 处理Worker故障
- Workers have 5-minute heartbeat timeout
- Tasks of crashed workers can be reclaimed
- Build retry logic into worker prompts
- Worker有5分钟的心跳超时
- 崩溃Worker的任务可被重新认领
- 在Worker提示词中加入重试逻辑
7. Prefer write Over broadcast
7. 优先使用write而非broadcast
broadcastwritebroadcastwrite8. Match Agent Type to Task
8. 匹配Agent类型与任务
- Explore for searching/reading
- Plan for architecture design
- general-purpose for implementation
- Specialized reviewers for specific review types
- Explore:搜索/读取场景
- Plan:架构设计场景
- general-purpose:实现场景
- 专业审查Agent:特定类型的审查场景
Quick Reference
快速参考
Spawn Subagent (No Team)
生成子Agent(无需Team)
javascript
Task({ subagent_type: "Explore", description: "Find files", prompt: "..." })javascript
Task({ subagent_type: "Explore", description: "查找文件", prompt: "..." })Spawn Teammate (With Team)
生成Teammate(需Team)
javascript
Teammate({ operation: "spawnTeam", team_name: "my-team" })
Task({ team_name: "my-team", name: "worker", subagent_type: "general-purpose", prompt: "...", run_in_background: true })javascript
Teammate({ operation: "spawnTeam", team_name: "my-team" })
Task({ team_name: "my-team", name: "worker", subagent_type: "general-purpose", prompt: "...", run_in_background: true })Message Teammate
向Teammate发送消息
javascript
Teammate({ operation: "write", target_agent_id: "worker-1", value: "..." })javascript
Teammate({ operation: "write", target_agent_id: "worker-1", value: "..." })Create Task Pipeline
创建任务流水线
javascript
TaskCreate({ subject: "Step 1", description: "..." })
TaskCreate({ subject: "Step 2", description: "..." })
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })javascript
TaskCreate({ subject: "步骤1", description: "..." })
TaskCreate({ subject: "步骤2", description: "..." })
TaskUpdate({ taskId: "2", addBlockedBy: ["1"] })Shutdown Team
关闭Team
javascript
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
// Wait for approval...
Teammate({ operation: "cleanup" })Based on Claude Code v2.1.19 - Tested and verified 2026-01-25
javascript
Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" })
// 等待批准...
Teammate({ operation: "cleanup" })基于Claude Code v2.1.19 - 测试验证于2026-01-25