Claude Code官方文档子代理Sub-agents

Claude Code Sub-agents 子代理 - 多任务并行与上下文隔离

用专门的 subagents 处理隔离任务,节省主对话上下文,限定工具与权限,并跨项目复用配置;含内置代理、frontmatter 字段和分叉模式。

· 阅读约 32 分钟

Subagents 是处理特定类型任务的专门 AI 助手。当一个辅助任务会用搜索结果、日志或文件内容充斥您的主对话,而您不会再次引用这些内容时,请使用一个 subagent:该 subagent 在自己的上下文中完成这项工作,仅返回摘要。当您不断生成相同类型的工作者并使用相同的指令时,定义一个自定义 subagent。

每个 subagent 在自己的 context window 中运行,具有自定义系统提示、特定的工具访问权限和独立的权限。当 Claude 遇到与 subagent 描述相匹配的任务时,它会委托给该 subagent,该 subagent 独立工作并返回结果。

ℹ️ 如果您需要多个代理并行工作并相互通信,请参阅 agent teams 代替。Subagents 在单个会话中工作;agent teams 跨多个会话进行协调。

Subagents 帮助您:

  • 保留上下文,通过将探索和实现保持在主对话之外
  • 强制执行约束,通过限制 subagent 可以使用的工具
  • 跨项目重用配置,使用用户级 subagents
  • 专门化行为,为特定领域使用专注的系统提示
  • 控制成本,通过将任务路由到更快、更便宜的模型(如 Haiku)

Claude 使用每个 subagent 的描述来决定何时委托任务。创建 subagent 时,请编写清晰的描述,以便 Claude 知道何时使用它。

内置 subagents

Claude Code 包括内置 subagents,Claude 在适当时自动使用。每个都继承父对话的权限,并有额外的工具限制。

Explore

一个快速的、只读的代理,针对搜索和分析代码库进行了优化。

  • Model: Haiku(快速、低延迟)
  • Tools: 只读工具(拒绝访问 Write 和 Edit 工具)
  • Purpose: 文件发现、代码搜索、代码库探索

当 Claude 需要搜索或理解代码库而不进行更改时,它会委托给 Explore。这样可以将探索结果保持在主对话上下文之外。

调用 Explore 时,Claude 指定一个彻底程度级别:quick 用于有针对性的查找,medium 用于平衡的探索,或 very thorough 用于全面分析。

Plan

一个研究代理,在 plan mode 期间使用,以在呈现计划之前收集上下文。

  • Model: 从主对话继承
  • Tools: 只读工具(拒绝访问 Write 和 Edit 工具)
  • Purpose: 用于规划的代码库研究

General-purpose

一个能够处理复杂、多步骤任务的代理,需要探索和操作。

  • Model: 从主对话继承
  • Tools: 所有工具
  • Purpose: 复杂研究、多步骤操作、代码修改

Other

Claude Code 包括用于特定任务的其他辅助代理。这些通常会自动调用,因此您不需要直接使用它们。

AgentModelClaude 何时使用它
statusline-setupSonnet当您运行 /statusline 来配置您的状态行时
claude-code-guideHaiku当您提出关于 Claude Code 功能的问题时

快速入门:创建您的第一个 subagent

Subagents 在带有 YAML frontmatter 的 Markdown 文件中定义。您可以手动创建它们或使用 /agents 命令。

本演练指导您使用 /agents 命令创建用户级 subagent。

步骤 1:打开 subagents 界面

在 Claude Code 中,运行:

/agents

步骤 2:选择一个位置

切换到 Library 选项卡,选择 Create new agent,然后选择 Personal。这会将 subagent 保存到 ~/.claude/agents/,以便在所有项目中可用。

步骤 3:使用 Claude 生成

选择 Generate with Claude。出现提示时,描述 subagent:

A code improvement agent that scans files and suggests improvements
for readability, performance, and best practices. It should explain
each issue, show the current code, and provide an improved version.

