mcpField
S
sub-agent-patterns

sub-agent-patterns

github.com/jezwebAgent 工作流1.1k396 次安装3 周前更新
代码仓库

关于 sub-agent-patterns

为 Claude Code 提供子 Agent 使用与配置指南,面向需要委派代码探索、修改和多步骤任务的开发者。重点介绍隔离上下文、工具权限和自定义 Agent 的实践。

主要功能

  1. 01内置探索、规划和通用子 Agent
  2. 02为任务配置工具与提示词
  3. 03通过文件或 CLI 定义自定义 Agent
  4. 04委派及恢复子 Agent 会话
  5. 05说明 MCP 工具继承规则

适用场景

  1. 01将冗长的代码搜索结果移出主对话
  2. 02委派重复的部署、审查或迁移流程
  3. 03恢复跨会话的长时间研究任务

MCP 相关

说明子 Agent 省略 tools 字段时会继承所有工具,包括 MCP 工具;指定 tools 后则成为允许列表。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jezweb/claude-skills --skill sub-agent-patterns

安装后在 Claude Code 中输入/sub-agent-patterns确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
.claude-plugin/
plugin.json
rules/
sub-agent-patterns.md

详细介绍

Claude Code 中的子 Agent

状态:已可用于生产环境 ✅ 上次更新:2026-02-02 来源:https://code.claude.com/docs/en/sub-agents

子 Agent 是 Claude Code 可委派任务的专用 AI 助手。每个子 Agent 都有自己的上下文窗口、可配置的工具和自定义系统提示词。


为什么使用子 Agent:保持上下文整洁

子 Agent 的主要价值不在于专业化,而在于保持主上下文整洁。

不使用 Agent(上下文膨胀):

Main context accumulates:
├─ git status output (50 lines)
├─ npm run build output (200 lines)
├─ tsc --noEmit output (100 lines)
├─ wrangler deploy output (100 lines)
├─ curl health check responses
├─ All reasoning about what to do next
└─ Context: 📈 500+ lines consumed

使用 Agent(上下文整洁):

Main context:
├─ "Deploy to cloudflare"
├─ [agent summary - 30 lines]
└─ Context: 📊 ~50 lines consumed

Agent context (isolated):
├─ All verbose tool outputs
├─ All intermediate reasoning
└─ Discarded after returning summary

计算方式:一个部署工作流会运行约 10 次工具调用。这样会在主上下文中产生 500 多行内容,而使用 Agent 时只需 30 行摘要。在整个会话中,这种差异会不断累积并显著扩大。

这在以下情况中最重要:

  • 可重复的工作流(部署、迁移、审计、审查)
  • 输出冗长的工具(构建日志、测试结果、API 响应)
  • 多步骤操作,且只需关注最终结果
  • 上下文压力逐渐累积的长会话

关键要点:使用 Agent 处理重复执行的工作流,而不只是用于专业化。随着时间推移,节省的上下文会不断累积。


内置子 Agent

Claude Code 内置了三个开箱即用的子 Agent:

Explore Agent

快速、轻量的 Agent,专为只读代码库探索而优化。

属性值
模型Haiku(快速、低延迟)
模式严格只读
工具Glob、Grep、Read、Bash(只读:ls、git status、git log、git diff、find、cat、head、tail)

详尽程度(调用时指定):

  • quick - 快速搜索、定向查找
  • medium - 兼顾速度和详尽程度
  • very thorough - 对多个位置进行全面分析

Claude 使用场景:搜索和理解代码库,但不做任何更改。调查结果不会让主对话膨胀。

User: Where are errors from the client handled?
Claude: [Invokes Explore with "medium" thoroughness]
       → Returns: src/services/process.ts:712
Plan Agent

专为计划模式下的研究和信息收集而设计。

属性值
模型Sonnet
模式只读研究
工具Read、Glob、Grep、Bash
调用方式在计划模式下自动调用

Claude 使用场景:在计划模式下研究代码库并制定计划。它能防止无限嵌套(子 Agent 不能再启动子 Agent)。

General-Purpose Agent

功能强大的 Agent,适用于需要同时探索和执行操作的复杂多步骤任务。

属性值
模型Sonnet
模式可读写
工具所有工具
用途复杂研究、多步骤操作、代码修改

