首页 / 课程 / S06: Subagent Fork

S06: Subagent Fork 子智能体与分支

"Divide and conquer" -- 子 Agent 是并行处理的关键。

Harness 层: Subagent -- 任务分解与并行执行。

本章导图:子代理:父会话派生并行子会话,汇总结果回到主线。

🎯 问题

复杂任务需要:

  • 并行处理多个独立子任务
  • 隔离执行环境避免冲突
  • 分配不同模型节省成本
  • 长时间任务后台运行

单个 Agent Loop 无法满足这些需求。

💡 解决方案

Claude Code 实现了 Agent Tool,允许创建子 Agent:

+------------------+
|   Parent Agent   |
+--------+---------+
         |
    +----+----+----+
    |    |    |    |
    v    v    v    v
  Agent Agent Agent Agent
   (1)   (2)   (3)   (4)
    |    |    |    |
    +----+----+----+
         |
         v
    合并结果
                        

🔑 内置 Agent 类型

🌐

General Purpose

通用 Agent,完整工具访问

🔍

Explore

快速代码库探索 (Haiku)

📋

Plan

架构规划 Agent

🔀

Fork

继承父进程上下文

📐 Agent 定义

// 源码位置: src/tools/AgentTool/AgentTool.tsx

type AgentDefinition = {
  agentType: string          // 类型标识
  whenToUse: string          // 使用场景描述
  tools: string[]            // 可用工具列表
  maxTurns: number           // 最大轮次
  model: string | 'inherit'  // 模型选择
  permissionMode: PermissionMode
  getSystemPrompt: () => string
}

// Explore Agent 示例
const EXPLORE_AGENT: AgentDefinition = {
  agentType: 'Explore',
  whenToUse: 'Fast agent for codebase exploration',
  tools: ['Glob', 'Grep', 'Read'],
  maxTurns: 50,
  model: 'haiku',
  permissionMode: 'bubble',
}

🔒 隔离模式

worktree创建临时 Git worktree,文件系统隔离
remote在远程 CCR 环境运行
none共享当前目录(默认)