⚠️ 学习声明:本文档基于 Claude Code 2.1.88 源码分析整理,仅供个人学习研究使用,不做任何商业用途。
Claude Code 支持后台任务、子 Agent、团队协作等多种并行执行模式。
一、任务类型
type TaskType = | 'local_bash' | 'local_agent' | 'remote_agent' | 'in_process_teammate' | 'local_workflow' | 'monitor_mcp' | 'dream'
type TaskStatus = | 'pending' | 'running' | 'completed' | 'failed' | 'killed'
|
二、Task ID 设计
const TASK_ID_PREFIXES: Record<string, string> = { local_bash: 'b', local_agent: 'a', remote_agent: 'r', in_process_teammate: 't', local_workflow: 'w', monitor_mcp: 'm', dream: 'd', };
export function generateTaskId(type: TaskType): string { const prefix = getTaskIdPrefix(type); const bytes = randomBytes(8); let id = prefix; for (let i = 0; i < 8; i++) { id += TASK_ID_ALPHABET[bytes[i]! % TASK_ID_ALPHABET.length]; } return id; }
|
三、Agent 系统
主 Agent (REPL) │ ├─ AgentTool("分析这个 bug") │ │ │ └─ 子 Agent 1 (独立上下文) │ ├─ FileRead → 读取相关文件 │ ├─ Grep → 搜索错误模式 │ └─ 返回分析结果给主 Agent │ ├─ AgentTool("写单元测试") │ │ │ └─ 子 Agent 2 (独立上下文) │ ├─ FileRead → 读取被测代码 │ ├─ FileWrite → 创建测试文件 │ ├─ BashTool → 运行测试 │ └─ 返回测试结果 │ └─ 主 Agent 综合所有子 Agent 结果
|
3.2 Agent 定义
type AgentDefinition = { name: string; slug: string; description: string; prompt: string; model?: string; tools?: string[]; mcpServers?: McpServerConfig[]; maxTokens?: number; isBuiltIn: boolean; };
|
3.3 Agent 执行隔离
export function createSubagentContext(parentContext: ToolUseContext) { return { toolPermissionContext: parentContext.toolPermissionContext, mcpClients: parentContext.options.mcpClients,
messages: [], readFileCache: createFileStateCacheWithSizeLimit(), abortController: new AbortController(),
tools: resolveAgentTools(agentDefinition, parentContext.options.tools), }; }
|
四、Coordinator 模式
export function isCoordinatorMode(): boolean { return isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE); }
|
Coordinator 用户上下文
export function getCoordinatorUserContext( mcpClients, scratchpadDir, ): { [k: string]: string } { }
|
五、Agent Swarms (团队模式)
Worktree 模式
async function createAgentWorktree(agentId: string): Promise<string> { }
async function removeAgentWorktree(agentId: string): Promise<void> { }
|
六、后台任务管理
6.1 Shell 任务
export function spawnShellTask(input: LocalShellSpawnInput): TaskHandle { }
export function backgroundExistingForegroundTask(taskId: string): void; export function registerForeground(taskId: string): void; export function unregisterForeground(taskId: string): void;
|
6.2 任务输出读取
type TaskState = { outputFile: string; outputOffset: number; };
function readTaskOutput(task: TaskState): string { const content = readFromOffset(task.outputFile, task.outputOffset); task.outputOffset += content.length; return content; }
|
七、Task Status 状态机
pending → running → completed → failed → killed
任何状态 → killed (外部终止)
|
export function isTerminalTaskStatus(status: TaskStatus): boolean { return status === 'completed' || status === 'failed' || status === 'killed'; }
|
八、In-Process Teammate
export function injectUserMessageToTeammate( agentId: AgentId, message: string, ): void { }
|
九、任务工具集成
| 工具 |
功能 |
TaskCreateTool |
创建新任务 (bash/agent) |
TaskGetTool |
获取任务状态和输出 |
TaskUpdateTool |
更新任务描述/状态 |
TaskListTool |
列出所有任务 |
TaskStopTool |
终止任务 |
TaskOutputTool |
读取任务输出 |
TodoWriteTool |
管理 TODO 列表 |
十、多 Agent 系统的学术基础
11.1 为什么需要多 Agent?
单 Agent 的局限性:
| 瓶颈 |
表现 |
多 Agent 解法 |
| 上下文窗口 |
一个 Agent 只能关注一个任务 |
每个子 Agent 有独立窗口 |
| 专注度 |
大任务中的子任务容易被忽略 |
每个子 Agent 专注一个子任务 |
| 工具冲突 |
并行工具调用可能相互干扰 |
隔离的工具执行环境 |
| 权限边界 |
一个 Agent 拥有全部权限 |
子 Agent 可被限制权限 |
11.2 学术文献中的多 Agent 模式
| 论文 |
核心模式 |
CC 对应 |
| AutoGen (Wu et al., 2023) |
Agent 间对话协调 |
Swarm 的 Agent 通信 |
| ChatDev (Qian et al., 2024) |
角色模拟(CEO+CTO+程序员) |
Task 的角色分工 |
| MetaGPT (Hong et al., 2024) |
SOP 驱动的 Agent 流程 |
Plan Mode + Task |
11.3 三种多 Agent 架构
1. 层次式(Hierarchical) 主 Agent → 分配子任务 → 子 Agent → 回传结果 CC 实现: Task
2. 对等式(Peer-to-Peer) Agent A ⇔ Agent B(通过 Mailbox 通信) CC 实现: Swarm + Mailbox
3. 混合式(Hybrid) 主 Agent 协调 + 子 Agent 间可直接通信 CC 实现: InProcessTeammate + Mailbox
|
十一、Task 系统:层次式多 Agent
12.1 Task 的生命周期
Task 创建 │ ├─ CREATED ──→ RUNNING ──→ COMPLETED │ │ │ ├─ FAILED (工具执行失败) │ ├─ ABORTED (用户中断) │ └─ TIMEOUT (超时) │ └─ 父 Agent 轮询 Task 状态(循环或 callback)
|
12.2 Task 的代理模式(Delegation)
const task = await createTask({ description: "Refactor UserService to use dependency injection", context: "See src/services/UserService.ts (450 lines)", tools: [FileReadTool, FileEditTool, GrepTool], maxTurns: 10, });
const [task1, task2] = await Promise.all([ createTask({ description: "Add unit tests for UserService" }), createTask({ description: "Update UserController to use new UserService" }), ]);
|
12.3 子 Agent 的上下文隔离
每个子 Agent 拥有独立的:
- System Prompt(包含子任务的专用指令)
- Messages 历史(不包含主 Agent 的对话)
- 工具集(主 Agent 可限制子 Agent 能使用的工具)
- 权限模式(子 Agent 可被授予更低或更高的信任级别)
十二、Swarm 系统:对等式多 Agent
13.1 Swarm 的设计目标
- 自动并行化:将可以并行的工作自动分配给多个 Agent
- 容错性:单个 Agent 失败不影响其他 Agent
- 弹性伸缩:Agent 数量可根据工作负载动态调整
13.2 Swarm 架构
┌─────────────┐ │ Swarm │ │ Coordinator │ ← 协调者(通常是主 Agent) └──┬──┬──┬───┘ │ │ │ ┌──────┘ │ └──────┐ ▼ ▼ ▼ Agent 1 Agent 2 Agent 3 (Task A) (Task B) (Task C) │ │ │ └────┬────┴────┬────┘ ▼ ▼ Mailbox Mailbox │ │ └────┬────┘ ▼ Coordinator
|
13.3 权限同步
Swarm 中的 Agent 通常继承主 Agent 的权限模式,但可通过 leaderPermissionBridge 实现细粒度控制:
class LeaderPermissionBridge { async requestPermission(childAgentId: string, tool: Tool, input: any): Promise<boolean> { const decision = await askUser({ message: `Agent ${childAgentId} wants to use ${tool.name}`, details: JSON.stringify(input), }); return decision === 'allow'; } }
|
十三、Mailbox:Agent 间通信
14.1 Mailbox 的设计
Mailbox 是 Agent 间异步通信的通道,灵感来自 Erlang/OTP 的 Actor 模型:
interface Mailbox { send(toAgentId: string, message: AgentMessage): Promise<void>;
receive(): Promise<AgentMessage[]>;
clear(): void; }
interface AgentMessage { from: string; to: string; type: 'result' | 'query' | 'notification'; content: string; timestamp: number; }
|
14.2 通信模式
1. 通知(Notification)— 单向,无响应 Agent A → Mailbox → Agent B "Task X is done, here are the results"
2. 查询(Query)— 请求-响应 Agent A → Mailbox → Agent B → Mailbox → Agent A "What's the return type of UserService.findById()?"
3. 广播(Broadcast)— 一对多 Coordinator → Mailbox → [Agent 1, Agent 2, Agent 3] "All agents: the API schema changed, adjust your code"
|
14.3 与 Actor 模型的对比
| 维度 |
Erlang Actor |
CC Mailbox |
| 隔离性 |
进程级隔离 |
上下文级隔离 |
| 消息传递 |
异步 by default |
异步 + 可选的同步等待 |
| 监督树 |
OTP Supervisor |
Swarm Coordinator |
| 故障处理 |
Let it crash |
任务级重试 |
十四、Swarm 的协调算法与容错
15.1 工作分配策略
Swarm Coordinator 将工作分配给多个 Agent 时面临经典的调度问题:
type AllocationStrategy = | 'round-robin' | 'least-loaded' | 'capability-match';
function allocateWork(tasks: Task[], agents: Agent[]): Map<Agent, Task[]> { const allocation = new Map<Agent, Task[]>();
for (const task of tasks) { const capable = agents.filter(a => a.capabilities.includes(task.type));
const best = capable.sort((a, b) => a.activeTasks - b.activeTasks)[0];
if (!allocation.has(best)) allocation.set(best, []); allocation.get(best)!.push(task); }
return allocation; }
|
15.2 容错模式
Fault Tolerance Patterns in Swarm:
1. 超时重试 (Timeout + Retry) 子 Agent 在 maxTurns 内未完成 → 重新分配给另一个 Agent
2. 心跳检测 (Heartbeat) 子 Agent 每 30s 向 Coordinator 发送心跳 3 次心跳未收到 → 标记为 FAILED,任务重新分配
3. 结果冗余 (Result Redundancy) 关键任务分配给 2 个 Agent 同时执行 比较结果 → 取一致性高的
4. 优雅降级 (Graceful Degradation) 如果 5 个 Agent 中 2 个失败 → 剩余的 3 个继续工作 如果 Coordinator 失败 → 子 Agent 超时后自行结束
|
15.3 与 Ray/Dask 的架构对比
| 维度 |
CC Swarm |
Ray (分布式计算) |
Dask |
| 任务粒度 |
LLM Turn(秒-分钟级) |
函数调用(毫秒-秒级) |
数组操作 |
| 调度策略 |
Capability + Load |
依赖性 DAG |
Task Graph |
| 容错 |
超时重试 + 心跳 |
Lineage + 重建 |
重试 |
| 通信 |
Mailbox (消息传递) |
Object Store (共享内存) |
序列化传递 |
| 适用场景 |
LLM Agent 协作 |
通用分布式计算 |
科学计算 |
核心差异:Swarm 处理的是非确定性的 LLM 推理(同一任务分配给两个 Agent 可能产生不同结果),而 Ray/Dask 处理的是确定性的函数计算。这导致了完全不同的容错和协调策略。
15.4 多 Agent 的共识问题
当多个 Agent 对同一问题给出不同答案时,Coordinator 需要进行共识决策:
function resolveDisagreement(results: AgentResult[]): FinalResult { const votes = results.map(r => r.conclusion); const majority = mostFrequent(votes);
const weighted = results.map(r => ({ conclusion: r.conclusion, weight: r.confidence * (1 / r.errorRate), }));
return selectBest(weighted); }
|
这实际上是一个简化的拜占庭将军问题变体——在存在可能”出错”(产生低质量输出)的 Agent 的情况下达成可靠共识。
涉及源文件
tools/AgentTool/loadAgentsDir.ts
utils/agentSwarmsEnabled.ts
utils/forkedAgent.ts
utils/mailbox.ts
utils/swarm/leaderPermissionBridge.ts
utils/swarm/permissionSync.ts
utils/worktree.ts