0%

Claude Code 源码解析 (4):多 Agent 协作的架构设计

Claude Code 源码解析 (4):多 Agent 协作的架构设计

导读: 这是 Claude Code 20 个功能特性源码解析系列的第 4 篇,深入分析 Agent 管理工具 (AgentTool) 的架构设计。


📋 目录

  1. 问题引入:为什么需要多 Agent 协作?
  2. [技术原理:Agent 管理的核心架构](#技术原理 agent-管理的核心架构)
  3. 设计思想:为什么这样设计
  4. 解决方案:完整实现详解
  5. OpenClaw 最佳实践
  6. 总结

问题引入:为什么需要多 Agent 协作?

痛点场景

场景 1:单一 Agent 能力有限

1
2
3
4
5
6
7
8
9
用户:"帮我开发一个完整的 Web 应用"

单一 Agent:
- 写前端 → 不擅长
- 写后端 → 还可以
- 写测试 → 不专业
- 部署 → 不熟悉

结果:每个环节都勉强能用,但不够专业

场景 2:上下文窗口限制

1
2
3
4
5
6
用户:"分析这个 10 万行代码的项目"

单一 Agent:
- 上下文窗口:128K tokens
- 项目大小:500K tokens
- 结果:无法完整理解项目

场景 3:长时间任务

1
2
3
4
5
6
用户:"重构整个项目的代码风格"

单一 Agent:
- 预计耗时:2 小时
- 实际执行:30 分钟后超时
- 结果:只完成了一半

核心问题

设计 AI 助手的 Agent 管理系统时,面临以下挑战:

  1. 能力边界问题

    • 单一 Agent 无法胜任所有任务
    • 如何根据任务类型选择合适的 Agent?
  2. 上下文限制问题

    • 单个 Agent 的上下文窗口有限
    • 如何分布式处理大任务?
  3. 协作效率问题

    • 多个 Agent 如何分工?
    • 如何避免重复工作?
  4. 状态同步问题

    • Agent 之间如何共享信息?
    • 如何保证一致性?

Claude Code 用 AgentTool + Coordinator 模式解决了这些问题。


技术原理:Agent 管理的核心架构

整体架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
┌─────────────────────────────────────────────────────────────┐
│ 用户请求 │
│ "帮我开发一个完整的 Web 应用" │
└─────────────────────┬───────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ Coordinator (协调器) │
│ - 任务分解 │
│ - Agent 分配 │
│ - 进度跟踪 │
│ - 结果聚合 │
└─────────────┬───────────────────────────────────────────────┘


┌─────────────────────────┐
│ 任务队列 │
│ ┌─────────────────┐ │
│ │ Task 1: 前端 │ │
│ │ Task 2: 后端 │ │
│ │ Task 3: 测试 │ │
│ │ Task 4: 部署 │ │
│ └─────────────────┘ │
└─────────────────────────┘

┌─────────┼─────────┬─────────┐
│ │ │ │
▼ ▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
│ Agent 1│ │ Agent 2│ │ Agent 3│ │ Agent 4│
│ 前端 │ │ 后端 │ │ 测试 │ │ 部署 │
│专家 │ │专家 │ │专家 │ │专家 │
└────────┘ └────────┘ └────────┘ └────────┘

Agent 定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface AgentDefinition {
// 基本信息
name: string;
description: string;

// 能力描述
capabilities: string[];

// 专用 Prompt
systemPrompt?: string;

// 模型配置
model?: string;

// 工具配置
allowedTools?: string[];
disallowedTools?: string[];

// 权限配置
permissions?: PermissionConfig;

// 状态
status: 'idle' | 'busy' | 'offline';
}

内置 Agent 示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const builtInAgents: AgentDefinition[] = [
{
name: 'plan-agent',
description: '计划专家,擅长任务分解和规划',
capabilities: ['task-planning', 'decomposition'],
systemPrompt: '你是一个专业的计划专家...',
model: 'opus',
allowedTools: ['task_create', 'task_list'],
},
{
name: 'code-agent',
description: '代码专家,擅长编写和审查代码',
capabilities: ['coding', 'code-review'],
systemPrompt: '你是一个专业的软件工程师...',
model: 'sonnet',
allowedTools: ['file_read', 'file_write', 'file_edit', 'bash'],
},
{
name: 'test-agent',
description: '测试专家,擅长编写测试用例',
capabilities: ['testing', 'qa'],
systemPrompt: '你是一个专业的测试工程师...',
model: 'sonnet',
allowedTools: ['file_read', 'file_write', 'bash'],
},
{
name: 'devops-agent',
description: '运维专家,擅长部署和监控',
capabilities: ['deployment', 'monitoring'],
systemPrompt: '你是一个专业的运维工程师...',
model: 'sonnet',
allowedTools: ['bash', 'task_create'],
},
];

任务分解算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
interface Task {
id: string;
description: string;
agent?: string; // 分配的 Agent
status: 'pending' | 'running' | 'completed' | 'failed';
result?: string;
dependencies?: string[]; // 依赖的其他任务
}

async function decomposeTask(
taskDescription: string,
context: AgentContext
): Promise<Task[]> {
// 使用 plan-agent 进行任务分解
const planAgent = getAgent('plan-agent');

const prompt = `
请将以下任务分解为可执行的子任务:

任务:${taskDescription}

要求:
1. 每个子任务应该是独立的
2. 标注每个子任务需要的专业技能
3. 标注子任务之间的依赖关系
4. 估计每个子任务的复杂度 (1-10)

返回 JSON 格式:
{
"subtasks": [
{
"description": "子任务描述",
"skill": "需要的技能",
"complexity": 5,
"dependencies": []
}
]
}
`;

const response = await planAgent.generate(prompt);
const plan = JSON.parse(response.content);

// 转换为 Task 对象
return plan.subtasks.map((subtask: any, index: number) => ({
id: `task-${index}`,
description: subtask.description,
status: 'pending',
dependencies: subtask.dependencies || [],
complexity: subtask.complexity,
requiredSkill: subtask.skill,
}));
}

Agent 分配算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function assignAgent(
task: Task,
agents: AgentDefinition[]
): string | null {
// 根据技能匹配
const skillMap: Record<string, string[]> = {
'frontend': ['code-agent'],
'backend': ['code-agent'],
'testing': ['test-agent'],
'deployment': ['devops-agent'],
'planning': ['plan-agent'],
};

const requiredAgents = skillMap[task.requiredSkill] || [];

// 找到空闲的 Agent
for (const agentName of requiredAgents) {
const agent = agents.find(a => a.name === agentName);
if (agent && agent.status === 'idle') {
return agentName;
}
}

// 如果没有空闲,返回第一个匹配的
if (requiredAgents.length > 0) {
return requiredAgents[0];
}

// 默认返回 code-agent
return 'code-agent';
}

并行执行引擎

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class TaskExecutor {
private runningTasks = new Map<string, Promise<any>>();
private completedTasks = new Map<string, any>();

async executeTasks(
tasks: Task[],
agents: AgentDefinition[]
): Promise<void> {
const pending = [...tasks];

while (pending.length > 0 || this.runningTasks.size > 0) {
// 1. 找出可以执行的任务 (依赖已满足)
const readyTasks = pending.filter(task =>
this.dependenciesSatisfied(task)
);

// 2. 分配 Agent 并启动
for (const task of readyTasks) {
const agentName = assignAgent(task, agents);
if (agentName) {
task.agent = agentName;
const promise = this.executeTask(task);
this.runningTasks.set(task.id, promise);

// 从 pending 移除
const index = pending.indexOf(task);
pending.splice(index, 1);
}
}

// 3. 等待至少一个任务完成
if (this.runningTasks.size > 0) {
const completed = await Promise.race(
Array.from(this.runningTasks.entries()).map(
async ([id, promise]) => {
const result = await promise;
return { id, result };
}
)
);

this.completedTasks.set(completed.id, completed.result);
this.runningTasks.delete(completed.id);

// 更新任务状态
const task = tasks.find(t => t.id === completed.id);
if (task) {
task.status = 'completed';
task.result = completed.result;
}
}
}
}

private dependenciesSatisfied(task: Task): boolean {
if (!task.dependencies) return true;

return task.dependencies.every(depId =>
this.completedTasks.has(depId)
);
}

private async executeTask(task: Task): Promise<any> {
const agent = getAgent(task.agent!);

const prompt = `
请完成以下任务:

${task.description}

上下文:
${this.getContext(task.dependencies || [])}
`;

return await agent.generate(prompt);
}

private getContext(dependencyIds: string[]): string {
return dependencyIds
.map(id => this.completedTasks.get(id))
.filter(Boolean)
.join('\n---\n');
}
}

状态同步机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class AgentStateManager {
private stateStore = new Map<string, AgentState>();
private listeners = new Set<StateListener>();

// 更新 Agent 状态
updateState(agentId: string, state: Partial<AgentState>): void {
const current = this.stateStore.get(agentId) || {};
const updated = { ...current, ...state };

this.stateStore.set(agentId, updated);
this.notifyListeners(agentId, updated);
}

// 获取 Agent 状态
getState(agentId: string): AgentState | undefined {
return this.stateStore.get(agentId);
}

// 获取所有 Agent 状态
getAllStates(): Map<string, AgentState> {
return new Map(this.stateStore);
}

// 订阅状态变化
subscribe(listener: StateListener): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}

private notifyListeners(agentId: string, state: AgentState): void {
for (const listener of this.listeners) {
listener(agentId, state);
}
}
}

