Agent 工具
概述
AgentTool 是 Claude Code 中最复杂的工具之一,它允许 Claude 生成子代理来并行处理复杂任务。每个子代理有自己的对话上下文、工具池和权限。
Source:
src/tools/AgentTool/(69KB 主文件 + 多个辅助文件)
架构
输入参数
typescript
// Source: src/tools/AgentTool/AgentTool.tsx:82-125
{
description: string // 3-5 词任务描述
prompt: string // 详细指令
subagent_type?: string // 代理定义名称
model?: 'sonnet' | 'opus' | 'haiku' // 模型覆盖
run_in_background?: boolean // 后台运行
name?: string // 可寻址名称(用于 SendMessage)
team_name?: string // 团队上下文
mode?: PermissionMode // 权限模式覆盖
isolation?: 'worktree' // Git 隔离
}执行流程
代理定义
代理定义从 .agents/ 目录的 Markdown 文件加载:
markdown
---
name: code-reviewer
description: Reviews code for quality and best practices
model: sonnet
tools: [Read, Grep, Glob]
---
You are a code reviewer. Analyze the provided code for:
- Bug risks
- Performance issues
- Code style violationsSource:
src/tools/AgentTool/loadAgentsDir.ts(26KB)
工具池过滤
子代理不会继承主对话的完整工具池:
typescript
// runAgent.ts:99+
const agentTools = filterToolsForAgent(
parentTools,
agentDefinition.tools // 代理定义中指定的工具列表
);同步 vs 后台
同步代理
typescript
// 主对话等待子代理完成
const result = await agentTool.call({
prompt: "Search for all TODO comments",
run_in_background: false, // 默认
});
// result = { status: 'completed', result: "Found 15 TODOs..." }后台代理
typescript
// 主对话立即继续
const result = await agentTool.call({
prompt: "Run comprehensive test suite",
run_in_background: true,
});
// result = { status: 'async_launched', agentId: "abc123" }
// 完成后通过任务通知机制告知多代理通信
通过 SendMessageTool 实现代理间通信:
typescript
// 主 Claude 启动一个命名代理
agentTool.call({
prompt: "Monitor test failures",
name: "test-watcher",
});
// 后续可以发送消息
sendMessageTool.call({
to: "test-watcher",
message: "Check if the latest fix resolved the failure",
});代理名称通过 AppState.agentNameRegistry 注册和解析。
Git Worktree 隔离
当 isolation: 'worktree' 时,子代理在一个独立的 Git worktree 中工作:
这确保了子代理的修改不会影响主工作目录。
关键文件
| 文件 | 大小 | 功能 |
|---|---|---|
AgentTool.tsx | 69KB | 工具定义、输入验证 |
runAgent.ts | 35KB | 代理执行循环 |
loadAgentsDir.ts | 26KB | 加载代理定义 |
forkSubagent.ts | 8KB | Fork 代理(继承上下文) |
resumeAgent.ts | 9KB | 恢复后台代理 |
UI.tsx | 32KB | 代理进度/结果渲染 |
代理颜色系统
每个代理分配唯一颜色,便于在多代理输出中区分:
typescript
// Source: src/bootstrap/state.ts
agentColorMap: Map<string, AgentColorName>颜色在代理首次创建时分配,整个会话保持一致。