返回

Claude Code 源码分析 4:Agent 子代理系统实现

深入分析 Claude Code 的 Agent 子代理系统,包括子代理的创建、执行、通信、生命周期管理,以及 Team 多代理协作机制。这是 Claude Code 实现并行任务处理的核心。

本章概述

系列目录:Claude Code 源码分析系列索引

Claude Code 最强大的功能之一是子代理系统,它允许启动多个并行工作的 AI 代理(Agent),每个代理可以独立执行任务,并通过消息机制协作。

你将学到

  • ✅ 子代理的创建与生命周期管理
  • ✅ Agent 执行模式(同步/异步/fork)
  • ✅ Team 多代理协作机制
  • ✅ 子代理间通信(SendMessage)
  • ✅ 任务执行流程与状态管理

子代理系统概览

flowchart TB
    subgraph Parent["主代理 (Parent)"]
        A[Claude Code] --> B[AgentTool]
    end
    
    subgraph Agents["子代理 (Agents)"]
        B --> C1[Agent 1]
        B --> C2[Agent 2]
        B --> C3[Agent 3]
        B --> C4[...]
    end
    
    subgraph Team["Team 协作"]
        C1 <-->|SendMessage| C2
        C2 <-->|SendMessage| C3
        C1 --> D[Task List]
        C2 --> D
        C3 --> D
    end
    
    subgraph Execution["执行模式"]
        E1[同步执行] --> E2[等待完成]
        F1[异步执行] --> F2[后台运行]
        G1[Fork 隔离] --> G2[Worktree 隔离]
    end
    
    C1 -.-> E1
    C2 -.-> F1
    C3 -.-> G1

核心文件结构

src/
├── tools/AgentTool/              # AgentTool 实现
│   ├── AgentTool.tsx            # 主工具实现
│   ├── runAgent.ts              # 代理执行逻辑
│   ├── runAgent.ts              # 代理运行器
│   ├── built-in/                # 内置代理类型
│   │   ├── generalPurposeAgent.ts
│   │   ├── exploreAgent.ts
│   │   ├── plannerAgent.ts
│   │   └── executorAgent.ts
│   ├── loadAgentsDir.ts         # 代理定义加载
│   ├── forkSubagent.ts          # Fork 子代理
│   └── agentToolUtils.ts        # 工具函数
├── tasks/                        # 任务管理
│   ├── LocalAgentTask/          # 本地代理任务
│   ├── RemoteAgentTask/         # 远程代理任务
│   └── InProcessTeammateTask/   # 进程内队友任务
├── utils/swarm/                  # 团队管理
│   ├── teammateModel.ts         # 队友模型
│   ├── teammateInit.ts          # 队友初始化
│   ├── teamHelpers.ts           # 团队辅助
│   └── backends/                # 后端实现
└── utils/worktree.ts            # Worktree 管理

Agent 定义与类型

Agent 定义结构

// tools/AgentTool/loadAgentsDir.ts
export type AgentDefinition = {
  agentType: string           // 代理类型标识
  description: string         // 描述
  model?: string             // 指定模型
  tools: string[] | '*'      // 可用工具列表或全部
  mcpServers?: string[]      // MCP 服务器列表
  source: AgentSource        // 来源
  // ... 其他配置
}

内置代理类型

// tools/AgentTool/built-in/generalPurposeAgent.ts
export const GENERAL_PURPOSE_AGENT: AgentDefinition = {
  agentType: 'general-purpose',
  description: 'General purpose agent for researching complex questions',
  tools: ['*'],              // 可以使用所有工具
  model: 'sonnet',
  source: 'builtin'
}

// tools/AgentTool/built-in/exploreAgent.ts
export const EXPLORE_AGENT: AgentDefinition = {
  agentType: 'explore',
  description: 'Fast agent specialized for exploring codebases',
  tools: ['Glob', 'Grep', 'FileRead', 'Bash'],  // 有限工具集
  model: 'haiku',           // 使用更快的模型
  source: 'builtin'
}

// 其他内置代理:planner, executor, debugger, code-reviewer 等

AgentTool 调用流程

输入参数解析

// AgentTool.tsx:82-101
const baseInputSchema = z.object({
  description: z.string().describe('A short description of the task'),
  prompt: z.string().describe('The task for the agent to perform'),
  subagent_type: z.string().optional().describe('The type of agent to use'),
  model: z.enum(['sonnet', 'opus', 'haiku']).optional(),
  run_in_background: z.boolean().optional().describe('Run in background'),
  // 多代理参数
  name: z.string().optional().describe('Name for the agent'),
  team_name: z.string().optional().describe('Team name'),
  mode: permissionModeSchema().optional(),
  isolation: z.enum(['worktree']).optional(),
  cwd: z.string().optional()
});

Agent 创建流程