interface AgentState {
status: 'idle' | 'busy' | 'offline';
currentTask?: string;
progress?: number;
lastActive?: Date;
contextTokens?: number;
}

结果聚合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function aggregateResults(
tasks: Task[],
aggregationStrategy: AggregationStrategy
): string {
switch (aggregationStrategy) {
case 'concat':
// 简单拼接
return tasks
.filter(t => t.status === 'completed')
.map(t => `## ${t.description}\n\n${t.result}`)
.join('\n\n');

case 'summary':
// AI 总结
return aiSummarize(tasks);

case 'structured':
// 结构化输出
return JSON.stringify({
tasks: tasks.map(t => ({
description: t.description,
status: t.status,
result: t.result,
})),
summary: generateSummary(tasks),
});
}
}

function aiSummarize(tasks: Task[]): string {
const allResults = tasks
.filter(t => t.status === 'completed')
.map(t => `${t.description}: ${t.result}`)
.join('\n');

const summaryAgent = getAgent('plan-agent');

return summaryAgent.generate(`
请总结以下任务的执行结果:

${allResults}

总结要求:
1. 概述完成的工作
2. 列出关键成果
3. 指出潜在问题
`);
}

设计思想:为什么这样设计

思想 1:专业分工,各司其职

问题: 单一 Agent 无法胜任所有任务。

