docs: add multi-agent system documentation with architecture diagrams
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@ -34,6 +34,7 @@ A **locally runnable version** repaired from the leaked Claude Code source, with
|
||||
- Custom API endpoint and model support ([Third-Party Models Guide](docs/guide/third-party-models.en.md))
|
||||
- **Computer Use desktop control** — [Guide](docs/features/computer-use.en.md)
|
||||
- **Memory System** (cross-session persistent memory) — [Usage Guide](docs/memory/01-usage-guide.md)
|
||||
- **Multi-Agent System** (agent orchestration, parallel tasks, Teams collaboration) — [Usage Guide](docs/agent/01-usage-guide.md) | [Implementation](docs/agent/02-implementation.md)
|
||||
- Fallback Recovery CLI mode (`CLAUDE_CODE_FORCE_RECOVERY_CLI=1 ./bin/claude-haha`)
|
||||
|
||||
---
|
||||
@ -135,6 +136,7 @@ export PATH="$HOME/path/to/claude-code-haha/bin:$PATH"
|
||||
| [Third-Party Models](docs/guide/third-party-models.en.md) | Using OpenAI / DeepSeek / Ollama and other non-Anthropic models |
|
||||
| [Computer Use](docs/features/computer-use.en.md) | Desktop control (screenshots, mouse, keyboard) |
|
||||
| [Memory System](docs/memory/01-usage-guide.md) | Cross-session persistent memory usage and implementation |
|
||||
| [Multi-Agent System](docs/agent/01-usage-guide.md) | Agent orchestration, parallel tasks and Teams collaboration |
|
||||
| [Global Usage](docs/guide/global-usage.en.md) | Run claude-haha from any directory |
|
||||
| [FAQ](docs/guide/faq.en.md) | Common error troubleshooting |
|
||||
| [Source Fixes](docs/reference/fixes.en.md) | Fixes compared with the original leaked source |
|
||||
|
||||
@ -34,6 +34,7 @@
|
||||
- 支持自定义 API 端点和模型([第三方模型使用指南](docs/guide/third-party-models.md))
|
||||
- **Computer Use 桌面控制** — [使用指南](docs/features/computer-use.md)
|
||||
- **记忆系统**(跨会话持久化记忆)— [使用指南](docs/memory/01-usage-guide.md)
|
||||
- **多 Agent 系统**(多代理编排、并行任务、Teams 协作)— [使用指南](docs/agent/01-usage-guide.md) | [实现原理](docs/agent/02-implementation.md)
|
||||
- 降级 Recovery CLI 模式(`CLAUDE_CODE_FORCE_RECOVERY_CLI=1 ./bin/claude-haha`)
|
||||
|
||||
---
|
||||
@ -135,6 +136,7 @@ export PATH="$HOME/path/to/claude-code-haha/bin:$PATH"
|
||||
| [第三方模型](docs/guide/third-party-models.md) | 接入 OpenAI / DeepSeek / Ollama 等非 Anthropic 模型 |
|
||||
| [Computer Use](docs/features/computer-use.md) | 桌面控制功能(截屏、鼠标、键盘) |
|
||||
| [记忆系统](docs/memory/01-usage-guide.md) | 跨会话持久化记忆的使用与实现 |
|
||||
| [多 Agent 系统](docs/agent/01-usage-guide.md) | 多代理编排、并行任务执行与 Teams 协作 |
|
||||
| [全局使用](docs/guide/global-usage.md) | 在任意目录启动 claude-haha |
|
||||
| [常见问题](docs/guide/faq.md) | 常见错误排查 |
|
||||
| [源码修复记录](docs/reference/fixes.md) | 相对于原始泄露源码的修复内容 |
|
||||
|
||||
439
docs/agent/01-usage-guide.md
Normal file
@ -0,0 +1,439 @@
|
||||
# Claude Code 多 Agent 系统 — 使用指南
|
||||
|
||||
> 让 Claude Code 同时调度多个专业代理,并行处理复杂任务。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 一、什么是多 Agent 系统?
|
||||
|
||||
Claude Code 的多 Agent 系统是一套**智能任务编排框架**,让主代理能够生成多个专业化的子代理(Subagent),各自独立执行不同的任务,最终将结果汇总给用户。
|
||||
|
||||
核心理念:**把大任务拆分为多个专业小任务,并行执行,提高效率。**
|
||||
|
||||
| 场景 | 传统方式 | 多 Agent 方式 |
|
||||
|------|----------|---------------|
|
||||
| 调研 5 个模块的架构 | 逐个串行探索 | 5 个 Explore agent 并行扫描 |
|
||||
| 实现 + 测试 + 文档 | 顺序完成 | Team 成员各自负责一块 |
|
||||
| 代码审查 | 单线程逐文件看 | 多个 reviewer 并行审查 |
|
||||
| 调试复杂 bug | 一个假设一个假设试 | 多个 debugger 并行验证 |
|
||||
|
||||
---
|
||||
|
||||
## 二、六种内置 Agent
|
||||
|
||||