sequenceDiagram
    participant User as 用户
    participant Main as 主代理
    participant AgentTool as AgentTool
    participant Runner as runAgent
    participant Agent as 子代理
    
    User->>Main: 调用 Agent
    Main->>AgentTool: AgentTool.call(params)
    AgentTool->>AgentTool: 解析参数
    AgentTool->>AgentTool: 加载 Agent 定义
    AgentTool->>Runner: runAgent(agentDef, prompt)
    Runner->>Agent: 创建 Agent 上下文
    Agent->>Agent: 初始化工具集
    Agent->>Agent: 构建系统提示词
    Agent-->>Runner: Agent 实例
    Runner-->>AgentTool: Agent 会话
    AgentTool-->>Main: Agent 状态

执行模式

1. 同步执行(默认)

// AgentTool.tsx - 同步执行流程
export async function call(input: AgentToolInput) {
  // 创建 Agent
  const agent = await createAgent(input);
  
  // 同步执行,等待完成
  const result = await runAgent(agent);
  
  // 返回结果
  return result;
}

特点

  • 阻塞主代理
  • 等待子代理完成
  • 结果直接返回

2. 异步执行(后台)

// AgentTool.tsx - 后台执行
if (input.run_in_background) {
  // 注册异步任务
  const taskId = await registerAsyncAgent(agent);
  
  // 立即返回任务 ID
  return {
    type: 'background_task',
    taskId,
    message: 'Agent is running in background'
  };
}

特点

  • 不阻塞主代理
  • 后台运行
  • 通过 TaskOutputTool 获取结果

3. Fork 隔离执行

// forkSubagent.ts
export async function forkSubagent(params: ForkParams) {
  // 1. 创建 worktree
  const worktreePath = await createWorktree(params.name);
  
  // 2. 复制当前状态
  await copyStateToWorktree(worktreePath);
  
  // 3. 在新 worktree 中启动子代理
  const agent = await spawnForkedAgent({
    ...params,
    cwd: worktreePath
  });
  
  return agent;
}

特点

  • 使用 Git worktree 隔离
  • 不影响主工作区
  • 适合破坏性操作

Team 多代理协作

Team 创建

// tools/TeamCreateTool/TeamCreateTool.ts
export async function createTeam(params: TeamParams) {
  // 1. 创建团队配置
  const teamConfig = {
    name: params.team_name,
    description: params.description,
    maxAgents: params.max_agents || 5
  };
  
  // 2. 初始化团队状态
  await initializeTeam(teamConfig);
  
  // 3. 创建任务列表
  await createTaskList(teamConfig.name);
  
  return {
    type: 'success',
    teamId: teamConfig.name
  };
}

团队成员管理

// utils/swarm/teammateModel.ts
export type Teammate = {
  agentId: AgentId
  name: string
  model: string
  tools: string[]
  status: 'idle' | 'working' | 'completed' | 'error'
  task?: Task
  lastMessage?: Message
}

export type Team = {
  name: string
  members: Map<string, Teammate>
  taskList: TaskList
  createdAt: Date
}

消息通信机制

// tools/SendMessageTool/SendMessageTool.ts
export async function sendMessage(params: SendMessageParams) {
  const { to, message } = params;
  
  // 1. 查找目标代理
  const target = findAgent(to);
  if (!target) {
    throw new Error(`Agent ${to} not found`);
  }
  
  // 2. 发送消息
  await deliverMessage(target.agentId, {
    from: getCurrentAgentId(),
    content: message,
    timestamp: Date.now()
  });
  
  return { type: 'success' };
}

Team 协作流程

sequenceDiagram
    participant User as 用户
    participant Leader as Team Lead
    participant T1 as Agent 1
    participant T2 as Agent 2
    participant T3 as Agent 3
    participant Tasks as Task List
    
    User->>Leader: 创建 Team
    Leader->>Tasks: 初始化任务列表
    
    Leader->>T1: 分配任务 1
    Leader->>T2: 分配任务 2
    Leader->>T3: 分配任务 3
    
    par 并行执行
        T1->>T1: 执行任务 1
        T2->>T2: 执行任务 2
        T3->>T3: 执行任务 3
    end
    
    T1->>T2: SendMessage(需要协作)
    T2-->>T1: 返回结果
    
    T1->>Tasks: 标记任务 1 完成
    T2->>Tasks: 标记任务 2 完成
    T3->>Tasks: 标记任务 3 完成
    
    Leader->>Leader: 检查所有任务完成
    Leader-->>User: 返回汇总结果

任务管理与状态同步

任务列表

// utils/tasks.ts
export type Task = {
  id: string
  content: string
  status: TaskStatus
  owner?: AgentId
  createdAt: Date
  updatedAt: Date
}

export type TaskList = {
  id: string
  tasks: Task[]
  updatedAt: Date
}

export const TASK_STATUSES = {
  PENDING: 'pending',
  IN_PROGRESS: 'in_progress',
  COMPLETED: 'completed',
  BLOCKED: 'blocked',
  CANCELLED: 'cancelled'
} as const;

任务状态更新