解决: 按技能分工。

Agent 专长 工具 模型
plan-agent 任务分解、规划 task_* opus
code-agent 编码、审查 file_*, bash sonnet
test-agent 测试、QA file_*, bash sonnet
devops-agent 部署、监控 bash, task_* sonnet

设计智慧:

让专业的 Agent 做专业的事。

效果对比:

1
2
3
4
5
6
7
8
9
10
11
12
13
单一 Agent:
- 前端:60 分
- 后端:70 分
- 测试:50 分
- 部署:40 分
平均:55 分

多 Agent 协作:
- 前端专家:90 分
- 后端专家:90 分
- 测试专家:85 分
- 部署专家:85 分
平均:87.5 分

思想 2:任务分解,化整为零

问题: 大任务超出上下文窗口。

解决: 分解为小任务。

1
2
3
4
5
6
7
大任务:"开发一个完整的 Web 应用"
↓ 分解
Task 1: 设计数据库 schema
Task 2: 实现用户认证 API
Task 3: 实现前端登录页面
Task 4: 编写单元测试
Task 5: 部署到生产环境

分解原则:

  1. 独立性 - 每个子任务可以独立执行
  2. 可测试 - 每个子任务有明确的完成标准
  3. 依赖清晰 - 任务之间的依赖关系明确
  4. 大小适中 - 每个任务在上下文窗口内

思想 3:并行执行,提升效率

问题: 串行执行太慢。

解决: 并行执行独立任务。

1
2
3
4
5
6
7
8
9
10
11
串行执行:
Task 1 → Task 2 → Task 3 → Task 4
5 分钟 5 分钟 5 分钟 5 分钟
总计:20 分钟

并行执行 (无依赖):
Task 1 ┐
Task 2 ├─ 同时执行
Task 3 ┘
Task 4
总计:10 分钟 (Task 1-3 并行 5 分钟 + Task 4 5 分钟)