Claude 为您生成标识符、描述和系统提示。

步骤 4:选择工具

对于只读审查者,取消选择除 Read-only tools 之外的所有内容。

步骤 5:选择模型

选择 subagent 使用的模型。对于此示例代理,选择 Sonnet

步骤 6:选择颜色

为 subagent 选择背景颜色。

步骤 7:配置内存

选择 User scope 为 subagent 提供一个持久内存目录,位于 ~/.claude/agent-memory/

步骤 8:保存并尝试

查看配置摘要。按 sEnter 保存。Subagent 立即可用。尝试它:

Use the code-improver agent to suggest improvements in this project

配置 subagents

使用 /agents 命令

/agents 命令打开一个选项卡式界面来管理 subagents。Running 选项卡显示实时 subagents,让您打开或停止它们。Library 选项卡让您:

  • 查看所有可用的 subagents
  • 使用引导式设置或 Claude 生成创建新的 subagents
  • 编辑现有 subagent 配置和工具访问
  • 删除自定义 subagents
  • 查看当存在重复时哪些 subagents 是活跃的

要从命令行列出所有配置的 subagents 而不启动交互式会话,请运行 claude agents

选择 subagent 范围

Subagents 是带有 YAML frontmatter 的 Markdown 文件。根据范围将它们存储在不同的位置。当多个 subagents 共享相同的名称时,更高优先级的位置获胜。

LocationScopePriority如何创建
托管设置组织范围1(最高)通过托管设置部署
--agents CLI 标志当前会话2启动 Claude Code 时传递 JSON
.claude/agents/当前项目3交互式或手动
~/.claude/agents/所有您的项目4交互式或手动
Plugin 的 agents/ 目录启用 plugin 的位置5(最低)与 plugins 一起安装

项目 subagents.claude/agents/)非常适合特定于代码库的 subagents。将它们检入版本控制。

用户 subagents~/.claude/agents/)是在所有项目中可用的个人 subagents。

CLI 定义的 subagents 在启动 Claude Code 时作为 JSON 传递。它们仅存在于该会话中:

macOS、Linux、WSL

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"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  }
}'

Windows PowerShell

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"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  }
}
'@

ℹ️ 出于安全原因,plugin subagents 不支持 hooksmcpServerspermissionMode frontmatter 字段。加载来自 plugin 的代理时,这些字段被忽略。

编写 subagent 文件

Subagent 文件使用 YAML frontmatter 进行配置,然后是 Markdown 中的系统提示:

ℹ️ Subagents 在会话启动时加载。如果您直接在磁盘上添加或编辑 subagent 文件,请重启您的会话以加载它。通过 /agents 界面创建的 Subagents 无需重启即可立即生效。

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

支持的 frontmatter 字段

以下字段可以在 YAML frontmatter 中使用。只有 namedescription 是必需的。

FieldRequiredDescription
nameYes使用小写字母和连字符的唯一标识符
descriptionYesClaude 何时应该委托给此 subagent
toolsNosubagent 可以使用的工具。如果省略,继承所有工具
disallowedToolsNo要拒绝的工具,从继承或指定的列表中删除
modelNo使用的模型:sonnetopushaiku、完整模型 ID 或 inherit。默认为 inherit
permissionModeNo权限模式:defaultacceptEditsautodontAskbypassPermissionsplan
maxTurnsNosubagent 停止前的最大代理轮数
skillsNo在启动时加载到 subagent 的上下文中的 skills
mcpServersNo对此 subagent 可用的 MCP servers
hooksNo限定于此 subagent 的生命周期 hooks
memoryNo持久内存范围:userprojectlocal
backgroundNo设置为 true 以始终将此 subagent 作为后台任务运行
effortNo此 subagent 活跃时的努力级别
isolationNo设置为 worktree 以在临时 git worktree 中运行
colorNoSubagent 在任务列表和转录中的显示颜色
initialPromptNo当此代理作为主会话代理运行时,自动提交为第一个用户轮次