Claude 使用场景:

  • 任务既需要探索,也需要修改
  • 需要复杂推理来解读搜索结果
  • 可能需要采用多种策略
  • 任务包含多个相互依赖的步骤

创建自定义子 Agent

文件位置
类型位置范围优先级
项目.claude/agents/仅限当前项目最高
用户~/.claude/agents/所有项目较低
CLI--agents '{...}'当前会话中等

名称冲突时,项目级设置优先。

⚠️ 严重:需要重启会话

Agent 只会在会话启动时加载。如果在会话期间创建新的 Agent 文件:

  1. 它们不会出现在 /agents 中
  2. Claude 无法调用它们
  3. 解决方案:重启 Claude Code 会话,以发现新 Agent

这是自定义 Agent“无法正常工作”最常见的原因——它们是在会话启动后创建的。

文件格式

使用 YAML frontmatter 的 Markdown 文件:

---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: inherit
permissionMode: default
skills: project-workflow
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

Your sub-agent's system prompt goes here.

Include specific instructions, best practices, and constraints.
配置字段
字段必填描述
name是唯一标识符(小写,使用连字符)
description是Claude 应在何时使用此 Agent
tools否以逗号分隔的列表。完全省略 = 继承所有工具(包括 MCP)
model否sonnet、opus、haiku 或 inherit。默认值:sonnet
permissionMode否default、acceptEdits、dontAsk、bypassPermissions、plan、ignore
skills否自动加载的技能列表,以逗号分隔(子 Agent 不会继承父级技能)
hooks否PreToolUse、PostToolUse、Stop 事件处理程序
MCP 工具继承(重要)

要从子 Agent 访问 MCP 工具,必须完全省略 tools 字段。

在 tools 字段中指定任何工具后,该字段就会变成允许列表。此处不支持通配符语法。

# ❌ WRONG - "*" is interpreted literally as a tool named "*", not a wildcard
tools: Read, Grep, Glob, "*"

# ❌ WRONG - this is an allowlist, agent cannot access MCP tools
tools: Read, Grep, Glob

# ✅ CORRECT - omit tools field entirely to inherit ALL tools including MCP
# tools field omitted
model: sonnet

重要提示:"*" 不是有效的通配符语法。解析时,它会被视为不存在的字面工具名称。

需要重启 Agent:更改 Agent 配置文件后,只有重启 Claude Code 会话才会生效。

可用工具参考

可分配给子 Agent 的完整工具列表:

工具用途类型
Read读取文件(文本、图像、PDF、笔记本)只读
Write创建或覆盖文件写入
Edit精确替换文件中的字符串写入
MultiEdit批量编辑单个文件写入
Glob匹配文件模式(**/*.ts)只读
Grep使用正则表达式搜索内容(ripgrep)只读
LS列出目录内容只读
Bash执行 Shell 命令执行
BashOutput获取后台 Shell 的输出执行
KillShell终止后台 Shell执行
Task启动子 Agent编排
WebFetch获取并分析网页内容Web
WebSearch搜索网页Web
TodoWrite创建和管理任务列表组织
TodoRead读取当前任务列表组织
NotebookRead读取 Jupyter 笔记本笔记本
NotebookEdit编辑 Jupyter 笔记本单元格笔记本
AskUserQuestion交互式询问用户UI
EnterPlanMode进入规划模式规划
ExitPlanMode携带计划退出规划模式规划
Skill在对话中执行技能技能
LSP语言服务器协议集成高级
MCPSearch发现 MCP 工具高级

不同类型 Agent 的工具访问模式:

Agent 类型推荐工具备注
只读审查者Read, Grep, Glob, LS无写入能力
文件创建者Read, Write, Edit, Glob, Grep⚠️ 不包含 Bash——避免频繁请求批准
脚本运行者Read, Write, Edit, Glob, Grep, Bash需要执行 CLI 时使用
研究 AgentRead, Grep, Glob, WebFetch, WebSearch只读外部访问
文档编写者Read, Write, Edit, Glob, Grep, WebFetch不包含 Bash,工作流更简洁
编排者Read, Grep, Glob, Task仅使用最少工具,将任务委派给专门的 Agent
完整访问权限省略 tools 字段(继承所有工具)谨慎使用

⚠️ 工具访问原则:如果 Agent 不需要 Bash,就不要给它 Bash。每条 Bash 命令都需要批准,会中断工作流。请参阅下文的“避免 Bash 批准请求过多”。

避免 Bash 审批请求过多(严重)

当子 Agent 的工具列表中包含 Bash 时,它们通常会默认使用 cat > file << 'EOF' heredoc 来创建文件,而不是使用 Write 工具。每条不同的 Bash 命令都需要用户批准,因此会导致:

  • 每次运行 Agent 都会出现几十条审批请求
  • 工作流缓慢且令人沮丧
  • 难以审查(heredoc 是大段未格式化的内容)

根本原因:

  1. 模型默认使用 bash 操作文件 - 训练数据使其倾向于使用 shell 命令
  2. 工具列表中有 Bash = 会使用 Bash - 即使 Write 工具可用也一样
  3. 指令被埋没 - 在 450 行提示词的第 300 行写上“不要使用 bash”规则,往往会被忽略

解决方案(按优先顺序排列):

  1. 从工具列表中移除 Bash(如果不需要):

    # Before - causes approval spam
    tools: Read, Write, Edit, Glob, Grep, Bash
    
    # After - clean file operations
    tools: Read, Write, Edit, Glob, Grep
    

    如果 Agent 只创建文件,就不需要 Bash。协调器可以在之后运行必要的脚本。

  2. 将关键指令放在最前面(紧接在 frontmatter 后):

    ---
    name: site-builder
    tools: Read, Write, Edit, Glob, Grep
    model: sonnet
    ---
    
    ## ⛔ CRITICAL: USE WRITE TOOL FOR ALL FILES
    
    **You do NOT have Bash access.** Create ALL files using the **Write tool**.
    
    ---
    
    [rest of prompt...]
    

    放在顶部的指令会得到遵循。埋在 300 行之后的指令则会被忽略。

  3. 移除相互矛盾的指令:

    # BAD - contradictory
    Line 75: "Copy images with `cp -r intake/images/* build/images/`"
    Line 300: "NEVER use cp, mkdir, cat, or echo"
    
    # GOOD - consistent
    Only mention the pattern you want used. Remove all bash examples if you want Write tool.
    

何时保留 Bash:

  • Agent 需要运行外部 CLI(wrangler、npm、git)
  • Agent 需要执行脚本
  • Agent 需要检查命令输出

测试:移除 Bash 前后对比:

  • 之前(有 Bash):出现 11 次以上 heredoc 审批请求,应用了错误模式
  • 之后(无 Bash):主要使用 Write 工具,应用了正确模式,审批请求极少
使用 /agents 命令(推荐)
/agents

交互式菜单,可用于:

  • 查看所有子 Agent(内置、用户、项目)
  • 通过引导式设置创建新的子 Agent
  • 编辑现有子 Agent 及其工具访问权限
  • 删除自定义子 Agent
  • 查看哪些子 Agent 处于活动状态
CLI 配置
claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

使用子 Agent

自动委派

Claude 会根据以下内容主动委派任务:

  • 你请求中的任务描述
  • 子 Agent 配置中的 description 字段
  • 当前上下文和可用工具

提示:在 description 中加入“use PROACTIVELY”或“MUST BE USED”,可以让调用更加自动。

显式调用
> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error
可恢复的子 Agent

可以恢复子 Agent,以继续之前的对话:

# Initial invocation
> Use the code-analyzer agent to review the auth module
[Agent completes, returns agentId: "abc123"]

# Resume with full context
> Resume agent abc123 and now analyze the authorization logic

适用场景:

  • 跨多个会话进行长期研究
  • 迭代完善内容,同时保留上下文
  • 在保留上下文的情况下执行多步骤工作流
禁用子 Agent

将以下内容添加到 settings.json 权限中:

{
  "permissions": {
    "deny": ["Task(Explore)", "Task(Plan)"]
  }
}

或者通过 CLI:

claude --disallowedTools "Task(Explore)"

Agent 编排

子 Agent 可以调用其他子 Agent,从而实现复杂的编排模式。只需在 Agent 的工具列表中加入 Task 工具即可。

工作原理

当子 Agent 可以使用 Task 工具时,它可以:

  • 启动其他子 Agent(内置或自定义)
  • 协调多个专家并行工作
  • 串联多个 Agent,执行多阶段工作流
---
name: orchestrator
description: Orchestrator agent that coordinates other specialized agents. Use for complex multi-phase tasks.
tools: Read, Grep, Glob, Task  # ← Task tool enables agent spawning
model: sonnet
---
协调器模式
---
name: release-orchestrator
description: Coordinates release preparation by delegating to specialized agents. Use before releases.
tools: Read, Grep, Glob, Bash, Task
---

You are a release orchestrator. When invoked:

1. Use Task tool to spawn code-reviewer agent
   → Review all uncommitted changes

2. Use Task tool to spawn test-runner agent
   → Run full test suite

3. Use Task tool to spawn doc-validator agent
   → Check documentation is current

4. Collect all reports and synthesize:
   - Blockers (must fix before release)
   - Warnings (should address)
   - Ready to release: YES/NO

Spawn agents in parallel when tasks are independent.
Wait for all agents before synthesizing final report.
实际示例

多专家工作流:

User: "Prepare this codebase for production"

orchestrator agent:
  ├─ Task(code-reviewer) → Reviews code quality
  ├─ Task(security-auditor) → Checks for vulnerabilities
  ├─ Task(performance-analyzer) → Identifies bottlenecks
  └─ Synthesizes findings into actionable report

并行研究:

User: "Compare these 5 frameworks for our use case"

research-orchestrator:
  ├─ Task(general-purpose) → Research framework A
  ├─ Task(general-purpose) → Research framework B
  ├─ Task(general-purpose) → Research framework C
  ├─ Task(general-purpose) → Research framework D
  ├─ Task(general-purpose) → Research framework E
  └─ Synthesizes comparison matrix with recommendation
嵌套深度
层级示例状态
1Claude → 协调器✅ 可用
2协调器 → code-reviewer✅ 可用
3code-reviewer → 子任务⚠️ 可用,但上下文会变得稀疏
4+更深层的嵌套❌ 不推荐

最佳实践:将编排控制在 2 层以内。超过这个深度,上下文窗口会缩小,协调也会变得脆弱。

何时使用编排
使用编排使用直接委派
复杂的多阶段工作流单一专家任务
需要整合多个来源的信息简单的审计或审查
并行执行很重要顺序执行即可
需要不同的专家相同类型的 Agent
协调器与直接委派

直接委派(更简单,通常已足够):

User: "Review my code changes"
Claude: [Invokes code-reviewer agent directly]

编排(需要协调时使用):

User: "Prepare release"
Claude: [Invokes release-orchestrator]
        orchestrator: [Spawns code-reviewer, test-runner, doc-validator]
        orchestrator: [Synthesizes all reports]
        [Returns comprehensive release readiness report]
配置说明
  1. 工具访问权限会传递:拥有 Task 的编排器可以启动会话有权访问的任何 Agent
  2. 模型继承:启动的 Agent 使用其配置的模型(或在设为 inherit 时继承模型)
  3. 上下文隔离:每个启动的 Agent 都有自己的上下文窗口
  4. 结果逐级返回:编排器会收到 Agent 的结果,并可对其进行综合处理

高级模式

后台 Agent(异步委派)

将 Agent 发送到后台,同时继续在主会话中工作:

Ctrl+B 可在 Agent 执行期间将其移至后台。

> Use the research-agent to analyze these 10 frameworks
[Agent starts working...]
[Press Ctrl+B]
→ Agent continues in background
→ Main session free for other work
→ Check results later with: "What did the research agent find?"

适用场景:

  • 长时间运行的研究任务
  • 并行获取文档
  • 非阻塞式代码审查
模型选择策略

质量优先的方法:大多数 Agent 默认使用 Sonnet。Haiku 节省的成本很少能弥补质量损失。

模型最适合速度成本质量
sonnet大多数 Agent 的默认选择 - 内容生成、推理、文件创建均衡标准✅ 高
opus创意工作、复杂推理、质量至关重要的输出较慢高端✅ 最高
haiku仅用于简单的脚本执行,且质量无关紧要快 2 倍便宜 3 倍⚠️ 不定
inherit与主对话保持一致不定不定与父级一致

为什么默认使用 Sonnet?

测试显示质量差异显著:

  • Haiku:样式表链接错误、缺少 CSS、数值错误、模式不正确
  • Sonnet:模式正确、验证恰当、错误更少
任务类型推荐模型原因
内容生成Sonnet质量很重要
文件创建Sonnet模式必须正确
编写代码SonnetBug 代价高
审计/审查Sonnet需要判断力
创意工作Opus追求最高质量
部署脚本Haiku(可以)只是运行命令
简单格式检查Haiku(可以)只需判断通过或失败

模式:默认使用 Sonnet,创意工作使用 Opus,只有在质量确实无关紧要时才使用 Haiku:

---
name: site-builder
model: sonnet  # Content quality matters - NOT haiku
tools: Read, Write, Edit, Glob, Grep
---

---
name: creative-director
model: opus  # Creative work needs maximum quality
tools: Read, Write, Edit, Glob, Grep
---

---
name: deploy-runner
model: haiku  # Just running wrangler commands - quality irrelevant
tools: Read, Bash
---
Agent 上下文注意事项

Agent 的上下文用量很大程度上取决于任务:

场景上下文工具调用是否可行?
深度研究 Agent130k90+✅ 可行
多文件审计80k+50+✅ 可行
简单格式检查3k5-10✅ 可行
链式编排不定不定✅ 取决于任务

实际情况:执行有意义的工作时,Agent 即使进行 90+ 次工具调用并使用 130k 上下文,也能正常运行。限制因素是任务复杂度,而非任意设定的 Token 限制。

真正重要的是:

  • Agent 是否在每次工具调用后都有进展?
  • 上下文是否用于实际工作,而非重复指令?
  • 最终结果是否连贯?

上下文何时会成为问题:

  • Agent 开始重复自己或无法理清思路
  • 结果变得不连贯或相互矛盾
  • Agent 在长会话中“忘记”了先前的发现
基于角色的路由

通过明确的约束,防止 Agent 偏离到相邻领域:

---
name: frontend-specialist
description: Frontend code expert. NEVER writes backend logic.
tools: Read, Write, Edit, Glob, Grep
---

You are a frontend specialist.

BOUNDARIES:
- NEVER write backend logic, API routes, or database queries
- ALWAYS use React patterns consistent with the codebase
- If task requires backend work, STOP and report "Requires backend specialist"

FOCUS:
- React components, hooks, state management
- CSS/Tailwind styling
- Client-side routing
- Browser APIs

这样可以避免 Agent 遇到不熟悉的领域时产生幻觉。

Hooks 模式

Hooks 可实现自动验证和反馈:

提交时阻止(强制执行质量门槛):

hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: |
            if [[ "$BASH_COMMAND" == *"git commit"* ]]; then
              npm test || exit 1
            fi

提示型 Hooks(非阻塞反馈):

hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/lint-check.sh"
          # Exits 0 to continue, non-zero to warn

最佳实践:在提交阶段而非计划过程中进行验证。让 Agent 自由工作,并在更改永久生效前发现问题。

嵌套的 CLAUDE.md 上下文

访问相应路径时,Claude 会自动加载子目录中的 CLAUDE.md 文件:

project/
├── CLAUDE.md              # Root context (always loaded)
├── src/
│   └── CLAUDE.md          # Loaded when editing src/**
├── tests/
│   └── CLAUDE.md          # Loaded when editing tests/**
└── docs/
    └── CLAUDE.md          # Loaded when editing docs/**

用途:目录专属的编码标准、本地模式、模块文档。

此上下文采用延迟加载方式——子 Agent 能获取相关上下文,同时避免主提示词臃肿。

主从式与自定义子 Agent

两种委派理念:

自定义子 Agent(明确的专家):

Main Claude → task-runner agent → result
  • 优点:上下文隔离、提示词专业化、可复用
  • 缺点:把关效应(主 Agent 会失去可见性)

主从式(动态委派):

Main Claude → Task(general-purpose) → result
  • 优点:主 Agent 能及时了解情况,路由灵活
  • 缺点:专业化程度较低,可能需要更多指导

建议:对定义明确且重复的任务使用自定义 Agent。对于需要关注主上下文的临时委派,使用 Task(general-purpose)。


委派模式

最佳适用场景

最佳用例:重复执行但需要判断力的任务。

✅ Good fit:
   - Audit 70 skills (repetitive) checking versions against docs (judgment)
   - Update 50 files (repetitive) deciding what needs changing (judgment)
   - Research 10 frameworks (repetitive) evaluating trade-offs (judgment)

❌ Poor fit:
   - Simple find-replace (no judgment needed, use sed/grep)
   - Single complex task (not repetitive, do it yourself)
   - Tasks with cross-item dependencies (agents work independently)
核心提示词模板

以下 5 步结构始终有效:

For each [item]:
1. Read [source file/data]
2. Verify with [external check - npm view, API, docs]
3. Check [authoritative source]
4. Evaluate/score
5. FIX issues found ← Critical: gives agent authority to act

关键要素:

  • “修复发现的问题”——没有这项要求,Agent 只会报告;有了这项要求,它们才会采取行动。
  • 准确的文件路径——避免歧义和修改错误的文件
  • 输出格式模板——确保报告格式一致且可解析
  • 项目列表——明确列出要处理的内容
批次大小
批次大小适用场景
3-5 项复杂任务(深入研究、多步骤修复)
5-8 项标准任务(审计、更新、验证)
8-12 项简单任务(版本检查、格式修复)

为什么不更多?

  • Agent 的上下文会被占满
  • 一次失败不会导致整个批次都出问题
  • 较小的变更集更容易审查

并行 Agent:同时启动 2-4 个 Agent,每个 Agent 处理各自的批次。

工作流模式
┌─────────────────────────────────────────────────────────────┐
│  1. PLAN: Identify items, divide into batches               │
│     └─ "58 skills ÷ 10 per batch = 6 agents"                │
├─────────────────────────────────────────────────────────────┤
│  2. LAUNCH: Parallel Task tool calls with identical prompts │
│     └─ Same template, different item lists                  │
├─────────────────────────────────────────────────────────────┤
│  3. WAIT: Agents work in parallel                           │
│     └─ Read → Verify → Check → Edit → Report                │
├─────────────────────────────────────────────────────────────┤
│  4. REVIEW: Check agent reports and file changes            │
│     └─ git status, spot-check diffs                         │
├─────────────────────────────────────────────────────────────┤
│  5. COMMIT: Batch changes with meaningful changelog         │
│     └─ One commit per tier/category, not per agent          │
└─────────────────────────────────────────────────────────────┘

提示词模板

审计/验证模式
Deep audit these [N] [items]. For each:

1. Read the [source file] from [path]
2. Verify [versions/data] with [command or API]
3. Check official [docs/source] for accuracy
4. Score 1-10 and note any issues
5. FIX issues found directly in the file

Items to audit:
- [item-1]
- [item-2]
- [item-3]

For each item, create a summary with:
- Score and status (PASS/NEEDS_UPDATE)
- Issues found
- Fixes applied
- Files modified

Working directory: [absolute path]
批量更新模式
Update these [N] [items] to [new standard/format]. For each:

1. Read the current file at [path pattern]
2. Identify what needs changing
3. Apply the update following this pattern:
   [show example of correct format]
4. Verify the change is valid
5. Report what was changed

Items to update:
- [item-1]
- [item-2]
- [item-3]

Output format:
| Item | Status | Changes Made |
|------|--------|--------------|

Working directory: [absolute path]
研究/比较模式
Research these [N] [options/frameworks/tools]. For each:

1. Check official documentation at [URL pattern or search]
2. Find current version and recent changes
3. Identify key features relevant to [use case]
4. Note any gotchas, limitations, or known issues
5. Rate suitability for [specific need] (1-10)

Options to research:
- [option-1]
- [option-2]
- [option-3]

Output format:
## [Option Name]
- **Version**: X.Y.Z
- **Key Features**: ...
- **Limitations**: ...
- **Suitability Score**: X/10
- **Recommendation**: ...

自定义子 Agent 示例

代码审查员
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.
调试器
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations

Focus on fixing the underlying issue, not the symptoms.
数据科学家
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---

You are a data scientist specializing in SQL and BigQuery analysis.

When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly

Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations

Always ensure queries are efficient and cost-effective.

提交策略

Agent 不提交代码——它们只编辑文件。这是有意为之:

Agent 负责人工负责
研究与验证审查变更
编辑文件抽查差异
评分与报告git add/commit
创建摘要编写变更日志

为什么?

  • 提交前审查可以发现 Agent 的错误
  • 将多个 Agent 的工作合并为有意义的提交
  • 保持提交历史整洁(而不是 50 个细碎的提交)
  • 由人工决定提交信息和分组

提交模式:

git add [files] && git commit -m "$(cat <<'EOF'
[type]([scope]): [summary]

[Batch 1 changes]
[Batch 2 changes]
[Batch 3 changes]

🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"

错误处理

一个 Agent 失败时
  1. 检查错误消息
  2. 决定:重试该批次,或跳过并继续
  3. 不要让一次失败阻碍整个操作
Agent 做出错误修改时
  1. 使用 git diff [file] 查看更改
  2. 使用 git checkout -- [file] 撤销更改
  3. 使用更具体的说明重新运行
Agent 之间发生冲突时

这种情况很少见(Agent 通常处理不同项目),但如果发生:

  1. 检查哪个 Agent 的更改正确
  2. 手动解决,或重新运行其中一个 Agent

最佳实践

  1. 从 Claude 生成的 Agent 开始:使用 /agents 生成初始配置,然后自定义
  2. 设计职责明确的子 Agent:每个 Agent 只承担一项清晰的职责
  3. 编写详细的提示词:提供具体说明、示例和约束
  4. 非必要时不要授予 Bash 权限:避免反复请求审批(参见“避免 Bash 审批请求泛滥”)
  5. 将关键说明放在最前面:提示词顶部的说明会得到遵循,埋在后面的说明则会被忽略
  6. 删除相互矛盾的说明:如果需要 Write 工具,就删除所有 Bash 示例
  7. 默认使用 Sonnet 模型:质量比节省成本更重要(参见“模型选择”)
  8. 版本控制:将 .claude/agents/ 纳入 git 管理,以便团队共享
  9. 谨慎使用 inherit 指定模型:显式设置模型更有利于获得可预测的行为

性能考量

考量因素影响
上下文效率Agent 可保留主上下文,从而支持更长的会话
延迟子 Agent 从全新状态启动,收集上下文时可能会增加延迟
全面性探索 Agent 的全面性等级,在速度和完整性之间进行权衡

快速参考

Built-in agents:
  Explore  → Haiku, read-only, quick/medium/thorough
  Plan     → Sonnet, plan mode research
  General  → Sonnet, all tools, read/write

Custom agents:
  Project  → .claude/agents/*.md (highest priority)
  User     → ~/.claude/agents/*.md
  CLI      → --agents '{...}'

Config fields:
  name, description (required)
  tools, model, permissionMode, skills, hooks (optional)

Tool access principle:
  ⚠️ Don't give Bash unless agent needs CLI execution
  File creators: Read, Write, Edit, Glob, Grep (no Bash!)
  Script runners: Read, Write, Edit, Glob, Grep, Bash (only if needed)
  Research: Read, Grep, Glob, WebFetch, WebSearch

Model selection (quality-first):
  Default: sonnet (most agents - quality matters)
  Creative: opus (maximum quality)
  Scripts only: haiku (just running commands)
  ⚠️ Avoid Haiku for content generation - quality drops significantly

Instruction placement:
  ⛔ Critical instructions go FIRST (right after frontmatter)
  ⚠️ Instructions buried 300+ lines deep get ignored
  ✅ Remove contradictory instructions (pick one pattern)

Delegation:
  Batch size: 5-8 items per agent
  Parallel: 2-4 agents simultaneously
  Prompt: 5-step (read → verify → check → evaluate → FIX)

Orchestration:
  Enable: Add "Task" to agent's tools list
  Depth: Keep to 2 levels max
  Use: Multi-phase workflows, parallel specialists

Advanced:
  Background: Ctrl+B during agent execution
  Context: 130k+ and 90+ tool calls work fine for real work
  Hooks: PreToolUse, PostToolUse, Stop events

Resume agents:
  > Resume agent [agentId] and continue...

参考资料

官方文档
社区资源

最后更新:2026-02-02

评论

支持 Markdown