依赖感知调度:

1
2
3
4
5
6
7
8
9
// Task 2 依赖 Task 1
Task 1 ──────→ Task 2
↓ ↓
Task 3 ──────→ Task 4

调度顺序:
1. 启动 Task 1Task 3 (无依赖)
2. Task 1 完成后,启动 Task 2
3. Task 3 完成后,启动 Task 4

思想 4:状态透明,可追踪

问题: 不知道 Agent 在做什么。

解决: 实时状态同步。

1
2
3
4
5
6
interface AgentState {
status: 'idle' | 'busy' | 'offline';
currentTask?: string;
progress?: number; // 0-100
lastActive?: Date;
}

状态展示:

1
2
3
4
5
6
7
8
Agent 状态面板:

┌─────────────────────────────────────┐
│ plan-agent │ 🟢 空闲 │
│ code-agent │ 🟡 忙碌 (Task 2) 75% │
│ test-agent │ 🟢 空闲 │
│ devops-agent │ 🔴 离线 │
└─────────────────────────────────────┘

思想 5:结果聚合,统一输出

问题: 多个 Agent 的结果如何呈现?

解决: 智能聚合。

聚合策略:

策略 适用场景 说明
concat 简单任务 直接拼接结果
summary 复杂任务 AI 总结关键信息
structured 程序化场景 JSON 结构化输出

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
用户:"帮我开发一个 Web 应用"

聚合结果:

## 任务 1: 数据库设计
[plan-agent 完成]
设计了用户表、文章表、评论表...

## 任务 2: 后端 API
[code-agent 完成]
实现了用户认证、文章 CRUD...

## 任务 3: 前端页面
[code-agent 完成]
实现了登录页、首页、文章页...

## 总结
[plan-agent 总结]
已完成 Web 应用的核心功能,包括...
待完成:样式优化、性能调优...

解决方案:完整实现详解

AgentTool 核心实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
export class AgentTool extends Tool {
name = 'agent';
description = '管理和协作 Agent';

inputSchema = {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['list', 'create', 'delete', 'switch', 'task'],
description: '操作类型',
},
name: {
type: 'string',
description: 'Agent 名称',
},
task: {
type: 'string',
description: '任务描述',
},
config: {
type: 'object',
description: 'Agent 配置',
},
},
required: ['action'],
};

async execute(input: AgentInput, context: ToolContext): Promise<ToolResult> {
switch (input.action) {
case 'list':
return this.listAgents();

case 'create':
return this.createAgent(input.name!, input.config!);

case 'delete':
return this.deleteAgent(input.name!);

case 'switch':
return this.switchAgent(input.name!);

case 'task':
return this.executeTask(input.task!, context);

default:
return {
success: false,
error: `Unknown action: ${input.action}`,
};
}
}

private async executeTask(
taskDescription: string,
context: ToolContext
): Promise<ToolResult> {
// 1. 任务分解
const tasks = await decomposeTask(taskDescription, context);

// 2. 获取可用 Agent
const agents = await this.getAvailableAgents();

// 3. 分配 Agent
for (const task of tasks) {
task.agent = assignAgent(task, agents);
}

// 4. 执行任务
const executor = new TaskExecutor();
await executor.executeTasks(tasks, agents);

// 5. 聚合结果
const result = aggregateResults(tasks, 'summary');

return {
success: true,
result,
tasks: tasks.map(t => ({
id: t.id,
description: t.description,
status: t.status,
agent: t.agent,
})),
};
}
}