|
||||
|
||||
Claude Code 内置了 6 种专业代理,每种都有特定的工具池和适用场景:
|
||||
|
||||
### 1. general-purpose(通用代理)
|
||||
|
||||
**适用场景**:复杂的多步骤研究、代码搜索、需要完整工具访问的任务。
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "调研认证模块",
|
||||
prompt: "分析 src/auth/ 下所有文件的认证流程...",
|
||||
subagent_type: "general-purpose"
|
||||
})
|
||||
```
|
||||
|
||||
- **工具池**:全部工具(`*`)
|
||||
- **模型**:继承父代理
|
||||
- **特点**:万能型,不确定用哪个 agent 时选它
|
||||
|
||||
### 2. Explore(探索代理)
|
||||
|
||||
**适用场景**:快速搜索文件、搜索代码模式、回答代码库结构问题。
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "搜索 API 端点",
|
||||
prompt: "找到所有 REST API 端点的定义...",
|
||||
subagent_type: "Explore"
|
||||
})
|
||||
```
|
||||
|
||||
- **工具池**:只读工具(Glob、Grep、Read、Bash)
|
||||
- **模型**:Haiku(快速低成本)
|
||||
- **特点**:不能修改文件,速度快,适合调研
|
||||
|
||||
### 3. Plan(规划代理)
|
||||
|
||||
**适用场景**:设计实现方案、分析架构权衡、生成分步计划。
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "规划重构方案",
|
||||
prompt: "设计将 monolith 拆分为微服务的方案...",
|
||||
subagent_type: "Plan"
|
||||
})
|
||||
```
|
||||
|
||||
- **工具池**:只读工具(同 Explore)
|
||||
- **模型**:继承父代理(需要强推理能力)
|
||||
- **特点**:输出结构化计划,包含关键文件和依赖分析
|
||||
|
||||
### 4. verification(验证代理)
|
||||
|
||||
**适用场景**:独立验证实现是否正确,运行测试,边界检查。
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "验证登录功能",
|
||||
prompt: "验证新实现的登录功能是否正确...",
|
||||
subagent_type: "verification"
|
||||
})
|
||||
```
|
||||
|
||||
- **工具池**:只读工具
|
||||
- **模型**:继承父代理
|
||||
- **特点**:始终在后台运行,输出 PASS/FAIL/PARTIAL 判定,红色标识
|
||||
|
||||
### 5. claude-code-guide(指南代理)
|
||||
|
||||
**适用场景**:回答关于 Claude Code、Agent SDK、Claude API 的问题。
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "查询 Claude API 用法",
|
||||
prompt: "如何使用 tool_use 功能...",
|
||||
subagent_type: "claude-code-guide"
|
||||
})
|
||||
```
|
||||
|
||||
- **工具池**:Bash、Read、WebFetch、WebSearch
|
||||
- **模型**:Haiku
|
||||
- **特点**:专注文档查询,dontAsk 权限模式
|
||||
|
||||
### 6. statusline-setup(状态栏配置代理)
|
||||
|
||||
**适用场景**:配置 Claude Code 状态栏显示。
|
||||
|
||||
- **工具池**:仅 Read + Edit
|
||||
- **模型**:Sonnet
|
||||
- **特点**:高度专业化,范围极小
|
||||
|
||||
### Agent 类型对比表
|
||||
|
||||
| Agent | 读写 | 工具池 | 模型 | 用途 |
|
||||
|-------|------|--------|------|------|
|
||||
| general-purpose | 读写 | 全部 | 继承 | 通用任务 |
|
||||
| Explore | 只读 | 搜索+读取 | Haiku | 快速探索 |
|
||||
| Plan | 只读 | 搜索+读取 | 继承 | 架构规划 |
|
||||
| verification | 只读 | 搜索+读取 | 继承 | 独立验证 |
|
||||
| claude-code-guide | 只读 | 搜索+网络 | Haiku | 文档指南 |
|
||||
| statusline-setup | 读写 | Read+Edit | Sonnet | 状态栏配置 |
|
||||
|
||||
---
|
||||
|
||||
## 三、如何生成 Agent
|
||||
|
||||
### 基本参数
|
||||
|
||||
Agent 工具接受以下参数:
|
||||
|
||||
| 参数 | 类型 | 必需 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `description` | string | 是 | 3-5 词任务简述 |
|
||||
| `prompt` | string | 是 | 完整的任务描述 |
|
||||
| `subagent_type` | string | 否 | Agent 类型(见上表) |
|
||||
| `model` | string | 否 | 模型覆盖:sonnet/opus/haiku |
|
||||
| `run_in_background` | boolean | 否 | 是否后台运行 |
|
||||
| `name` | string | 否 | 命名后可通过 SendMessage 寻址 |
|
||||
| `team_name` | string | 否 | 加入指定团队 |
|
||||
| `mode` | string | 否 | 权限模式 |
|
||||
| `isolation` | string | 否 | 隔离模式:worktree |
|
||||
|
||||
### 前台同步执行(默认)
|
||||
|
||||
最简单的用法,Agent 执行完毕后返回结果:
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "分析错误日志",
|
||||
prompt: "读取 logs/ 下最近的错误日志,总结常见错误模式"
|
||||
})
|
||||
```
|
||||
|
||||
主代理会等待子代理完成,然后收到结果继续工作。
|
||||
|
||||
### 后台异步执行
|
||||
|
||||
适合耗时任务,主代理可以继续做其他事情:
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "全面代码审查",
|
||||
prompt: "审查 src/ 下所有 TypeScript 文件的代码质量...",
|
||||
run_in_background: true
|
||||
})
|
||||
```
|
||||
|
||||
- Agent 立即返回 `async_launched` 状态和 taskId
|
||||
- 主代理继续工作,不需要等待
|
||||
- Agent 完成后自动收到 `<task-notification>` 通知
|
||||
- 通知包含任务状态、输出文件路径和结果摘要
|
||||
|
||||
### 并行生成多个 Agent
|
||||
|
||||
在一条消息中生成多个独立的 Agent,实现真正的并行:
|
||||
|
||||
```
|
||||
// 同时启动 3 个探索 agent
|
||||
Agent({ description: "探索前端", prompt: "...", subagent_type: "Explore", run_in_background: true })
|
||||
Agent({ description: "探索后端", prompt: "...", subagent_type: "Explore", run_in_background: true })
|
||||
Agent({ description: "探索数据库", prompt: "...", subagent_type: "Explore", run_in_background: true })
|
||||
```
|
||||
|
||||
### Worktree 隔离
|
||||
|
||||
让 Agent 在独立的 git worktree 中工作,不影响主工作区:
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "实验性重构",
|
||||
prompt: "尝试将模块 X 重构为...",
|
||||
isolation: "worktree"
|
||||
})
|
||||
```
|
||||
|
||||
- 自动创建 git worktree(独立分支)
|
||||
- Agent 在隔离环境中自由修改文件
|
||||
- 完成后如有改动,返回 worktree 路径和分支名
|
||||
- 无改动则自动清理
|
||||
|
||||
---
|
||||
|
||||
## 四、后台任务管理
|
||||
|
||||

|
||||
|
||||
### 任务状态
|
||||
|
||||
后台 Agent 有四种状态:
|
||||
|
||||
| 状态 | 说明 |
|
||||
|------|------|
|
||||
| `running` | 正在执行中 |
|
||||
| `completed` | 执行成功 |
|
||||
| `failed` | 执行失败 |
|
||||
| `killed` | 被手动终止 |
|
||||
|
||||
### 进度追踪
|
||||
|
||||
后台 Agent 的进度实时更新:
|
||||
|
||||
- **Token 消耗**:输入/输出 token 计数
|
||||
- **工具使用**:已使用的工具次数
|
||||
- **最近活动**:最近 5 个工具调用描述(循环缓冲区)
|
||||
- **最后活动时间**:用于检测卡住的任务
|
||||
|
||||
### 完成通知
|
||||
|
||||
当后台 Agent 完成时,主代理收到 XML 格式的通知:
|
||||
|
||||
```xml
|
||||
<task-notification>
|
||||
<task-id>abc123</task-id>
|
||||
<status>completed</status>
|
||||
<summary>Agent "探索前端" completed</summary>
|
||||
<output-file>~/.claude/temp/.../tasks/abc123.output</output-file>
|
||||
</task-notification>
|
||||
```
|
||||
|
||||
### 自动后台化
|
||||
|
||||
当 `tengu_auto_background_agents` 特性开启时,前台 Agent 运行超过 **120 秒**会自动转为后台执行,释放主代理继续工作。
|
||||
|
||||
---
|
||||
|
||||
## 五、Agent Teams — 多代理协作
|
||||
|
||||