选择模型

model 字段控制 subagent 使用的 AI model:

  • Model alias: 使用可用的别名之一:sonnetopushaiku
  • Full model ID: 使用完整的模型 ID,如 claude-opus-4-7claude-sonnet-4-6
  • inherit: 使用与主对话相同的模型
  • Omitted: 默认为 inherit

Claude Code 按以下顺序解析 subagent 的模型:

  1. CLAUDE_CODE_SUBAGENT_MODEL 环境变量,如果设置
  2. 每次调用的 model 参数
  3. Subagent 定义的 model frontmatter
  4. 主对话的模型

控制 subagent 能力

可用工具

Subagents 可以使用 Claude Code 的任何内部工具。默认情况下,subagents 继承主对话的所有工具,包括 MCP 工具。

要限制工具,使用 tools 字段(允许列表)或 disallowedTools 字段(拒绝列表):

---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---
---
name: no-writes
description: Inherits every tool except file writes
disallowedTools: Write, Edit
---

限制可以生成哪些 subagents

当代理作为主线程运行时,使用 claude --agent,它可以使用 Agent 工具生成 subagents。要限制它可以生成的 subagent 类型,在 tools 字段中使用 Agent(agent_type) 语法。

---
name: coordinator
description: Coordinates work across specialized agents
tools: Agent(worker, researcher), Read, Bash
---

将 MCP 服务器限定于 subagent

使用 mcpServers 字段为 subagent 提供对主对话中不可用的 MCP 服务器的访问。

---
name: browser-tester
description: Tests features in a real browser using Playwright
mcpServers:
  - playwright:
      type: stdio
      command: npx
      args: ["-y", "@playwright/mcp@latest"]
  - github
---

Use the Playwright tools to navigate, screenshot, and interact with pages.

权限模式

permissionMode 字段控制 subagent 如何处理权限提示。

ModeBehavior
default标准权限检查,带有提示
acceptEdits自动接受文件编辑和工作目录中路径的常见文件系统命令
autoAuto mode:后台分类器审查命令和受保护目录的写入
dontAsk自动拒绝权限提示(显式允许的工具仍然工作)
bypassPermissions跳过权限提示
planPlan mode(只读探索)

⚠️ 谨慎使用 bypassPermissions。它跳过权限提示,允许 subagent 在没有批准的情况下执行操作,包括对 .git.claude.vscode.idea.husky 的写入。

将技能预加载到 subagents

使用 skills 字段在启动时将技能内容注入到 subagent 的上下文中:

---
name: api-developer
description: Implement API endpoints following team conventions
skills:
  - api-conventions
  - error-handling-patterns
---

Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

启用持久内存

memory 字段为 subagent 提供一个在对话中幸存的持久目录。

---
name: code-reviewer
description: Reviews code for quality and best practices
memory: user
---

You are a code reviewer. As you review code, update your agent memory with
patterns, conventions, and recurring issues you discover.
ScopeLocation使用时机
user~/.claude/agent-memory/<name-of-agent>/subagent 应该在所有项目中记住学习
project.claude/agent-memory/<name-of-agent>/subagent 的知识是特定于项目的并可通过版本控制共享
local.claude/agent-memory-local/<name-of-agent>/subagent 的知识是特定于项目的但不应检入版本控制

使用 hooks 的条件规则

为了更动态地控制工具使用,使用 PreToolUse hooks 在执行前验证操作。

---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---

禁用特定 subagents

您可以通过将 subagents 添加到您的设置中的 deny 数组来防止 Claude 使用特定 subagents。使用格式 Agent(subagent-name)

{
  "permissions": {
    "deny": ["Agent(Explore)", "Agent(my-custom-agent)"]
  }
}

这对内置和自定义 subagents 都有效。您也可以使用 --disallowedTools CLI 标志:

claude --disallowedTools "Agent(Explore)"

为 subagents 定义 hooks