// tools/TodoWriteTool/TodoWriteTool.ts
export async function updateTasks(todos: Todo[]) {
  const taskList = await loadTaskList();
  
  for (const todo of todos) {
    const existing = taskList.tasks.find(t => t.id === todo.id);
    if (existing) {
      existing.status = todo.status;
      existing.updatedAt = new Date();
    } else {
      taskList.tasks.push({
        id: todo.id,
        content: todo.content,
        status: todo.status,
        createdAt: new Date(),
        updatedAt: new Date()
      });
    }
  }
  
  await saveTaskList(taskList);
  return { type: 'success' };
}

子代理生命周期

生命周期阶段

flowchart TB
    subgraph Lifecycle["Agent 生命周期"]
        A[初始化] --> B{执行模式}
        B -->|同步| C[同步执行]
        B -->|异步| D[异步注册]
        B -->|Fork| E[Fork 创建]
        
        C --> F[对话循环]
        D --> F
        E --> F
        
        F --> G{完成条件}
        G -->|工具调用| H[执行工具]
        H --> F
        G -->|结果返回| I[完成]
        G -->|错误| J[错误处理]
        
        J --> K[重试/终止]
        I --> L[清理资源]
        K --> L
    end

对话循环实现

// runAgent.ts - 简化示意
export async function runAgent(params: RunAgentParams) {
  const messages: Message[] = [];
  let isComplete = false;
  
  // 添加系统提示词
  messages.push({
    role: 'system',
    content: params.systemPrompt
  });
  
  // 添加用户任务
  messages.push({
    role: 'user',
    content: params.prompt
  });
  
  while (!isComplete) {
    // 调用 Claude API
    const response = await callClaudeAPI({
      messages,
      tools: params.tools,
      model: params.model
    });
    
    // 处理响应
    if (response.tool_calls) {
      for (const toolCall of response.tool_calls) {
        // 执行工具
        const result = await executeTool(toolCall);
        
        // 添加结果到消息
        messages.push(toolCallToMessage(toolCall));
        messages.push(toolResultToMessage(result));
      }
    } else {
      // 代理完成,返回结果
      isComplete = true;
      return {
        type: 'success',
        result: response.content
      };
    }
  }
}

权限与隔离

Worktree 隔离

// utils/worktree.ts
export async function createAgentWorktree(agentName: string) {
  // 1. 创建 worktree 目录
  const worktreePath = `.claude/worktrees/${agentName}`;
  
  // 2. 使用 git worktree 创建隔离副本
  await exec(`git worktree add ${worktreePath} -b ${agentName}`);
  
  // 3. 复制必要配置
  await copyFile('.env', `${worktreePath}/.env`);
  
  return worktreePath;
}

export async function removeAgentWorktree(worktreePath: string) {
  // 清理 worktree
  await exec(`git worktree remove ${worktreePath}`);
}

权限模式

// utils/permissions/PermissionMode.ts
export const PERMISSION_MODES = {
  AUTO: 'auto',           // 自动允许安全操作
  PLAN: 'plan',           // 计划模式需批准
  MANUAL: 'manual',       // 所有操作需确认
  BYPASS: 'bypass'        // 绕过所有检查(危险)
} as const;

export type PermissionMode = typeof PERMISSION_MODES[keyof typeof PERMISSION_MODES];

最佳实践

1. Agent 选择策略

// ✅ 根据任务选择合适代理
const agentSelection = {
  'explore': '快速代码探索,使用 haiku',
  'plan': '复杂规划任务,使用 opus',
  'execute': '代码实现,使用 sonnet',
  'debug': '调试分析,使用 sonnet'
};

2. Team 协作模式

// ✅ 有效的 Team 协作
const workflow = {
  // 1. 创建 Team
  team: await createTeam({ name: 'feature-team' }),
  
  // 2. 分配任务
  tasks: [
    { agent: 'explore', task: '分析代码库' },
    { agent: 'plan', task: '制定计划' },
    { agent: 'execute', task: '实现功能' }
  ],
  
  // 3. 并行执行
  // 4. 汇总结果
};

3. 错误处理

// ✅ 健壮的错误处理
try {
  const result = await runAgent(agent);
  return result;
} catch (error) {
  if (error instanceof AgentTimeoutError) {
    // 超时处理
    return await handleTimeout(agent);
  }
  if (error instanceof AgentError) {
    // 代理错误
    return await handleAgentError(agent, error);
  }
  throw error;
}

小结

本章深入分析了 Claude Code 的 Agent 子代理系统:

核心概念

概念 说明 应用场景
Agent 子代理实例 独立任务执行
Team 多代理协作组 复杂任务分解
SendMessage 代理间通信 协作与数据传递
Worktree Git 隔离 安全隔离执行
Fork 隔离模式 破坏性操作

架构优势

  1. 并行执行 - 多个 Agent 同时工作
  2. 安全隔离 - Worktree 保证主分支安全
  3. 灵活通信 - SendMessage 支持协作
  4. 类型安全 - TypeScript 类型保障

学习收获

  • 🎯 多代理设计 - Team 协作模式
  • 🔄 并发控制 - 同步/异步/fork 模式
  • 🛡️ 隔离机制 - Worktree 安全实践
  • 📡 通信机制 - Agent 间消息传递

系列导航

参考资源