|
||||
|
||||
Agent Teams 是更高级的多代理协作模式,多个代理以团队形式工作,通过消息通信协调任务。
|
||||
|
||||
### 创建团队
|
||||
|
||||
```
|
||||
TeamCreate({
|
||||
team_name: "feature-team",
|
||||
description: "开发用户认证功能"
|
||||
})
|
||||
```
|
||||
|
||||
团队创建后:
|
||||
- 生成团队配置文件:`~/.claude/teams/{team_name}/config.json`
|
||||
- 创建共享任务目录:`~/.claude/tasks/{team_name}/`
|
||||
- 当前代理自动成为 **Team Lead**(团队负责人)
|
||||
|
||||
### 添加团队成员
|
||||
|
||||
通过 Agent 工具指定 `name` 和 `team_name` 生成队友:
|
||||
|
||||
```
|
||||
Agent({
|
||||
description: "前端开发",
|
||||
prompt: "负责实现登录页面的 React 组件...",
|
||||
name: "frontend-dev",
|
||||
team_name: "feature-team"
|
||||
})
|
||||
|
||||
Agent({
|
||||
description: "后端开发",
|
||||
prompt: "负责实现认证 API 端点...",
|
||||
name: "backend-dev",
|
||||
team_name: "feature-team"
|
||||
})
|
||||
```
|
||||
|
||||
### 队友通信
|
||||
|
||||
通过 SendMessage 工具发送消息:
|
||||
|
||||
```
|
||||
// 发送给特定队友
|
||||
SendMessage({
|
||||
to: "frontend-dev",
|
||||
message: "API 接口已就绪,格式是...",
|
||||
summary: "通知 API 接口格式"
|
||||
})
|
||||
|
||||
// 广播给所有队友
|
||||
SendMessage({
|
||||
to: "*",
|
||||
message: "大家暂停,需求变更了...",
|
||||
summary: "广播需求变更"
|
||||
})
|
||||
```
|
||||
|
||||
### 关停协调
|
||||
|
||||
当任务完成后,Team Lead 请求队友关停:
|
||||
|
||||
```
|
||||
// 1. 发送关停请求
|
||||
SendMessage({
|
||||
to: "frontend-dev",
|
||||
message: { type: "shutdown_request", reason: "任务已完成" }
|
||||
})
|
||||
|
||||
// 2. 队友回复批准
|
||||
SendMessage({
|
||||
to: "team-lead",
|
||||
message: { type: "shutdown_response", request_id: "...", approve: true }
|
||||
})
|
||||
|
||||
// 3. 所有队友关停后,清理团队
|
||||
TeamDelete()
|
||||
```
|
||||
|
||||
### 执行后端
|
||||
|
||||
Agent Teams 支持两种执行后端:
|
||||
|
||||
| 后端 | 说明 | 适用场景 |
|
||||
|------|------|----------|
|
||||
| **in-process** | 同进程运行,AsyncLocalStorage 隔离 | 默认模式,轻量高效 |
|
||||
| **tmux** | 独立 tmux pane 运行 | 需要独立终端视图 |
|
||||
| **iTerm2** | 独立 iTerm2 窗口运行 | macOS iTerm2 用户 |
|
||||
|
||||
---
|
||||
|
||||
## 六、自定义 Agent
|
||||
|
||||
除了内置 Agent,你还可以创建自己的专业代理。
|
||||
|
||||
### 定义格式
|
||||
|
||||
在 `.claude/agents/` 目录下创建 `.md` 文件:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: code-reviewer
|
||||
description: 专业代码审查代理
|
||||
tools:
|
||||
- Read
|
||||
- Grep
|
||||
- Glob
|
||||
- Bash
|
||||
model: sonnet
|
||||
permissionMode: dontAsk
|
||||
maxTurns: 10
|
||||
---
|
||||
|
||||
你是一个专业的代码审查员。请检查以下方面:
|
||||
|
||||
1. 代码质量和可读性
|
||||
2. 潜在的安全漏洞
|
||||
3. 性能问题
|
||||
4. 最佳实践遵循
|
||||
```
|
||||
|
||||
### 可配置字段
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `name` | string | Agent 类型名称 |
|
||||
| `description` | string | 何时使用的说明 |
|
||||
| `tools` | string[] | 允许的工具列表(`['*']` 表示全部) |
|
||||
| `disallowedTools` | string[] | 禁止的工具列表 |
|
||||
| `model` | string | 使用的模型(sonnet/opus/haiku/inherit) |
|
||||
| `permissionMode` | string | 权限模式 |
|
||||
| `maxTurns` | number | 最大对话轮数 |
|
||||
| `mcpServers` | object[] | 需要的 MCP 服务器 |
|
||||
| `hooks` | object | Agent 特定的钩子 |
|
||||
| `skills` | string[] | 可使用的技能 |
|
||||
| `memory` | string | 记忆作用域(user/project/local) |
|
||||
| `isolation` | string | 隔离模式(worktree/remote) |
|
||||
| `background` | boolean | 是否默认后台运行 |
|
||||
|
||||
### 加载优先级
|
||||
|
||||
自定义 Agent 的加载遵循优先级:
|
||||
|
||||
1. **内置 Agent**(built-in)— 系统预定义
|
||||
2. **插件 Agent**(plugin)— 通过插件注册
|
||||
3. **用户 Agent**(user)— `~/.claude/agents/`
|
||||
4. **项目 Agent**(project)— `.claude/agents/`(项目级)
|
||||
5. **标记 Agent**(flag)— 通过 API 注册
|
||||
6. **策略 Agent**(policy)— 组织策略
|
||||
|
||||
同名 Agent 按优先级覆盖。
|
||||
|
||||
---
|
||||
|
||||
## 七、权限模式
|
||||
|
||||
每个 Agent 可以设置不同的权限模式:
|
||||
|
||||
| 模式 | 说明 |
|
||||
|------|------|
|
||||
| `default` | 正常权限请求,需要用户确认 |
|
||||
| `plan` | 所有操作需要显式审批 |
|
||||
| `acceptEdits` | 自动接受文件编辑,其他操作需确认 |
|
||||
| `bypassPermissions` | 跳过所有权限检查 |
|
||||
| `dontAsk` | 拒绝所有未预批准的操作 |
|
||||
| `auto` | AI 驱动的权限分类(仅 Ant 内部) |
|
||||
| `bubble` | 权限提示冒泡到父代理终端 |
|
||||
|
||||
---
|
||||
|
||||
## 八、快速参考
|
||||
|
||||
| 操作 | 方法 |
|
||||
|------|------|
|
||||
| 生成子代理 | `Agent({ prompt: "...", subagent_type: "Explore" })` |
|
||||
| 后台运行 | `Agent({ ..., run_in_background: true })` |
|
||||
| 并行生成 | 单条消息中发送多个 Agent 调用 |
|
||||
| Worktree 隔离 | `Agent({ ..., isolation: "worktree" })` |
|
||||
| 创建团队 | `TeamCreate({ team_name: "..." })` |
|
||||
| 发送消息 | `SendMessage({ to: "name", message: "..." })` |
|
||||
| 广播消息 | `SendMessage({ to: "*", message: "..." })` |
|
||||
| 请求关停 | `SendMessage({ to: "name", message: { type: "shutdown_request" } })` |
|
||||
| 删除团队 | `TeamDelete()` |
|
||||
| 自定义 Agent | 在 `.claude/agents/*.md` 创建定义文件 |
|
||||
| 指定模型 | `Agent({ ..., model: "haiku" })` |
|
||||
| 命名 Agent | `Agent({ ..., name: "researcher" })` |
|
||||
848
docs/agent/02-implementation.md
Normal file
@ -0,0 +1,848 @@
|
||||
# Claude Code 多 Agent 系统 — 实现原理
|
||||
|
||||
> 深入剖析多 Agent 编排的架构设计、生成流程、上下文传递和协作机制。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 一、架构总览
|
||||
|
||||
Claude Code 的多 Agent 系统由以下核心模块组成:
|
||||
|
||||
### 5 大核心模块
|
||||
|
||||
| 模块 | 职责 | 关键文件 |
|
||||
|------|------|----------|
|
||||
| **Agent Tool** | 主入口,路由分发,参数解析 | `src/tools/AgentTool/AgentTool.tsx` |
|
||||
| **执行引擎** | Agent 生命周期管理,查询循环 | `src/tools/AgentTool/runAgent.ts` |
|
||||
| **上下文管理** | 系统提示词构建,缓存安全参数 | `src/utils/forkedAgent.ts` |
|
||||
| **任务系统** | 状态追踪,进度更新,通知队列 | `src/tasks/LocalAgentTask/` |
|
||||
| **Swarm 基础设施** | 团队管理,邮箱通信,权限同步 | `src/utils/swarm/` |
|
||||
|
||||
### 5 大 Agent 类别
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Agent Tool │
|
||||
│ (入口 & 路由分发) │
|
||||
├───────────┬───────────┬───────────┬─────────────┤
|
||||
│ Subagent │ Fork │ Teammate │ Remote │
|
||||
│ (子代理) │ (分叉) │ (队友) │ (远程) │
|
||||
│ │ │ │ │
|
||||
│ 独立上下文 │ 继承上下文 │ 团队协作 │ CCR 环境 │
|
||||
│ 按类型过滤 │ 缓存共享 │ 邮箱通信 │ 远程执行 │
|
||||
│ 工具池 │ 字节一致 │ 权限同步 │ 轮询结果 │
|
||||
└───────────┴───────────┴───────────┴─────────────┘
|
||||
│
|
||||
┌─────┴─────┐
|
||||
│ DreamTask │
|
||||
│ (记忆整合) │
|
||||
│ 定时后台 │
|
||||
└───────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、Agent 生成流程 — 四条路径
|
||||
|
||||
### 入口:`AgentTool.call()`
|
||||
|
||||
`src/tools/AgentTool/AgentTool.tsx` 中的 `call()` 函数是所有 Agent 生成的入口。根据输入参数,路由到四条不同的生成路径:
|
||||
|
||||
```
|
||||
AgentTool.call(input)
|
||||
│
|
||||
├─ team_name + name? ──────→ 路径1: spawnTeammate()
|
||||
│
|
||||
├─ run_in_background? ────→ 路径2: registerAsyncAgent()
|
||||
│ └─ agent.background?
|
||||
│
|
||||
├─ 省略 subagent_type? ───→ 路径3: Fork (buildForkedMessages())
|
||||
│ └─ fork 实验开启?
|
||||
│
|
||||
└─ 默认 ───────────────────→ 路径4: runAgent() 同步执行
|
||||
```
|
||||
|
||||
### 路径 1:Teammate 生成
|
||||
|
||||
**触发条件**:`team_name` 和 `name` 同时存在
|
||||
|
||||
**入口函数**:`spawnTeammate()` — `src/tools/shared/spawnMultiAgent.ts`
|
||||
|
||||
**流程**:
|
||||
|
||||
1. 检测执行后端(tmux / iTerm2 / in-process)
|
||||
2. 为队友生成唯一 `agentId`:`formatAgentId(name, teamName)`
|
||||
3. 分配颜色(从预定义调色板)
|
||||
4. 创建执行环境:
|
||||
- **in-process**:通过 `spawnInProcessTeammate()` 在同进程中启动
|
||||
- **tmux**:通过 `TmuxBackend` 创建新 pane
|
||||
- **iTerm2**:通过 `ITerm2Backend` 创建新窗口
|
||||
5. 写入 TeamFile 成员列表
|
||||
6. 返回 `TeammateSpawnedOutput`(包含 pane ID、agent ID 等)
|
||||
|
||||
**In-Process 队友的隔离**:
|
||||
|
||||
```typescript
|
||||
// src/utils/swarm/spawnInProcess.ts
|
||||
export async function spawnInProcessTeammate(config, context) {
|
||||
// 1. 独立的 AbortController(不随 leader 中断)
|
||||
const abortController = new AbortController()
|
||||
|
||||
// 2. AsyncLocalStorage 上下文隔离
|
||||
runWithTeammateContext(teammateContext, async () => {
|
||||
// 3. 独立的任务状态
|
||||
// 4. 独立的消息循环
|
||||
// 5. 共享的权限管道(通过 mailbox)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 路径 2:异步 Subagent
|
||||
|
||||
**触发条件**:`run_in_background=true` 或 Agent 定义中 `background: true`
|
||||
|
||||
**流程**:
|
||||
|
||||
```
|
||||
registerAsyncAgent()
|
||||
│
|
||||
├─ 创建 LocalAgentTask(status: 'running')
|
||||
├─ 注册到 agentNameRegistry(如有 name)
|
||||
├─ 创建输出文件符号链接
|
||||
├─ 创建 AbortController(链接到父代理)
|
||||
├─ 发射 SDK event: task_started
|
||||
│
|
||||
└─ void runAsyncAgentLifecycle() ← 异步分离执行
|
||||
│
|
||||
├─ 创建 ProgressTracker
|
||||
├─ 遍历 makeStream() 生成器
|
||||
│ ├─ 追加消息到 agentMessages[]
|
||||
│ ├─ 更新进度(tokens、tools、activities)
|
||||
│ └─ 发射 SDK progress events
|
||||
│
|
||||
└─ 完成时:
|
||||
├─ finalizeAgentTool()(提取结果)
|
||||
├─ completeAgentTask()(标记完成)
|
||||
├─ 清理 worktree(如有隔离)
|
||||
└─ enqueuePendingNotification()(通知主代理)
|
||||
```
|
||||
|
||||
**关键实现**:`src/tools/AgentTool/agentToolUtils.ts` — `runAsyncAgentLifecycle()`
|
||||
|
||||
### 路径 3:Fork Subagent
|
||||
|
||||
**触发条件**:省略 `subagent_type` 且 Fork 实验开启
|
||||
|
||||
**核心优化**:通过字节级一致的 API 请求前缀,实现 **prompt cache 命中**。
|
||||
|
||||

|
||||
|
||||
**流程**:
|
||||
|
||||
```
|
||||
buildForkedMessages(directive, assistantMessage)
|
||||
│
|
||||
├─ 保留父代理完整的 assistant message(所有 tool_use 块)
|
||||
├─ 构建 user message:
|
||||
│ ├─ 对每个 tool_use 创建占位 tool_result(字节一致)
|
||||
│ └─ 追加 per-child directive(唯一差异部分)
|
||||
│
|
||||
└─ 结果:字节级一致的 API 前缀 → prompt cache 命中!
|
||||
```
|
||||
|
||||
**Fork 子代理的行为约束**(通过 `FORK_BOILERPLATE_TAG` 注入):
|
||||
|
||||
```
|
||||
1. 你是分叉的工作进程,不是主代理
|
||||
2. 不要对话、提问或建议后续步骤
|
||||
3. 直接使用工具(Bash、Read、Write 等)
|
||||
4. 如修改文件,在报告前提交更改
|
||||
5. 工具调用之间不要输出文本
|
||||
6. 严格限制在指令范围内
|
||||
7. 报告控制在 500 词以内
|
||||
8. 响应必须以 "Scope:" 开头
|
||||
```
|
||||
|
||||
**防递归保护**:`isInForkChild()` 检测是否在 fork 子进程中,防止嵌套 fork。
|
||||
|
||||
### 路径 4:同步 Subagent
|
||||
|
||||
**触发条件**:默认路径(无 team_name、无 background、非 fork)
|
||||
|
||||
**流程**:
|
||||
|
||||
```
|
||||
runAgent(promptMessages, toolUseContext, options)
|
||||
│
|
||||
├─ 解析 Agent 定义(getSystemPrompt、tools、permissions)
|
||||
├─ 构建系统提示词(buildEffectiveSystemPrompt)
|
||||
├─ 创建隔离的 ToolUseContext(createSubagentContext)
|
||||
├─ 启动查询循环(query() async generator)
|
||||
│ ├─ 发送 API 请求
|
||||
│ ├─ 处理流式事件
|
||||
│ ├─ 执行工具调用
|
||||
│ └─ 累积消息和 usage
|
||||
│
|
||||
└─ 返回 AgentToolResult
|
||||
├─ content: 最后 assistant 消息的文本
|
||||
├─ totalToolUseCount
|
||||
├─ totalDurationMs
|
||||
└─ totalTokens
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、工具池系统 — 三层过滤
|
||||
|
||||

|
||||
|
||||
### 第一层:全局禁止
|
||||
|
||||
`ALL_AGENT_DISALLOWED_TOOLS` — 对所有 Agent 禁止的工具:
|
||||
|
||||
| 工具 | 禁止原因 |
|
||||
|------|----------|
|
||||
| TaskOutput | 仅主代理可读取任务输出 |
|
||||
| ExitPlanMode | 仅主代理可退出计划模式 |
|
||||
| EnterPlanMode | 仅主代理可进入计划模式 |
|
||||
| AskUserQuestion | 子代理不应直接问用户 |
|
||||
| TaskStop | 仅主代理可终止任务 |
|
||||
| Agent | 防止递归生成(Ant 内部例外) |
|
||||
|
||||
### 第二层:Agent 类型过滤
|
||||
|
||||
`filterToolsForAgent()` — 基于 Agent 类型的工具过滤:
|
||||
|
||||
```typescript
|
||||
// src/tools/AgentTool/agentToolUtils.ts
|
||||
function filterToolsForAgent(tools, agentDef) {
|
||||
// 1. 移除 ALL_AGENT_DISALLOWED_TOOLS
|
||||
// 2. 如果非内置 Agent,额外移除 CUSTOM_AGENT_DISALLOWED_TOOLS
|
||||
// 3. 如果是异步 Agent,限制为 ASYNC_AGENT_ALLOWED_TOOLS
|
||||
// 4. MCP 工具始终允许
|
||||
}
|
||||
```
|
||||
|
||||
**ASYNC_AGENT_ALLOWED_TOOLS**(15 个):
|
||||
|
||||
```
|
||||
Read, WebSearch, TodoWrite, Grep, WebFetch, Glob,
|
||||
Bash/PowerShell, FileEdit, FileWrite, NotebookEdit,
|
||||
Skill, SyntheticOutput, ToolSearch, EnterWorktree, ExitWorktree
|
||||
```
|
||||
|
||||
### 第三层:Agent 定义过滤
|
||||
|
||||
`resolveAgentTools()` — 基于 Agent 定义的工具解析:
|
||||
|
||||
```typescript
|
||||
function resolveAgentTools(agentDef, availableTools) {
|
||||
if (tools === ['*'] || undefined) → 通配符,全部允许
|
||||
if (tools === ['Read', 'Grep']) → 仅允许列表中的工具
|
||||
if (disallowedTools === ['Agent']) → 从可用工具中减去
|
||||
}
|
||||
```
|
||||
|
||||
**过滤流程图**:
|
||||
|
||||
```
|
||||
所有可用工具
|
||||
│
|
||||
├─ 减去 ALL_AGENT_DISALLOWED_TOOLS ──→ 通用禁止
|
||||
│
|
||||
├─ 非内置?减去 CUSTOM_AGENT_DISALLOWED_TOOLS ──→ 自定义限制
|
||||
│
|
||||
├─ 异步?限制为 ASYNC_AGENT_ALLOWED_TOOLS ──→ 异步白名单
|
||||
│
|
||||
├─ 有 tools 列表?取交集 ──→ Agent 白名单
|
||||
│
|
||||
├─ 有 disallowedTools?取差集 ──→ Agent 黑名单
|
||||
│
|
||||
└─ 最终工具池
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、上下文传递机制
|
||||
|
||||

|
||||
|
||||
### CacheSafeParams — 缓存安全参数
|
||||
|
||||
```typescript
|
||||
// src/utils/forkedAgent.ts
|
||||
export type CacheSafeParams = {
|
||||
systemPrompt: SystemPrompt // 系统提示词
|
||||
userContext: { [k: string]: string } // 目录结构、CLAUDE.md 等
|
||||
systemContext: { [k: string]: string } // git status、环境信息
|
||||
toolUseContext: ToolUseContext // 工具配置、模型、选项
|
||||
forkContextMessages: Message[] // Fork 上下文消息(用于缓存共享)
|
||||
}
|
||||
```
|
||||
|
||||
**缓存共享原理**:
|
||||
|
||||
Fork Agent 通过保持 API 请求前缀字节级一致来复用 prompt cache:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ 共享前缀(字节一致) │
|
||||
│ ┌──────────────────────────────────┐ │
|
||||
│ │ System Prompt │ │
|
||||
│ │ User Context │ │
|
||||
│ │ System Context │ │
|
||||
│ │ Tool Use Context │ │
|
||||
│ │ 对话历史 Messages │ │
|
||||
│ │ Assistant Message (all tool_use) │ │
|
||||
│ │ User Message (placeholder results│) │
|
||||
│ └──────────────────────────────────┘ │
|
||||
├─────────────────────────────────────────┤
|
||||
│ 唯一差异:per-child directive text │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 系统提示词构建
|
||||
|
||||
`buildEffectiveSystemPrompt()` — `src/utils/systemPrompt.ts`
|
||||
|
||||
**优先级链**(从高到低):
|
||||
|
||||
```
|
||||
Override System Prompt ← 最高优先级,完全替换
|
||||
↓
|
||||
Coordinator System Prompt ← 协调器模式专用
|
||||
↓
|
||||
Agent System Prompt ← agentDefinition.getSystemPrompt()
|
||||
↓ - proactive 模式:追加到默认
|
||||
↓ - 其他:替换默认
|
||||
Custom System Prompt ← --system-prompt 参数
|
||||
↓
|
||||
Default System Prompt ← Claude Code 标准提示词
|
||||
↓
|
||||
Append System Prompt ← 追加到末尾
|
||||
```
|
||||
|
||||
**Agent 特有的系统提示词增强**:
|
||||
|
||||
```typescript
|
||||
// src/tools/AgentTool/runAgent.ts
|
||||
function getAgentSystemPrompt(agentDef, toolUseContext) {
|
||||
let prompt = agentDef.getSystemPrompt({ toolUseContext })
|
||||
prompt = enhanceSystemPromptWithEnvDetails(prompt)
|
||||
// 添加:工作目录、启用工具列表、模型信息、环境变量
|
||||
return prompt
|
||||
}
|
||||
```
|
||||
|
||||
### SubagentContext — 子代理上下文隔离
|
||||
|
||||
```typescript
|
||||
// src/utils/forkedAgent.ts
|
||||
export type SubagentContextOverrides = {
|
||||
options?: ToolUseContext['options'] // 自定义工具、模型
|
||||
agentId?: AgentId // 子代理 ID
|
||||
agentType?: string // Agent 类型
|
||||
messages?: Message[] // 自定义消息历史
|
||||
readFileState?: ToolUseContext['readFileState'] // 文件读取缓存
|
||||
abortController?: AbortController // 中止控制器
|
||||
|
||||
// 显式 opt-in 共享(默认隔离)
|
||||
shareSetAppState?: boolean // 共享 AppState 写入
|
||||
shareSetResponseLength?: boolean // 共享响应长度度量
|
||||
shareAbortController?: boolean // 共享中止控制器
|
||||
|
||||
// 实验性注入
|
||||
criticalSystemReminder_EXPERIMENTAL?: string // 每轮重新注入的提醒
|
||||
contentReplacementState?: ContentReplacementState
|
||||
}
|
||||
```
|
||||
|
||||
**隔离 vs 共享**:
|
||||
|
||||
| 资源 | 默认 | 说明 |
|
||||
|------|------|------|
|
||||
| readFileState | 克隆 | 文件读取缓存独立 |
|
||||
| messages | 新建 | 消息历史独立 |
|
||||
| abortController | 新建(链接父) | 父取消时子也取消 |
|
||||
| setAppState | No-op | 默认不影响父状态 |
|
||||
| contentReplacementState | 克隆 | 内容替换状态独立 |
|
||||
|
||||
### 模型解析
|
||||
|
||||
`getAgentModel()` — `src/utils/model/agent.ts`
|
||||
|
||||
**优先级链**:
|
||||
|
||||
```
|
||||
CLAUDE_CODE_SUBAGENT_MODEL 环境变量 ← 最高
|
||||
↓
|
||||
Agent({ model: 'opus' }) 参数 ← 工具指定
|
||||
↓
|
||||
agentDefinition.model ← Agent 定义
|
||||
↓
|
||||
'inherit' ← 继承父代理模型
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、Agent Teams 内部机制
|
||||
|
||||
### TeamFile 结构
|
||||
|
||||
```typescript
|
||||
// 存储路径:~/.claude/teams/{team_name}/config.json
|
||||
{
|
||||
name: string // 团队名称
|
||||
description?: string // 团队描述
|
||||
createdAt: number // 创建时间戳
|
||||
leadAgentId: string // Team Lead 的 Agent ID
|
||||
leadSessionId?: string // Lead 的会话 UUID
|
||||
hiddenPaneIds?: string[] // UI 中隐藏的 pane
|
||||
teamAllowedPaths?: TeamAllowedPath[] // 团队级共享权限
|
||||
members: Array<{
|
||||
agentId: string // 成员 Agent ID
|
||||
name: string // 显示名称
|
||||
agentType?: string // 角色类型
|
||||
model?: string // 使用的模型
|
||||
prompt?: string // 初始任务
|
||||
color?: string // UI 颜色
|
||||
planModeRequired?: boolean // 是否需要 plan 审批
|
||||
joinedAt: number // 加入时间
|
||||
tmuxPaneId: string // 终端 pane ID
|
||||
cwd: string // 工作目录
|
||||
worktreePath?: string // Worktree 路径
|
||||
sessionId?: string // 会话 ID
|
||||
subscriptions: string[] // 消息订阅
|
||||
backendType?: 'tmux'|'iterm2'|'in-process'
|
||||
isActive?: boolean // false=空闲, true/undefined=活跃
|
||||
mode?: PermissionMode // 当前权限模式
|
||||
}>
|
||||
}
|
||||
```
|
||||
|
||||
### 邮箱系统
|
||||
|
||||

|
||||
|
||||
**存储路径**:`~/.claude/teams/{team_name}/inboxes/{agent_name}.json`
|
||||
|
||||
```typescript
|
||||
// src/utils/teammateMailbox.ts
|
||||
type TeammateMessage = {
|
||||
from: string // 发送者名称
|
||||
text: string // 消息内容(纯文本或 JSON)
|
||||
timestamp: string // ISO 时间戳
|
||||
read: boolean // 是否已读
|
||||
color?: string // 发送者颜色
|
||||
summary?: string // 5-10 词摘要
|
||||
}
|
||||
```
|
||||
|
||||
**并发安全**:使用 `proper-lockfile` 文件锁,10 次重试,5-100ms 指数退避。
|
||||
|
||||
**消息类型**:
|
||||
|
||||
| 消息 | 格式 | 用途 |
|
||||
|------|------|------|
|
||||
| 纯文本 | `string` | 普通对话消息 |
|
||||
| shutdown_request | `{ type, reason }` | 请求队友关停 |
|
||||
| shutdown_response | `{ type, request_id, approve }` | 批准/拒绝关停 |
|
||||
| plan_approval_response | `{ type, request_id, approve }` | 审批 plan |
|
||||
| permission_request | `{ type, toolName, path }` | 权限请求 |
|
||||
| idle_notification | 特殊格式 | 空闲通知 |
|
||||
|
||||
### 收件箱轮询
|
||||
|
||||
```typescript
|
||||
// src/hooks/useInboxPoller.ts
|
||||
// 轮询间隔:1000ms
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(async () => {
|
||||
const messages = await readUnreadMessages(agentName, teamName)
|
||||
|
||||
for (const msg of messages) {
|
||||
if (isShutdownRequest(msg.text)) {
|
||||
// 处理关停请求
|
||||
} else if (isPlanApprovalResponse(msg.text)) {
|
||||
// 处理 plan 审批
|
||||
} else if (isPermissionRequest(msg.text)) {
|
||||
// 路由到权限系统
|
||||
} else {
|
||||
// 纯文本消息 → 提交为新对话轮
|
||||
onSubmitMessage(formatted)
|
||||
}
|
||||
}
|
||||
}, INBOX_POLL_INTERVAL_MS)
|
||||
}, [])
|
||||
```
|
||||
|
||||
**消息处理状态**:
|
||||
|
||||
| 状态 | 说明 |
|
||||
|------|------|
|
||||
| `pending` | 新收到,等待处理 |
|
||||
| `processing` | 正在处理(权限请求等) |
|
||||
| `processed` | 已处理完毕 |
|
||||
|
||||
### 消息路由
|
||||
|
||||
```
|
||||
SendMessage({ to, message })
|
||||
│
|
||||
├─ to === "*" → 广播
|
||||
│ └─ 遍历所有队友,逐个写入 mailbox
|
||||
│
|
||||
├─ agentNameRegistry.has(to) → in-process 子代理
|
||||
│ └─ 通过 AppState pending messages 队列路由
|
||||
│
|
||||
├─ teamFile.members.find(to) → 进程级队友
|
||||
│ └─ writeToMailbox(to, message, teamName)
|
||||
│
|
||||
├─ to.startsWith("bridge:") → 远程会话
|
||||
│ └─ postInterClaudeMessage(sessionId, message)
|
||||
│
|
||||
└─ to.startsWith("uds:") → Unix Domain Socket
|
||||
└─ sendToUdsSocket(socketPath, message)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 六、后台任务引擎
|
||||
|
||||

|
||||
|
||||
### LocalAgentTask 状态机
|
||||
|
||||
```typescript
|
||||
// src/tasks/LocalAgentTask/LocalAgentTask.tsx
|
||||
type LocalAgentTaskState = {
|
||||
type: 'local_agent'
|
||||
agentId: AgentId // 唯一标识
|
||||
status: 'running' | 'completed' | 'failed' | 'killed'
|
||||
isBackgrounded: boolean // 前台 vs 后台
|
||||
|
||||
progress: {
|
||||
latestInputTokens: number // 最新输入 tokens
|
||||
cumulativeOutputTokens: number // 累计输出 tokens
|
||||
toolUseCount: number // 工具使用次数
|
||||
recentActivities: ToolActivity[] // 最近 5 个活动
|
||||
lastActivity: number // 最后活动时间戳
|
||||
}
|
||||
|
||||
result?: AgentToolResult // 最终结果
|
||||
abortController: AbortController // 中止控制器
|
||||
retain: boolean // UI 保持标志
|
||||
evictAfter?: number // 延迟清除时间戳
|
||||
}
|
||||
```
|
||||
|
||||
**状态转换**:
|
||||
|
||||
```
|
||||
┌──────────────────────────┐
|
||||
│ │
|
||||
register │ ┌──── killed ←── abort()
|
||||
│ │ │
|
||||
▼ │ │
|
||||
running ─────┼────┼──── completed ← finalizeAgentTool()
|
||||
│ │
|
||||
│ └──── failed ← error / timeout
|
||||
│
|
||||
└──── evict ← notified && endTime > grace
|
||||
```
|
||||
|
||||
### 进度追踪
|
||||
|
||||
```typescript
|
||||
// ProgressTracker
|
||||
function updateProgressFromMessage(tracker, message) {
|
||||
// 1. 累积输入 tokens(取最新值)
|
||||
tracker.latestInputTokens = message.usage?.input_tokens
|
||||
|
||||
// 2. 累加输出 tokens
|
||||
tracker.cumulativeOutputTokens += message.usage?.output_tokens
|
||||
|
||||
// 3. 统计工具使用
|
||||
tracker.toolUseCount += countToolUses(message)
|
||||
|
||||
// 4. 维护最近活动(循环缓冲区,max 5)
|
||||
tracker.recentActivities = [...activities].slice(-5)
|
||||
}
|
||||
```
|
||||
|
||||
### 通知系统
|
||||
|
||||
```typescript
|
||||
// src/utils/messageQueueManager.ts
|
||||
function enqueuePendingNotification(taskId, result) {
|
||||
// 1. 原子设置 notified 标志(防重复)
|
||||
if (task.notified) return
|
||||
task.notified = true
|
||||
|
||||
// 2. 格式化 XML 通知
|
||||
const notification = `
|
||||
<task-notification>
|
||||
<task-id>${taskId}</task-id>
|
||||
<status>${status}</status>
|
||||
<summary>${summary}</summary>
|
||||
<output-file>${outputPath}</output-file>
|
||||
</task-notification>
|
||||
`
|
||||
|
||||
// 3. 入队等待主代理消费
|
||||
pendingNotifications.push(notification)
|
||||
}
|
||||
```
|
||||
|
||||
### 输出管理
|
||||
|
||||
**存储路径**:`~/.claude/temp/{sessionId}/tasks/{taskId}.output`
|
||||
|
||||
| 参数 | 值 |
|
||||
|------|----|
|
||||
| 最大容量 | 5GB / 文件 |
|
||||
| 循环缓冲区 | 1000 行 |
|
||||
| 轮询间隔 | 1 秒 |
|
||||
| 终态保持时间 | 3 秒(任务面板 30 秒) |
|
||||
| 写入方式 | 队列异步写入,防内存堆积 |
|
||||
| 安全措施 | O_NOFOLLOW 防符号链接攻击 |
|
||||
|
||||
---
|
||||
|
||||
## 七、DreamTask — 自动记忆整合
|
||||
|
||||
DreamTask 是特殊的后台 Agent,用于跨会话记忆整合。
|
||||
|
||||
### 触发条件
|
||||
|
||||
```typescript
|
||||
// src/services/autoDream/autoDream.ts
|
||||
function executeAutoDream() {
|
||||
// 四重门控:
|
||||
if (hoursSinceLastConsolidation < minHours) return // 时间门:默认 24h
|
||||
if (sessionsSinceLastConsolidation < minSessions) return // 会话门:默认 5 次
|
||||
if (otherProcessConsolidating) return // 锁门:互斥
|
||||
if (timeSinceLastScan < 10min) return // 扫描节流:10 分钟
|
||||
}
|
||||
```
|
||||
|
||||
### DreamTask 状态
|
||||
|
||||
```typescript
|
||||
type DreamTaskState = {
|
||||
type: 'dream'
|
||||
phase: 'starting' | 'updating' // updating = 已开始编辑文件
|
||||
sessionsReviewing: number // 正在审查的会话数
|
||||
filesTouched: string[] // 编辑过的文件路径
|
||||
turns: DreamTurn[] // 对话轮次记录
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 八、Worktree 隔离实现
|
||||
|
||||
### 创建流程
|
||||
|
||||
```typescript
|
||||
// src/utils/worktree.ts
|
||||
async function createAgentWorktree(slug) {
|
||||
// 1. 校验 slug(防目录逃逸攻击)
|
||||
validateWorktreeSlug(slug)
|
||||
|
||||
// 2. 创建 git worktree
|
||||
git worktree add {path} -b {branch}
|
||||
|
||||
// 3. 符号链接大目录(节省磁盘)
|
||||
symlink(node_modules, worktree/node_modules)
|
||||
|
||||
// 4. 应用 sparse-checkout(如配置)
|
||||
if (sparseCheckoutPaths) {
|
||||
git sparse-checkout set {paths}
|
||||
}
|
||||
|
||||
// 5. 返回 WorktreeSession
|
||||
return { worktreePath, worktreeBranch, headCommit }
|
||||
}
|
||||
```
|
||||
|
||||
### 清理机制
|
||||
|
||||
- Agent 完成后自动检测是否有改动(`hasWorktreeChanges()`)
|
||||
- 有改动:返回 worktree 路径和分支名给用户
|
||||
- 无改动:自动删除 worktree(`removeAgentWorktree()`)
|
||||
- 异常退出:通过 `registerTeamForSessionCleanup()` 确保清理
|
||||
|
||||
---
|
||||
|
||||
## 九、权限同步机制
|
||||
|
||||
### 团队级权限
|
||||
|
||||
```typescript
|
||||
type TeamAllowedPath = {
|
||||
path: string // 绝对目录路径
|
||||
toolName: string // 适用的工具(如 "Edit", "Write")
|
||||
addedBy: string // 添加者名称
|
||||
addedAt: number // 添加时间
|
||||
}
|
||||
```
|
||||
|
||||
队友启动时,自动继承团队级权限规则。
|
||||
|
||||
### Bubble 模式
|
||||
|
||||
Fork Agent 使用 `bubble` 权限模式 — 权限提示冒泡到父代理终端:
|
||||
|
||||
```
|
||||
Fork Agent 需要权限
|
||||
│
|
||||
└─ bubble 模式 → 权限请求发送到父代理
|
||||
│
|
||||
└─ 父代理的 ToolUseConfirm 对话框显示
|
||||
│
|
||||
├─ 用户批准 → 结果回传给 Fork Agent
|
||||
└─ 用户拒绝 → Fork Agent 收到拒绝
|
||||
```
|
||||
|
||||
### In-Process 队友权限
|
||||
|
||||
```
|
||||
队友需要权限
|
||||
│
|
||||
├─ 有 UI bridge → 直接显示在 Leader 的确认对话框
|
||||
│ └─ 带 worker badge 标识来源
|
||||
│
|
||||
└─ 无 UI bridge → 通过 mailbox 排队
|
||||
└─ Leader 的 useSwarmPermissionPoller 处理
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十、Agent 生命周期完整数据流
|
||||
|
||||
```
|
||||
1. 用户触发 Agent Tool
|
||||
│
|
||||
2. AgentTool.call() 路由分发
|
||||
│
|
||||
3. 解析 Agent 定义
|
||||
├─ 查找 Agent 类型(内置 > 插件 > 用户 > 项目)
|
||||
├─ 加载系统提示词
|
||||
├─ 解析工具池(三层过滤)
|
||||
└─ 确定权限模式和模型
|
||||
│
|
||||
4. 创建隔离上下文
|
||||
├─ createSubagentContext()(克隆 readFileState)
|
||||
├─ 生成 agentId
|
||||
├─ 创建 AbortController
|
||||
└─ 可选:创建 worktree
|
||||
│
|
||||
5. 注册任务状态
|
||||
├─ registerAsyncAgent() 或 registerAgentForeground()
|
||||
├─ 发射 SDK event: task_started
|
||||
└─ Perfetto trace 注册
|
||||
│
|
||||
6. 执行查询循环
|
||||
├─ query() async generator
|
||||
│ ├─ 构建 API 请求(含 CacheSafeParams)
|
||||
│ ├─ 流式处理响应
|
||||
│ ├─ 执行工具调用
|
||||
│ └─ 累积 usage 指标
|
||||
├─ 更新进度(ProgressTracker)
|
||||
└─ 记录 transcript
|
||||
│
|
||||
7. 完成处理
|
||||
├─ finalizeAgentTool()(提取结果文本)
|
||||
├─ completeAgentTask()(标记完成)
|
||||
├─ 清理资源
|
||||
│ ├─ 释放文件状态缓存
|
||||
│ ├─ 关闭 MCP 连接
|
||||
│ └─ 删除 worktree(如有)
|
||||
├─ enqueuePendingNotification()(通知主代理)
|
||||
└─ 发射 SDK event: task_completed
|
||||
│
|
||||
8. 主代理消费结果
|
||||
├─ 同步:直接获取 AgentToolResult
|
||||
└─ 异步:收到 <task-notification> 后处理
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十一、关键源文件索引
|
||||
|
||||
### Agent Tool 核心
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `src/tools/AgentTool/AgentTool.tsx` | 主工具实现,路由分发 |
|
||||
| `src/tools/AgentTool/runAgent.ts` | 执行引擎,查询循环 |
|
||||
| `src/tools/AgentTool/agentToolUtils.ts` | 工具池解析,结果终结 |
|
||||
| `src/tools/AgentTool/forkSubagent.ts` | Fork 语义,消息继承 |
|
||||
| `src/tools/AgentTool/loadAgentsDir.ts` | Agent 定义类型,解析加载 |
|
||||
| `src/tools/AgentTool/builtInAgents.ts` | 内置 Agent 注册表 |
|
||||
| `src/tools/AgentTool/prompt.ts` | Agent 工具 schema 和文档 |
|
||||
| `src/tools/AgentTool/agentMemory.ts` | Agent 持久记忆 |
|
||||
|
||||
### Swarm 基础设施
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `src/tools/TeamCreateTool/TeamCreateTool.ts` | 团队创建 |
|
||||
| `src/tools/TeamDeleteTool/TeamDeleteTool.ts` | 团队清理 |
|
||||
| `src/tools/SendMessageTool/SendMessageTool.ts` | 代理间通信 |
|
||||
| `src/tools/shared/spawnMultiAgent.ts` | 队友生成入口 |
|
||||
| `src/utils/swarm/spawnInProcess.ts` | 进程内队友生成 |
|
||||
| `src/utils/swarm/teamHelpers.ts` | 团队文件读写 |
|
||||
| `src/utils/swarm/constants.ts` | 常量定义 |
|
||||
| `src/utils/swarm/teammateInit.ts` | 队友初始化 |
|
||||
| `src/utils/swarm/permissionSync.ts` | 权限同步 |
|
||||
| `src/utils/teammate.ts` | 队友身份解析 |
|
||||
| `src/utils/teammateMailbox.ts` | 邮箱消息队列 |
|
||||
| `src/utils/teamDiscovery.ts` | 团队发现 |
|
||||
| `src/hooks/useInboxPoller.ts` | 收件箱轮询 |
|
||||
|
||||
### 上下文管理
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `src/utils/forkedAgent.ts` | 缓存安全参数,子代理上下文 |
|
||||
| `src/utils/systemPrompt.ts` | 系统提示词优先级构建 |
|
||||
| `src/utils/model/agent.ts` | Agent 模型解析 |
|
||||
| `src/utils/worktree.ts` | Git worktree 隔离 |
|
||||
|
||||
### 任务系统
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `src/tasks/LocalAgentTask/LocalAgentTask.tsx` | 本地 Agent 任务 |
|
||||
| `src/tasks/RemoteAgentTask/RemoteAgentTask.tsx` | 远程 Agent 任务 |
|
||||
| `src/tasks/InProcessTeammateTask/` | 进程内队友任务 |
|
||||
| `src/tasks/DreamTask/DreamTask.ts` | 记忆整合任务 |
|
||||
| `src/utils/task/framework.ts` | 任务注册、状态更新 |
|
||||
| `src/utils/task/diskOutput.ts` | 任务输出文件管理 |
|
||||
| `src/utils/messageQueueManager.ts` | 通知队列 |
|
||||
|
||||
### 协调器
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `src/coordinator/coordinatorMode.ts` | 协调器模式配置 |
|
||||
|
||||
---
|
||||
|
||||
## 十二、Feature Flags
|
||||
|
||||
| Flag | 控制内容 |
|
||||
|------|----------|
|
||||
| `FORK_SUBAGENT` | 启用 Fork 路径(省略 subagent_type) |
|
||||
| `BUILTIN_EXPLORE_PLAN_AGENTS` | 启用 Explore/Plan Agent |
|
||||
| `VERIFICATION_AGENT` | 启用 verification Agent |
|
||||
| `COORDINATOR_MODE` | 启用协调器模式 |
|
||||
| `KAIROS` | 启用 cwd 参数 |
|
||||
| `tengu_auto_background_agents` | 120 秒后自动后台化 |
|
||||
| `tengu_slim_subagent_claudemd` | 只读 Agent 省略 CLAUDE.md |
|
||||
| `tengu_agent_list_attach` | Agent 列表通过 attachment 注入 |
|
||||
107
docs/agent/README.md
Normal file
@ -0,0 +1,107 @@
|
||||
# Claude Code 多 Agent 系统文档
|
||||
|
||||
> 完整的多 Agent 编排使用指南和实现原理文档
|
||||
|
||||
---
|
||||
|
||||
## 📚 文档目录
|
||||
|
||||
### [01-usage-guide.md](./01-usage-guide.md) — 使用指南
|
||||
|
||||
面向用户的完整使用手册,涵盖:
|
||||
|
||||
- **Agent 工具**:参数详解、生成方式、后台运行
|
||||
- **六种内置 Agent**:general-purpose、Explore、Plan、verification、claude-code-guide、statusline-setup
|
||||
- **后台任务**:异步执行、进度追踪、完成通知
|
||||
- **Agent Teams**:团队创建、成员协作、消息通信
|
||||
- **Worktree 隔离**:独立环境、分支管理、安全上下文
|
||||
- **自定义 Agent**:定义格式、工具池配置、系统提示词
|
||||
|
||||
**适合人群**:所有 Claude Code 用户
|
||||
|
||||
---
|
||||
|
||||
### [02-implementation.md](./02-implementation.md) — 实现原理
|
||||
|
||||
面向开发者的技术深度解析,涵盖:
|
||||
|
||||
- **架构总览**:5 大 Agent 类别、4 条生成路径
|
||||
- **Agent 生成流程**:同步/异步/Fork/Teammate 四种路径详解
|
||||
- **工具池系统**:三层过滤、常量定义、权限映射
|
||||
- **上下文传递**:CacheSafeParams、系统提示词构建、Fork 缓存优化
|
||||
- **Teams 内部机制**:TeamFile 结构、邮箱系统、收件箱轮询、消息路由
|
||||
- **后台任务引擎**:LocalAgentTask 生命周期、进度追踪、通知队列
|
||||
- **权限同步**:团队级权限、模式传播、bubble 模式
|
||||
- **完整数据流**:从 Agent Tool 调用到结果回传
|
||||
|
||||
**适合人群**:贡献者、架构师、想深入了解实现的开发者
|
||||
|
||||
---
|
||||
|
||||
## 🖼️ 配图说明
|
||||
|
||||
所有配图采用深色背景(#1a1a2e)+ Anthropic 品牌橙铜色(#D97757)风格,与 Claude Code 官方文档一致。
|
||||
|
||||
| 图片 | 说明 | 所属文档 |
|
||||
|------|------|----------|
|
||||
| `01-agent-overview.png` | 多 Agent 系统概览 — 架构全景 | 使用指南 |
|
||||
| `02-agent-types.png` | 六种内置 Agent — 类型对比矩阵 | 使用指南 |
|
||||
| `03-spawn-flow.png` | Agent 生成流程 — 四条路径决策树 | 使用指南 |
|
||||
| `04-agent-teams.png` | Agent Teams 协作 — 团队通信拓扑 | 使用指南 |
|
||||
| `05-architecture.png` | 实现架构总览 — 核心模块关系 | 实现原理 |
|
||||
| `06-context-passing.png` | 上下文传递 — CacheSafeParams 数据流 | 实现原理 |
|
||||
| `07-tool-pool.png` | 工具池系统 — 三层过滤流程 | 实现原理 |
|
||||
| `08-background-task.png` | 后台任务引擎 — 生命周期状态机 | 实现原理 |
|
||||
| `09-teams-mailbox.png` | Teams 邮箱系统 — 消息路由拓扑 | 实现原理 |
|
||||
| `10-fork-cache.png` | Fork 缓存优化 — 字节级一致共享 | 实现原理 |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 用户
|
||||
|
||||
1. 阅读 [使用指南](./01-usage-guide.md)
|
||||
2. 了解六种内置 Agent 及其适用场景
|
||||
3. 尝试在对话中使用 Agent 工具生成子代理
|
||||
4. 探索 Agent Teams 多代理协作
|
||||
|
||||
### 开发者
|
||||
|
||||
1. 阅读 [实现原理](./02-implementation.md)
|
||||
2. 查看源码位置:
|
||||
- `src/tools/AgentTool/` — Agent 工具实现
|
||||
- `src/tools/TeamCreateTool/` — 团队创建
|
||||
- `src/tools/SendMessageTool/` — 代理间通信
|
||||
- `src/utils/swarm/` — Swarm 协作基础设施
|
||||
- `src/utils/forkedAgent.ts` — Fork 代理上下文
|
||||
- `src/tasks/` — 任务管理系统
|
||||
3. 理解四条生成路径和上下文传递机制
|
||||
|
||||
---
|
||||
|
||||
## 📝 核心概念速查
|
||||
|
||||
| 概念 | 说明 |
|
||||
|------|------|
|
||||
| **Agent Tool** | 主入口工具,接受 prompt + subagent_type 生成子代理 |
|
||||
| **Subagent** | 独立执行任务的子代理,有自己的工具池和权限 |
|
||||
| **Fork Agent** | 继承父代理完整上下文的分叉代理,共享 prompt cache |
|
||||
| **Teammate** | Agent Teams 中的协作成员,通过邮箱通信 |
|
||||
| **Worktree** | Git worktree 隔离模式,独立文件环境 |
|
||||
| **LocalAgentTask** | 本地代理任务状态,追踪 running/completed/failed |
|
||||
| **DreamTask** | 自动记忆整合任务,定期后台运行 |
|
||||
| **CacheSafeParams** | 缓存安全参数,确保 API 请求前缀字节级一致 |
|
||||
| **TeamFile** | 团队配置文件,存储成员列表和权限 |
|
||||
| **Mailbox** | 基于文件的消息队列,支持队友间异步通信 |
|
||||
|
||||
---
|
||||
|
||||
## 🔗 相关资源
|
||||
|
||||
- [Claude Code 主文档](../)
|
||||
- [记忆系统文档](../memory/)
|
||||
- [Agent Tool 源码](../../src/tools/AgentTool/)
|
||||
- [Swarm 基础设施](../../src/utils/swarm/)
|
||||
- [任务管理系统](../../src/tasks/)
|
||||
- [GitHub Issues](https://github.com/anthropics/claude-code/issues)
|
||||
BIN
docs/agent/images/01-agent-overview.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
BIN
docs/agent/images/02-agent-types.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
BIN
docs/agent/images/03-spawn-flow.png
Normal file
|
After Width: | Height: | Size: 2.2 MiB |
BIN
docs/agent/images/04-agent-teams.png
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
docs/agent/images/05-architecture.png
Normal file
|
After Width: | Height: | Size: 1.9 MiB |
BIN
docs/agent/images/06-context-passing.png
Normal file
|
After Width: | Height: | Size: 116 KiB |
BIN
docs/agent/images/07-tool-pool.png
Normal file
|
After Width: | Height: | Size: 1.5 MiB |
BIN
docs/agent/images/08-background-task.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
BIN
docs/agent/images/09-teams-mailbox.png
Normal file
|
After Width: | Height: | Size: 87 KiB |
BIN
docs/agent/images/10-fork-cache.png
Normal file
|
After Width: | Height: | Size: 92 KiB |