Subagents 可以定义在 subagent 的生命周期中运行的 hooks。有两种方式来配置 hooks:

  1. 在 subagent 的 frontmatter 中:定义仅在该 subagent 活跃时运行的 hooks
  2. settings.json:定义在 subagents 启动或停止时在主会话中运行的 hooks

Subagent frontmatter 中的 Hooks

直接在 subagent 的 markdown 文件中定义 hooks。

---
name: code-reviewer
description: Review code changes with automatic linting
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-command.sh $TOOL_INPUT"
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

用于 subagent 事件的项目级 hooks

settings.json 中配置 hooks,以响应主会话中的 subagent 生命周期事件。

EventMatcher input何时触发
SubagentStartAgent type name当 subagent 开始执行时
SubagentStopAgent type name当 subagent 完成时
{
  "hooks": {
    "SubagentStart": [
      {
        "matcher": "db-agent",
        "hooks": [
          { "type": "command", "command": "./scripts/setup-db-connection.sh" }
        ]
      }
    ],
    "SubagentStop": [
      {
        "hooks": [
          { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }
        ]
      }
    ]
  }
}

使用 subagents

理解自动委托

Claude 根据您请求中的任务描述、subagent 配置中的 description 字段和当前上下文自动委托任务。要鼓励主动委托,在您的 subagent 的 description 字段中包含”use proactively”之类的短语。

显式调用 subagents

当自动委托不够时,您可以自己请求 subagent。三种模式从一次性建议升级到会话范围的默认值:

  • 自然语言:在提示中命名 subagent;Claude 决定是否委托
  • @-mention:保证 subagent 为一个任务运行
  • 会话范围:整个会话使用该 subagent 的系统提示、工具限制和模型,通过 --agent 标志或 agent 设置

对于自然语言:

Use the test-runner subagent to fix failing tests
Have the code-reviewer subagent look at my recent changes

@-mention subagent。 输入 @ 并从类型提前中选择 subagent,就像您 @-mention 文件一样:

@"code-reviewer (agent)" look at the auth changes

将整个会话作为 subagent 运行。 传递 --agent <name> 以启动一个会话:

claude --agent code-reviewer

要使其成为项目中每个会话的默认值,在 .claude/settings.json 中设置 agent

{
  "agent": "code-reviewer"
}

在前台或后台运行 subagents

Subagents 可以在前台(阻塞)或后台(并发)运行:

  • 前台 subagents 阻塞主对话直到完成。权限提示和澄清问题会传递给您。
  • 后台 subagents 在您继续工作时并发运行。启动前,Claude Code 会提示您 subagent 需要的任何工具权限。

Claude 根据任务决定是否在前台或后台运行 subagents。您也可以:

  • 要求 Claude “run this in the background”
  • Ctrl+B 将运行中的任务放在后台

要禁用所有后台任务功能,请将 CLAUDE_CODE_DISABLE_BACKGROUND_TASKS 环境变量设置为 1

常见模式

隔离高容量操作

subagents 最有效的用途之一是隔离产生大量输出的操作。运行测试、获取文档或处理日志文件可能会消耗大量上下文。

Use a subagent to run the test suite and report only the failing tests with their error messages

运行并行研究

对于独立的调查,生成多个 subagents 以同时工作:

Research the authentication, database, and API modules in parallel using separate subagents

⚠️ 当 subagents 完成时,它们的结果返回到您的主对话。运行许多 subagents,每个都返回详细结果,可能会消耗大量上下文。

链接 subagents

对于多步骤工作流,要求 Claude 按顺序使用 subagents。

Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

在 subagents 和主对话之间选择

在以下情况下使用 主对话

  • 任务需要频繁的来回或迭代细化
  • 多个阶段共享重要上下文(规划 → 实现 → 测试)
  • 您正在进行快速、有针对性的更改
  • 延迟很重要

在以下情况下使用 subagents

  • 任务产生您不需要在主上下文中的详细输出
  • 您想强制执行特定的工具限制或权限
  • 工作是自包含的,可以返回摘要