Coordinator 模式实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
export class Coordinator {
private agents: Map<string, Agent> = new Map();
private taskQueue: TaskQueue;
private stateManager: AgentStateManager;

constructor(config: CoordinatorConfig) {
this.taskQueue = new TaskQueue();
this.stateManager = new AgentStateManager();

// 初始化内置 Agent
this.initBuiltInAgents();
}

private initBuiltInAgents(): void {
const builtInAgents = [
{ name: 'plan-agent', role: 'planner' },
{ name: 'code-agent', role: 'developer' },
{ name: 'test-agent', role: 'tester' },
{ name: 'devops-agent', role: 'operator' },
];

for (const agentConfig of builtInAgents) {
const agent = new Agent(agentConfig);
this.agents.set(agentConfig.name, agent);
}
}

async executeTask(taskDescription: string): Promise<string> {
// 1. 使用 plan-agent 分解任务
const planAgent = this.agents.get('plan-agent')!;
const tasks = await planAgent.decompose(taskDescription);

// 2. 创建任务图 (处理依赖)
const taskGraph = this.buildTaskGraph(tasks);

// 3. 调度执行
const results = await this.scheduleTasks(taskGraph);

// 4. 聚合结果
return this.aggregateResults(results);
}

private buildTaskGraph(tasks: Task[]): TaskGraph {
const graph = new TaskGraph();

for (const task of tasks) {
graph.addNode(task);

// 添加依赖边
if (task.dependencies) {
for (const depId of task.dependencies) {
graph.addEdge(depId, task.id);
}
}
}

return graph;
}

private async scheduleTasks(graph: TaskGraph): Promise<Map<string, any>> {
const results = new Map<string, any>();
const inProgress = new Set<string>();

while (!graph.isComplete()) {
// 获取可执行的任务 (入度为 0)
const readyTasks = graph.getReadyTasks();

// 并行执行
const promises = readyTasks
.filter(task => !inProgress.has(task.id))
.map(async task => {
inProgress.add(task.id);

const agent = this.selectAgent(task);
const result = await agent.execute(task);

results.set(task.id, result);
graph.markComplete(task.id);
inProgress.delete(task.id);

return { taskId: task.id, result };
});

if (promises.length === 0) {
// 没有可执行的任务,等待
await this.waitForCompletion();
} else {
// 等待至少一个完成
await Promise.race(promises);
}
}

return results;
}

private selectAgent(task: Task): Agent {
// 根据任务类型选择 Agent
const skillMap: Record<string, string> = {
'planning': 'plan-agent',
'coding': 'code-agent',
'testing': 'test-agent',
'deployment': 'devops-agent',
};

const agentName = skillMap[task.type] || 'code-agent';
return this.agents.get(agentName)!;
}
}

Agent 定义配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# ~/.openclaw/config/agents.yaml

agents:
# 计划专家
- name: plan-agent
description: 任务分解和规划专家
system_prompt: |
你是一个专业的计划专家,擅长:
1. 将复杂任务分解为可执行的子任务
2. 识别任务之间的依赖关系
3. 评估任务复杂度和时间
model: opus
allowed_tools:
- task_create
- task_list
- task_update
max_concurrent_tasks: 5

# 代码专家
- name: code-agent
description: 软件开发专家
system_prompt: |
你是一个专业的软件工程师,擅长:
1. 编写高质量代码
2. 代码审查和优化
3. 架构设计
model: sonnet
allowed_tools:
- file_read
- file_write
- file_edit
- bash
- glob
- grep
max_concurrent_tasks: 3

# 测试专家
- name: test-agent
description: 测试和质量保证专家
system_prompt: |
你是一个专业的测试工程师,擅长:
1. 编写单元测试
2. 集成测试
3. 端到端测试
model: sonnet
allowed_tools:
- file_read
- file_write
- bash
max_concurrent_tasks: 3

# 运维专家
- name: devops-agent
description: 部署和运维专家
system_prompt: |
你是一个专业的运维工程师,擅长:
1. CI/CD 流程
2. 容器化部署
3. 监控和日志
model: sonnet
allowed_tools:
- bash
- task_create
max_concurrent_tasks: 2

自定义 Agent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 创建自定义 Agent
const customAgent = {
name: 'data-agent',
description: '数据处理专家',
systemPrompt: `
你是一个专业的数据工程师,擅长:
1. 数据清洗和转换
2. 数据分析
3. 数据可视化
`,
model: 'sonnet',
allowedTools: ['file_read', 'file_write', 'bash', 'python'],
permissions: {
allowedDirs: ['/data', '/tmp'],
maxFileSize: '1GB',
},
};

// 注册 Agent
await agentTool.execute({
action: 'create',
name: 'data-agent',
config: customAgent,
});

OpenClaw 最佳实践

实践 1:创建 Agent 配置文件

文件: ~/.openclaw/config/agents.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
agents:
- name: blog-agent
description: 博客写作助手
system_prompt: |
你是一个专业的技术博主,擅长:
1. 技术文章写作
2. 代码示例编写
3. 图表制作
model: sonnet
allowed_tools:
- file_write
- web_search
- web_fetch

- name: review-agent
description: 代码审查助手
system_prompt: |
你是一个资深的代码审查专家,擅长:
1. 发现代码问题
2. 提供改进建议
3. 最佳实践指导
model: opus
allowed_tools:
- file_read
- grep
- glob

实践 2:多 Agent 协作示例

1
2
3
4
5
6
7
8
# 创建多 Agent 任务
openclaw run agent --action task --task "
开发一个用户管理系统:
1. 设计数据库 schema
2. 实现 CRUD API
3. 编写单元测试
4. 创建前端页面
"

执行过程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[Coordinator] 接收任务:开发用户管理系统
[plan-agent] 分解任务为 4 个子任务
[Coordinator] 分配 Agent:
- Task 1 (数据库) → code-agent
- Task 2 (API) → code-agent
- Task 3 (测试) → test-agent
- Task 4 (前端) → code-agent

[Coordinator] 开始执行...
[code-agent] Task 1: 完成数据库设计
[code-agent] Task 2: 完成 API 实现
[test-agent] Task 3: 完成测试编写
[code-agent] Task 4: 完成前端页面

[plan-agent] 聚合结果,生成总结
[Coordinator] 任务完成!

实践 3:Agent 状态监控

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看所有 Agent 状态
openclaw run agent --action list

# 输出:
Agent 状态:

┌───────────────────────────────────────────┐
│ Agent │ 状态 │ 当前任务 │ 进度 │
├───────────────────────────────────────────┤
│ plan-agent │ 🟢 空闲 │ - │ - │
│ code-agent │ 🟡 忙碌 │ Task 2 │ 75% │
│ test-agent │ 🟢 空闲 │ - │ - │
│ devops-agent │ 🔴 离线 │ - │ - │
└───────────────────────────────────────────┘

实践 4:任务优先级管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ~/.openclaw/config/task-priority.yaml

priority_rules:
# 高优先级任务
- pattern: "*bug*"
priority: high
agent: code-agent

# 普通任务
- pattern: "*"
priority: normal
agent: auto

# 调度策略
scheduling:
# 高优先级任务插队
preemptive: true

# 最大并行任务数
max_parallel: 5

# 任务超时 (分钟)
timeout: 30

实践 5:结果审查工作流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 代码审查工作流
async function codeReviewWorkflow(prDescription: string): Promise<string> {
// 1. code-agent 分析代码
const codeAgent = getAgent('code-agent');
const analysis = await codeAgent.analyze(prDescription);

// 2. test-agent 检查测试覆盖
const testAgent = getAgent('test-agent');
const testCoverage = await testAgent.checkCoverage(prDescription);

// 3. review-agent 综合审查
const reviewAgent = getAgent('review-agent');
const review = await reviewAgent.review({
analysis,
testCoverage,
});

return review;
}

总结

核心要点

  1. 专业分工 - 不同 Agent 负责不同领域
  2. 任务分解 - 大任务拆分为小任务
  3. 并行执行 - 独立任务同时执行
  4. 状态同步 - 实时追踪 Agent 状态
  5. 结果聚合 - 智能整合多个结果

设计智慧

多 Agent 协作不是简单的任务分发,而是智能的团队协作。

Claude Code 的 Agent 管理设计告诉我们:

  • 专业分工提升质量
  • 任务分解突破限制
  • 并行执行提升效率
  • 状态透明建立信任

性能对比

场景 单一 Agent 多 Agent 协作 提升
Web 应用开发 60 分 87.5 分 46%
大项目分析 无法完成 完成
长时间任务 超时 完成

下一步

  • 配置内置 Agent
  • 创建自定义 Agent
  • 实现任务分解
  • 添加状态监控

系列文章:

  • [1] Bash 命令执行的安全艺术 (已发布)
  • [2] 差异编辑的设计艺术 (已发布)
  • [3] 文件搜索的底层原理 (已发布)
  • [4] 多 Agent 协作的架构设计 (本文)
  • [5] 技能系统的设计哲学 (待发布)

上一篇: Claude Code 源码解析 (3):文件搜索的底层原理


关于作者: John,OpenClaw 平台开发者,专注 AI 助手架构设计与实现。