ℹ️ Subagents 无法生成其他 subagents。如果您的工作流需要嵌套委托,请使用 Skills 或从主对话链接 subagents。

管理 subagent 上下文

恢复 subagents

每个 subagent 调用都会创建一个具有新鲜上下文的新实例。要继续现有 subagent 的工作而不是重新开始,要求 Claude 恢复它。

恢复的 subagents 保留其完整的对话历史,包括所有以前的工具调用、结果和推理。

自动压缩

Subagents 支持使用与主对话相同的逻辑进行自动压缩。默认情况下,自动压缩在大约 95% 容量时触发。

分叉当前对话

ℹ️ 分叉 subagents 是实验性的,需要 Claude Code v2.1.117 或更高版本。通过将 CLAUDE_CODE_FORK_SUBAGENT 环境变量设置为 1 来启用它们。

分叉是一个 subagent,它继承到目前为止的整个对话,而不是从头开始。这消除了 subagents 通常提供的输入隔离:分叉看到与主会话相同的系统提示、工具、模型和消息历史。

启用分叉模式以三种方式改变 Claude Code:

  • Claude 在它会使用 general-purpose subagent 时生成分叉。命名 subagents 如 Explore 仍然像以前一样生成。
  • 每个 subagent 生成都在 background 中运行,无论它是分叉还是命名 subagent。
  • /fork 命令生成分叉而不是充当 /branch 的别名。

您可以使用 /fork 后跟指令自己启动分叉:

/fork draft unit tests for the parser changes so far

观察和引导运行中的分叉

运行中的分叉出现在提示输入下方的面板中。使用这些键与面板交互:

KeyAction
/ 在行之间移动
Enter打开所选分叉的转录并向其发送后续消息
x关闭完成的分叉或停止运行中的分叉
Esc将焦点返回到提示输入

分叉与命名 subagents 的区别

分叉继承主会话在生成时拥有的一切。命名 subagent 从自己的定义开始。

分叉命名 subagent
上下文完整的对话历史新鲜上下文,带有您传递的提示
系统提示和工具与主会话相同来自 subagent 的定义文件
模型与主会话相同来自 subagent 的 model 字段
权限提示在您的终端中出现启动前预先批准,然后自动拒绝
Prompt cache与主会话共享单独的缓存

示例 subagents

这些示例演示了构建 subagents 的有效模式。

💡 最佳实践:

  • 设计专注的 subagents: 每个 subagent 应该在一个特定任务中表现出色
  • 编写详细的描述: Claude 使用描述来决定何时委托
  • 限制工具访问: 仅授予必要的权限以确保安全和专注
  • 检入版本控制: 与您的团队共享项目 subagents

代码审查者

一个只读 subagent,审查代码而不修改它。

---
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.

调试器

一个可以分析和修复问题的 subagent。

---
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.

数据科学家

一个用于数据分析工作的特定领域 subagent。

---
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

For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data

Always ensure queries are efficient and cost-effective.

数据库查询验证器

一个允许 Bash 访问但验证命令以仅允许只读 SQL 查询的 subagent。

---
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---

You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.

When asked to analyze data:
1. Identify which tables contain the relevant data
2. Write efficient SELECT queries with appropriate filters
3. Present results clearly with context

You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.

验证脚本(./scripts/validate-readonly-query.sh):

#!/bin/bash
# Blocks SQL write operations, allows SELECT queries

# Read JSON input from stdin
INPUT=$(cat)

# Extract the command field from tool_input using jq
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

if [ -z "$COMMAND" ]; then
  exit 0
fi

# Block write operations (case-insensitive)
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then
  echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
  exit 2
fi

exit 0

在 macOS 和 Linux 上,使脚本可执行:

chmod +x ./scripts/validate-readonly-query.sh

后续步骤


本文翻译自 Anthropic Claude Code 官方文档,最近一次同步:2025-05-01。