Claude Code中英文系列教程19:使用subagent子代理与创建自定义子代理【重要】

Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.

在 Claude Code 中创建和使用专门用于特定工作流程和改进上下文管理的 AI 子代理。

Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results.

子代理是处理特定类型任务的专门 AI 助手。每个子代理在自己的上下文窗口中运行,具有自定义系统提示、特定工具访问权限和独立权限。当 Claude 遇到与子代理描述匹配的任务时,它会委托给该子代理,该子代理独立工作并返回结果。

Subagents help you: 子代理可以帮助你:

1.Preserve context by keeping exploration and implementation out of your main conversation

通过将探索和实现保持在主对话之外来保留上下文

2.Enforce constraints by limiting which tools a subagent can use

通过限制子代理可以使用的工具 来执行约束

3.Reuse configurations across projects with user-level subagents

使用用户级别的子代理跨项目重用配置

4.Specialize behavior with focused system prompts for specific domains

使用针对特定领域的更专注的系统提示词来专门化行为

5.Control costs by routing tasks to faster, cheaper models like Haiku

通过将任务路由到更快、更便宜的模型(如 Haiku)来控制成本

Claude uses each subagent's description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it.

Claude 使用每个子代理的描述来决定何时委派任务。当你创建一个子代理时,请写一个清晰的描述,以便 Claude 知道何时使用它。

Claude Code includes several built-in subagents like Explore, Plan, and general-purpose. You can also create custom subagents to handle specific tasks.

Claude Code 包括几个内置的子代理,如 Explore、Plan 和通用型。你也可以创建自定义的子代理来处理特定任务。

一,Built-in subagents 内置子代理

Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation's permissions with additional tool restrictions.

Claude Code 包含内置子代理,Claude 在适当的时候会自动使用这些子代理。每个子代理都会继承父对话的权限,并带有额外的工具限制。

1, Explore 探索子代理

A fast, read-only agent optimized for searching and analyzing codebases.

一个快速、只读的代理,专为搜索和分析代码库而优化。

Model: Haiku (fast, low-latency)

模型:Haiku(快速,低延迟)

Tools: Read-only tools (denied access to Write and Edit tools)

工具:只读工具(无法访问写入和编辑工具)

Purpose: File discovery, code search, codebase exploration

用途:文件发现、代码搜索、代码库探索

Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.

当 Claude 需要搜索或理解代码库而不进行修改时,它会将任务委托给 Explore。这样可以确保探索结果不会干扰到你的对话上下文。

When invoking Explore, Claude specifies a thoroughness level: quick for targeted lookups, medium for balanced exploration, or very thorough for comprehensive analysis.

调用 Explore 时,Claude 会指定详细程度级别:quick用于目标查找,medium用于平衡探索,或 very thorough非常彻底用于全面分析。

2,Plan 计划子代理

A research agent used during plan mode to gather context before presenting a plan.

一个在计划模式下使用的调研代理,用于在展示计划前收集背景信息。

Model: Inherits from main conversation

模型:继承自主对话

Tools: Read-only tools (denied access to Write and Edit tools)

工具:只读工具(拒绝访问写入和编辑工具)

Purpose: Codebase research for planning

目的:为规划进行代码库研究

When you're in plan mode and Claude needs to understand your codebase, it delegates research to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still gathering necessary context.

当你在计划模式下,Claude 需要理解你的代码库时,它会将研究任务委托给计划子代理。这防止了无限嵌套(子代理不能生成其他子代理),同时仍然收集必要的上下文。

  1. General-purpose 通用型子代理

A capable agent for complex, multi-step tasks that require both exploration and action.

一个能够处理复杂、多步骤任务,并且需要同时进行探索和行动的智能代理。

Model: Inherits from main conversation

模型:继承自主对话

Tools: All tools 工具:所有工具

Purpose: Complex research, multi-step operations, code modifications

用途:复杂研究、多步骤操作、代码修改

Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps.

当任务需要探索和修改、复杂推理来解释结果,或多个依赖步骤时,Claude 会委托给通用工具。

4,Other 其它辅助代理

Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly.

Claude Code 包含用于特定任务的额外辅助代理。这些通常会被自动调用,因此你无需直接使用它们。

4.1 Bash代理:它使用Inherits 继承的模型,

什么时候会被调用:

Running terminal commands in a separate context

在单独的上下文中运行终端命令时

4.2 statusline-setup 状态行设置

使用Sonnet模型

When you run /statusline to configure your status line

当你运行 /statusline 来配置你的状态行时被调用

4.3 Claude Code Guide Claude Code 指南

使用Haiku 模型

When you ask questions about Claude Code features

当你询问有关 Claude Code 功能的问题时被调用

Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills.

除了这些内置的子代理,你还可以使用自定义提示、工具限制、权限模式、钩子和技能来创建自己的子代理。

二,Quickstart: create your first subagent

快速入门:创建你的第一个子代理

Subagents are defined in Markdown files with YAML frontmatter. You can create them manually or use the /agents command.

子代理在 Markdown 文件中使用 YAML 前导内容进行定义。你可以手动创建它们(下面会讲到),或使用 /agents 命令。

This walkthrough guides you through creating a user-level subagent with the /agent command. The subagent reviews code and suggests improvements for the codebase.

本指南将指导你使用 /agent 命令创建一个用户级别的子代理。该子代理会审查代码并为代码库提出改进建议。

分以下7步

2.1 Open the subagents interface

打开子代理界面

In Claude Code, run: 在 Claude Code 中运行:

/agents

2.2 Create a new user-level agent

创建一个新的用户级代理

Select Create new agent, then choose User-level. This saves the subagent to ~/.claude/agents/ so it's available in all your projects.

选择创建新代理,然后选择用户级别。这将把子代理保存到 ~/.claude/agents/ ,以便在所有你的项目中使用。

2.3 Generate with Claude 使用 Claude 生成

Select Generate with Claude. When prompted, describe the subagent:

选择使用 Claude 生成。当提示时,描述子代理,比如:

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.

一个代码改进agent,它扫描文件并对可读性、性能和最佳实践提出改进建议。它应该解释每个问题,显示当前代码,并提供改进版本。

Claude generates the system prompt and configuration. Press e to open it in your editor if you want to customize it.

Claude 生成系统提示词和配置。如果你想自定义它,按 e 在你的编辑器中打开它。

2.4 Select tools 选择工具

For a read-only reviewer, deselect everything except Read-only tools. If you keep all tools selected, the subagent inherits all tools available to the main conversation.

对于只读审阅者,除了只读工具外取消选中其它所有选项。如果你保持所有工具都选中,子代理只会继承主对话中所有可用的工具。

2.5 Select model 选择模型

Choose which model the subagent uses. For this example agent, select Sonnet, which balances capability and speed for analyzing code patterns.

选择子代理使用的模型。对于此示例代理,选择 Sonnet,它平衡了能力和速度,用于分析代码模式。

2.6 Choose a color 选择一个颜色

Pick a background color for the subagent. This helps you identify which subagent is running in the UI.

为子代理选择一个背景颜色。这有助于你在 UI 中识别哪个子代理正在运行。

2.7 Save and try it out

保存并试一下

Save the subagent. It's available immediately (no restart needed). Try it:

保存子代理。它立即可用(无需重启)。试试看,如输入如下提示词:

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

使用code-improver agent对项目提出改进建议

Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.

Claude 将任务委托给你的新子代理,它会扫描代码库并返回改进建议。

You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements.

现在你拥有一个子代理,可以在你机器上的任何项目中使用,用于分析代码库并提出改进建议。

You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins.

你也可以手动创建子代理,作为 Markdown 文件,通过 CLI 标志定义,或通过插件分发。

三,Configure subagents 配置子代理

3.1 Use the /agents command 使用 /agents 命令

The /agents command provides an interactive interface for managing subagents. Run /agents to:

/agents 命令提供了一个交互式界面来管理子代理。运行 /agents 来:

View all available subagents (built-in, user, project, and plugin)

查看所有可用的子代理(内置、用户、项目和插件)

Create new subagents with guided setup or Claude generation

通过引导设置或 Claude 生成创建新的子代理

Edit existing subagent configuration and tool access

编辑现有子代理的配置和工具访问权限

Delete custom subagents 删除自定义子代理

See which subagents are active when duplicates exist

当存在重复时查看哪些子代理处于活动状态

This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.

这是创建和管理子代理的推荐方法。对于手动创建或自动化,你也可以直接添加子代理文件。

3.2 Choose the subagent scope 选择子代理作用范围

Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.

子代理是带有 YAML 前导块的 Markdown 文件。根据作用范围将它们存储在不同的位置。当多个子代理共享相同名称时,优先级更高的位置将生效。

分以下4种情况,

1,--agents CLI flag 命令行标志

只作用于Current session 当前会话

优先级为 1 (highest) 最高

如何使用:Pass JSON when launching Claude Code

启动 Claude Code 时传递 JSON

2,.claude/agents/

只作用于Current project 当前项目

优先级为 2

通过 Interactive or manual 交互式或手动创建

3,~/.claude/agents/

适用于All your projects 所有你的项目

优先级为3

通过 Interactive or manual 交互式或手动创建

4,Plugin's agents/ directory 插件的 agents/ 目录

Scope作用范围:Where plugin is enabled 插件启用位置

优先级为4 (lowest) 最低

Installed with plugins 随插件安装


a.Project subagents (.claude/agents/) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively.

项目子代理( .claude/agents/ )非常适合特定代码库的子代理。将它们提交到版本控制中,以便你的团队可以协作使用和改进它们。

b.User subagents (~/.claude/agents/) are personal subagents available in all your projects.

用户子代理( ~/.claude/agents/ )是你所有项目中都可用的个人子代理。

c,CLI-defined subagents are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts:

CLI 定义的子代理在启动 Claude Code 时通过 JSON 传递。它们仅存在于该会话中,不会保存到磁盘,因此适用于快速测试或自动化脚本:

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"

}

}'

代码审查专家。在代码更改后主动使用。

你是一名高级代码审阅员。关注代码质量、安全性和最佳实践。

The --agents flag accepts JSON with the same fields as frontmatter. Use prompt for the system prompt (equivalent to the markdown body in file-based subagents).

--agents 标志接受与 frontmatter 相同字段的 JSON。使用 prompt 作为系统提示(相当于基于文件的子代理中的 markdown 正文)。

d,Plugin subagents come from plugins you've installed. They appear in /agents alongside your custom subagents.

插件子代理来自你已安装的插件。它们与你的自定义子代理一起出现在 /agents 中。

3.3 Write subagent files 编写子代理文件

Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:

子代理文件使用 YAML frontmatter 进行配置,随后是 Markdown 格式的系统提示:

Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use /agents to load it immediately.

子代理在会话启动时加载。如果你通过手动添加文件创建子代理,请重启会话或使用 /agents 立即加载它。

```bash


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.

```

审查代码的质量和最佳实践

你是一个代码审查者。当被调用时,分析代码并提供关于质量、安全性和最佳实践的具体的、可操作的反馈。

The frontmatter defines the subagent's metadata and configuration. The body becomes the system prompt that guides the subagent's behavior.

Subagents receive only this system prompt (plus basic environment details like working directory), not the full Claude Code system prompt.

frontmatter定义了子代理的元数据和配置。正文成为指导子代理行为的系统提示。

子代理只接收这个系统提示(加上基本环境详情,如工作目录),而不是完整的 Claude Code 系统提示。

3.3.1 Supported frontmatter fields 支持的 frontmatter 字段

The following fields can be used in the YAML frontmatter. Only name and description are required.

以下字段可用于 YAML 前导块。只有 name 和 description 是必需的。

name:Unique identifier using lowercase letters and hyphens

使用小写字母和连字符的唯一标识符

description:When Claude should delegate to this subagent

Claude 何时应将任务委托给此子代理

tools: Tools the subagent can use. Inherits all tools if omitted

子代理可使用的工具。如果省略,则继承所有工具

disallowedTools:Tools to deny, removed from inherited or specified list

要拒绝的工具,从继承或指定列表中移除

model: Model to use: sonnet, opus, haiku, or inherit. Defaults to inherit

使用的模型: sonnet , opus , haiku ,或 inherit 。默认为 inherit 继承

permissionMode: Permission mode: default, acceptEdits, dontAsk, bypassPermissions, or plan

权限模式: default , acceptEdits , dontAsk , bypassPermissions ,或 plan

skills:Skills to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation

加载到子代理上下文中的技能。完整技能内容被注入,而不仅仅是可供调用。子代理不会从父对话中继承技能

hooks:Lifecycle hooks scoped to this subagent

仅限于此子代理的生命周期钩子

3.4 Choose a model 选择模型

The model field controls which AI model the subagent uses:

model 字段控制子代理使用的 AI 模型:

Model alias: Use one of the available aliases: sonnet, opus, or haiku

模型别名:使用可用的别名之一: sonnet , opus ,或 haiku

inherit: Use the same model as the main conversation

继承:使用与主对话相同的模型

Omitted: If not specified, defaults to inherit (uses the same model as the main conversation)

省略:如果未指定,默认为 inherit (使用与主对话相同的模型)

3.5 Control subagent capabilities 控制子代理功能

You can control what subagents can do through tool access, permission modes, and conditional rules.

你可以通过工具访问权限、权限模式和条件规则来控制子代理能做什么。

3.5.1 Available tools 可用工具

Subagents can use any of Claude Code's internal tools. By default, subagents inherit all tools from the main conversation, including MCP tools.

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

To restrict tools, use the tools field (allowlist) or disallowedTools field (denylist):

要限制工具,请使用 tools 字段(允许列表)或 disallowedTools 字段(禁止列表),如:

```bash


name: safe-researcher

description: Research agent with restricted capabilities

tools: Read, Grep, Glob, Bash

disallowedTools: Write, Edit


能力受限的研究agent

```

3.5.2 Permission modes 权限模式

The permissionMode field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.

permissionMode 字段控制子代理如何处理权限提示。子代理继承主对话的权限上下文,但可以覆盖模式。

有如下5种权限模式

1,default:Standard permission checking with prompts

标准权限检查与提示

2,acceptEdits

Auto-accept file edits 自动接受文件编辑

3,dontAsk

Auto-deny permission prompts (explicitly allowed tools still work)

自动拒绝权限提示(明确允许的工具仍然有效)

4,bypassPermissions

Skip all permission checks

跳过所有权限检查、

5,plan

Plan mode (read-only exploration)

计划模式(只读探索)

Use bypassPermissions with caution. It skips all permission checks, allowing the subagent to execute any operation without approval.

谨慎使用 bypassPermissions 。它会跳过所有权限检查,允许子代理无须经批准执行任何操作。

If the parent uses bypassPermissions, this takes precedence and cannot be overridden.

如果父代理使用 bypassPermissions ,这将优先执行且无法被覆盖。

3.5.3 Preload skills into subagents

将技能预加载到子代理中

Use the skills field to inject skill content into a subagent's context at startup. This gives the subagent domain knowledge without requiring it to discover and load skills during execution.

使用 skills 字段在子代理启动时将技能内容注入其上下文中。这使子代理获得领域知识,而无需在执行过程中发现和加载技能。

```bash


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.

```

按照团队约定实现API端点

实现API端点。遵循预加载技能中的约定和模式。

The full content of each skill is injected into the subagent's context, not just made available for invocation. Subagents don't inherit skills from the parent conversation; you must list them explicitly.

每个技能的完整内容都会注入到子代理的上下文中,而不仅仅是可供调用。子代理不会从父对话中继承技能;你必须明确列出它们。

This is the inverse of running a skill in a subagent. With skills in a subagent, the subagent controls the system prompt and loads skill content.

With context: fork in a skill, the skill content is injected into the agent you specify. Both use the same underlying system.

这与在子代理中运行技能的情况相反。在子代理中使用 skills 时,子代理控制系统提示并加载技能内容。

在技能中使用 context: fork 时,技能内容会被注入到你指定的agent中。两者都使用相同的底层系统。

3.5.4 Conditional rules with hooks

带钩子的条件规则

For more dynamic control over tool usage, use PreToolUse hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.

为了更灵活地控制工具的使用,使用 PreToolUse 钩子在操作执行前进行验证。这在需要允许某些工具操作而阻止其他操作时很有用。

This example creates a subagent that only allows read-only database queries. The PreToolUse hook runs the script specified in command before each Bash command executes:

下面示例创建了一个子代理,仅允许只读数据库查询。 PreToolUse 钩子在每次 Bash 命令执行前运行 command 中指定的脚本:

```bash


name: db-reader

description: Execute read-only database queries

tools: Bash

hooks:

PreToolUse:

  • matcher: "Bash"

hooks:

  • type: command

command: "./scripts/validate-readonly-query.sh"


```

执行只读数据库查询

Claude Code passes hook input as JSON via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and exits with code 2 to block write operations:

Claude Code 通过标准输入(stdin)将钩子输入作为 JSON 传递给钩子命令。验证脚本读取这个 JSON,提取 Bash 命令,并以代码 2 退出来阻止写操作:

```bash

#!/bin/bash

./scripts/validate-readonly-query.sh

INPUT=$(cat)

COMMAND=(echo "INPUT" | jq -r '.tool_input.command // empty')

Block SQL write operations (case-insensitive)

if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then

echo "Blocked: Only SELECT queries are allowed" >&2

exit 2

fi

exit 0

```

See Hook input for the complete input schema and exit codes for how exit codes affect behavior.

查看 Hook 输入以获取完整的输入模式,并查看退出代码以了解退出代码如何影响行为。

3.5.5 Disable specific subagents

禁用特定子代理

You can prevent Claude from using specific subagents by adding them to the deny array in your settings. Use the format Task(subagent-name) where subagent-name matches the subagent's name field.

你可以通过在设置中将它们添加到 deny 数组来阻止 Claude 使用特定子代理。使用 Task(subagent-name) 格式,其中 subagent-name 与子代理的名称字段匹配。

```bash

{

"permissions": {

"deny": ["Task(Explore)", "Task(my-custom-agent)"]

}

}

```

This works for both built-in and custom subagents. You can also use the --disallowedTools CLI flag:

这适用于内置和自定义子代理。你也可以使用 --disallowedTools 命令行标志:

claude --disallowedTools "Task(Explore)"

3.6 Define hooks for subagents 为子代理定义钩子

Subagents can define hooks that run during the subagent's lifecycle. There are two ways to configure hooks:

子代理可以定义在子代理生命周期中运行的钩子。配置钩子有两种方式:

  1. In the subagent's frontmatter: Define hooks that run only while that subagent is active

在子代理的frontmatter文本中:定义仅在当前子代理激活时运行的钩子

  1. In settings.json: Define hooks that run in the main session when subagents start or stop

在 settings.json 中:定义在子代理启动或停止时在主会话中运行的钩子

3.6.1 Hooks in subagent frontmatter

子代理frontmatter中的钩子

Define hooks directly in the subagent's markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes.

直接在子代理的 markdown 文件中定义钩子。这些钩子只在特定子代理激活时运行,并在其结束时清理。

有以下3种,

1,PreToolUse

Matcher input Matcher字段输入:Tool name 工具名称

触发时机:Before the subagent uses a tool

子代理使用工具之前

2.PostToolUse

Matcher input Matcher字段输入:Tool name 工具名称

触发时机:After the subagent uses a tool

子代理使用工具后

3.Stop

Matcher input Matcher字段输入:(none)

触发时机:When the subagent finishes

子代理完成时

This example validates Bash commands with the PreToolUse hook and runs a linter after file edits with PostToolUse:

下面示例使用 PreToolUse 钩子验证 Bash 命令,并在文件编辑后使用 PostToolUse 运行代码检查工具

```bash


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"


```

使用自动检查检查代码更改

Stop hooks in frontmatter are automatically converted to SubagentStop events.

frontmatter 中的 Stop 钩子会自动转换为 SubagentStop 事件。

3.6.2 Project-level hooks for subagent events

子代理事件的项目级钩子

Configure hooks in settings.json that respond to subagent lifecycle events in the main session. Use the matcher field to target specific agent types by name.

在 settings.json 中配置钩子,以响应主会话中的子代理生命周期事件。使用 matcher 字段按名称指定特定的代理类型。

有2种

1,SubagentStart

Matcher input Matcher字段输入:Agent type name 代理类型名称

触发条件:When a subagent begins execution

当子代理开始执行

2,SubagentStop

Matcher input Matcher字段输入:Agent type name 代理类型名称

触发条件:When a subagent completes

当子代理完成

This example runs setup and cleanup scripts only when the db-agent subagent starts and stops:

下面示例仅在 db-agent 子代理启动和停止时运行设置和清理脚本:

```bash

{

"hooks": {

"SubagentStart": [

{

"matcher": "db-agent",

"hooks": [

{ "type": "command", "command": "./scripts/setup-db-connection.sh" }

]

}

],

"SubagentStop": [

{

"matcher": "db-agent",

"hooks": [

{ "type": "command", "command": "./scripts/cleanup-db-connection.sh" }

]

}

]

}

}

```

四,Work with subagents 与子代理一起工作

4.1 Understand automatic delegation 理解自动委派

Claude automatically delegates tasks based on the task description in your request, the description field in subagent configurations, and current context. To encourage proactive delegation, include phrases like "use proactively" in your subagent's description field.

Claude 根据你请求中的任务描述、子代理配置中的 description 字段以及当前上下文自动分配任务。为鼓励主动分配,请在子代理的描述字段中包含"主动使用"等短语。

You can also request a specific subagent explicitly:

你还可以明确请求特定的子代理:

Use the test-runner subagent to fix failing tests

Have the code-reviewer subagent look at my recent changes

4.2 Run subagents in foreground or background 在前台或后台运行子代理

Subagents can run in the foreground (blocking) or background (concurrent):

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

1,Foreground subagents block the main conversation until complete. Permission prompts and clarifying questions (like AskUserQuestion) are passed through to you.

前台子代理会阻塞主对话直到完成。权限提示和澄清问题(如 AskUserQuestion )会传递给你选择。

2,Background subagents run concurrently while you continue working. They inherit the parent's permissions and auto-deny anything not pre-approved.

If a background subagent needs a permission it doesn't have or needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents.

后台子代理在你继续工作时并发运行。它们继承父代理的权限,并自动拒绝未经预先批准的内容。

如果后台子代理需要它没有的权限或需要询问澄清问题,该工具调用会失败,但子代理会继续。后台子代理中不可用 MCP 工具。

所以尽量不要使用后台的。

If a background subagent fails due to missing permissions, you can resume it in the foreground to retry with interactive prompts.

如果后台子代理因权限缺失而失败,你可以在前台恢复它,使用交互式提示重试。

Claude decides whether to run subagents in the foreground or background based on the task. You can also:

Claude 根据任务决定是否在前台或后台运行子代理。你也可以:

Ask Claude to "run this in the background"

让 Claude 在后台运行

Press Ctrl+B to background a running task

按 Ctrl+B 将正在运行的任务置为后台

To disable all background task functionality, set the CLAUDE_CODE_DISABLE_BACKGROUND_TASKS environment variable to 1.

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

4.3 Common patterns 常见模式

4.3.1 Isolate high-volume operations

隔离高容量操作

One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context.

By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation.

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

通过将这些任务委托给子代理,冗长的输出会保留在子代理的上下文中,而只有相关的摘要会返回到你的主对话中。

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

使用子代理运行测试套件,并仅报告失败测试及其错误消息

4.3.2 Run parallel research 运行并行研究

For independent investigations, spawn multiple subagents to work simultaneously:

对于独立调查,生成多个子代理同时工作:

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

使用单独的子代理并行地研究身份验证、数据库和API模块

Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other.

每个子代理独立探索其领域,然后 Claude 综合研究结果。当研究路径不依赖于彼此时,这种方法效果最佳。

When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.

当子代理完成时,他们的结果会返回到你的主对话中。运行多个子代理,每个子代理都返回详细结果,可能会消耗大量上下文。

4.3.3 Chain subagents 链式子代理

For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.

对于多步骤工作流程,请要求 Claude 按顺序使用子代理。每个子代理完成任务后,将结果返回给 Claude,然后 Claude 将相关上下文传递给下一个子代理。

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

使用代码审查子代理来查找性能问题,然后使用优化子代理来修复它们

4.4 Choose between subagents and main conversation 在子代理和主对话之间选择

4.4.1 Use the main conversation when:

以下情况时使用主对话:

The task needs frequent back-and-forth or iterative refinement

任务需要频繁的来回沟通或迭代改进

Multiple phases share significant context (planning → implementation → testing)

多个阶段共享重要上下文(规划→实施→测试)

You're making a quick, targeted change

你正在做一个快速、有针对性的更改

Latency matters. Subagents start fresh and may need time to gather context

延迟很重要。子代理会重新开始,并且可能需要时间来收集上下文

4.4.2 Use subagents when: 当出现以下情况时使用子代理:

The task produces verbose output you don't need in your main context

任务产生大量输出,而你不需要在主上下文中使用这些输出

You want to enforce specific tool restrictions or permissions

你想强制执行特定的工具限制或权限

The work is self-contained and can return a summary

这项工作可以自包含并返回摘要

Consider Skills instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.

当你想要可重用的提示词或工作流程,并且这些工作流程在主对话上下文中运行而不是在隔离的子代理上下文中运行时,请考虑使用skills

Subagents cannot spawn other subagents. If your workflow requires nested delegation, use Skills or chain subagents from the main conversation.

子代理不能生成其他子代理。如果你的工作流程需要嵌套委托,请使用Skills或从主对话中链接子代理

4.5 Manage subagent context 管理子代理上下文

4.5.1 Resume subagents 恢复子代理

Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it.

每次调用子代理都会创建一个具有全新上下文的新实例。若要继续现有子代理的工作而不是重新开始,可以请 Claude 恢复它。

Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh.

恢复的子代理会保留其完整的对话历史,包括所有之前的工具调用、结果和推理。子代理会从它停止的地方继续,而不是重新开始。

When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:

当一个子代理完成时,Claude 会收到它的代理 ID。要继续一个子代理的工作,请让 Claude 继续之前的工作,如:

Use the code-reviewer subagent to review the authentication module #使用代码审查子代理来检查身份验证模块

Agent completes

Continue that code review and now analyze the authorization logic #继续代码审查,现在分析授权逻辑

Claude resumes the subagent with full context from previous conversation\] #Claude 使用之前的完整对话上下文恢复子代理 You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at \~/.claude/projects/{project}/{sessionId}/subagents/. Each transcript is stored as agent-{agentId}.jsonl. 如果你需要明确引用代理 ID,也可以向 Claude 询问代理 ID,或者在 \~/.claude/projects/{project}/{sessionId}/subagents/ 的转录文件中查找 ID。每个转录文件都存储为 agent-{agentId}.jsonl 。 Subagent transcripts persist independently of the main conversation: 子代理的转录独立于主对话持续存在: 1,Main conversation compaction: When the main conversation compacts, subagent transcripts are unaffected. They're stored in separate files. 主对话压缩:当主对话压缩时,子代理的文本记录不受影响。它们存储在不同的文件中。 Session persistence: Subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session. 会话持久化:子代理的文本记录在其会话中持续存在。你可以通过恢复同一个会话来在重新启动 Claude Code 后恢复子代理。 Automatic cleanup: Transcripts are cleaned up based on the cleanupPeriodDays setting (default: 30 days). 自动清理:文本记录根据 cleanupPeriodDays 设置进行清理(默认:30 天)。 4.5.2 Auto-compaction 自动压缩 Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE to a lower percentage (for example, 50). 子代理支持 当使用与主对话相同逻辑时的自动压缩。默认情况下,自动压缩在约 95%容量时触发。若要更早触发压缩,将 CLAUDE_AUTOCOMPACT_PCT_OVERRIDE 设置为较低百分比(例如 50 )。 Compaction events are logged in subagent transcript files: 压缩事件记录在子代理转录文件中: \`\`\`bash { "type": "system", "subtype": "compact_boundary", "compactMetadata": { "trigger": "auto", "preTokens": 167189 } } \`\`\` The preTokens value shows how many tokens were used before compaction occurred. preTokens 值显示了压缩发生前使用的 token 数量。 五,Best practices: 最佳实践: Design focused subagents: each subagent should excel at one specific task 设计专注的子代理:每个子代理应擅长一项特定任务 Write detailed descriptions: Claude uses the description to decide when to delegate 撰写详细描述:Claude 使用描述来决定何时进行任务委托 Limit tool access: grant only necessary permissions for security and focus 限制工具访问:仅授予必要权限以确保安全和专注 Check into version control: share project subagents with your team 检查版本控制:与团队共享项目子代理 六,Example subagents 示例子代理 These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude. 以下这些示例展示了构建子代理的有效模式。将它们作为起点使用,或使用 Claude 生成一个定制版本。 6.1 Code reviewer 代码审查者 A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output. 一个只读的子代理,用于审查代码而不修改它。这个例子展示了如何设计一个具有有限工具访问权限(没有编辑或写入)的专注子代理,以及一个详细的提示,明确说明要查找的内容和输出格式。 \`\`\`bash --- 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 #运行git diff查看最近的更改 2. Focus on modified files #关注已修改的文件 3. Begin review immediately #立即开始review 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 # 没有暴露密码或API密钥 - 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. 包括如何解决问题的具体示例。 \`\`\` 6.2 Debugger 调试器 A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification. 一个可以分析和修复问题的子代理。与代码审查者不同,这个子代理包括编辑功能,因为修复错误需要修改代码。提示词提供了一个从诊断到验证的清晰工作流程。 \`\`\`bash --- 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: 对于每个issue,提供 - Root cause explanation #根本原因解释 - Evidence supporting the diagnosis #支持诊断的证据 - Specific code fix #具体代码修复 - Testing approach #测试方法 - Prevention recommendations #预防建议 Focus on fixing the underlying issue, not the symptoms. #专注于解决根本问题,而不是症状。 \`\`\` 6.3 Data scientist 数据科学家 A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets model: sonnet for more capable analysis. 一个用于数据分析工作的特定领域子代理。这个例子展示了如何在典型的编码任务之外创建用于专业工作流的子代理。它明确地将 model: sonnet 设置为更强大的分析能力。 \`\`\`bash --- name: data-scientist description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries. #数据分析专家,擅长SQL查询、BigQuery操作和数据洞察。主动用于数据分析任务和查询。 tools: Bash, Read, Write model: sonnet --- You are a data scientist specializing in SQL and BigQuery analysis. #你是一个专门从事SQL和BigQuery分析的数据科学家。 When invoked: 当被调用时: 1. Understand the data analysis requirement #理解数据分析需求 2. Write efficient SQL queries #编写高效的SQL查询 3. Use BigQuery command line tools (bq) when appropriate #在适当的时候使用BigQuery命令行工具(bq) 4. Analyze and summarize results #分析并总结结果 5. Present findings clearly #清晰地展示发现 Key practices: #关键实践 - Write optimized SQL queries with proper filters #使用适当的过滤条件编写优化的SQL查询 - 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. #始终确保查询是高效和经济的。 \`\`\` 6.4 Database query validator 数据库查询验证器 A subagent that allows Bash access but validates commands to permit only read-only SQL queries. This example shows how to use PreToolUse hooks for conditional validation when you need finer control than the tools field provides. 一个允许 Bash 访问但是验证只读 SQL 查询命令的子代理。此示例展示了如何使用 PreToolUse 钩子进行条件验证,当你需要比 tools 字段提供的更精细控制时。 \`\`\`bash --- 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. #你是具有只读访问权限的数据库分析人员。执行SELECT查询来回答有关数据的问题。 When asked to analyze data: #当被要求分析数据时: 1. Identify which tables contain the relevant data #确定包含相关数据的表 2. Write efficient SELECT queries with appropriate filters #编写高效的SELECT查询并使用适当的过滤器 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. #不能修改数据。如果被要求进行INSERT、UPDATE、DELETE或修改模式,说明您只有读访问权限。 \`\`\` Claude Code passes hook input as JSON via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script exits with code 2 to block execution and returns an error message to Claude via stderr. Claude Code 通过标准输入将钩子的输入作为 JSON 传递给钩子命令。验证脚本读取此 JSON,提取将要执行的命令,并检查它是否为 SQL 写操作列表中的操作。如果检测到写操作,脚本以代码 2 退出以阻止执行,并通过标准错误返回错误消息给 Claude。 Create the validation script anywhere in your project. The path must match the command field in your hook configuration: 在你的项目中创建验证脚本。路径必须与你的钩子配置中的 command 字段匹配: \`\`\`bash #!/bin/bash # Blocks SQL write operations, allows SELECT queries #阻塞SQL写操作,允许SELECT查询 # Read JSON input from stdin #从标准输入读取JSON输入 INPUT=$(cat) # Extract the command field from tool_input using jq #使用jq从tool_input中提取命令字段 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 #被阻止:不允许写入操作。仅允许使用SELECT查询。 exit 2 fi exit 0 \`\`\` Make the script executable: 使脚本可执行: chmod +x ./scripts/validate-readonly-query.sh The hook receives JSON via stdin with the Bash command in tool_input.command. Exit code 2 blocks the operation and feeds the error message back to Claude. 钩子通过标准输入接收 JSON,其中包含在 tool_input.command 中的 Bash 命令。退出码 2 会阻止操作并将错误消息反馈给 Claude。 小结: 每个子代理在自己的上下文窗口中运行,子代理独立工作并返回结果。 简单子代理可以使用便宜模型 Claude 使用每个子代理的描述来决定何时委派任务。 使用 /agents 命令创建( \~/.claude/agents/),选择工具和模型,显示颜色,可以通过插件分发子代理。 提到2个skills:api-conventions 和 error-handling-patterns 可以加载skills的全部内容,而不仅仅是可供调用。所以应该会占用很多上下文。 可使用单独的子代理并行地研究身份验证、数据库和API模块 可链式调用子代理,由主claude调用 提供了几个子代理示例,如code-reviewer,Debugger, 自定义的子代理,一般都有角色, When invoked当被调用时做什么,然后有步骤。

相关推荐
hua_ban_yu2 小时前
vue3 + ts 制作指令,防止按钮在固定时间内重复点击,不会影响到表单的校验
前端·javascript·vue.js
Anastasiozzzz2 小时前
Redis的键过期是如何删除的?【面试高频】
java·数据库·redis·缓存·面试
老神在在0012 小时前
Token身份验证完整流程
java·前端·后端·学习·java-ee
北海屿鹿2 小时前
【MySQL】内置函数
android·数据库·mysql
利刃大大3 小时前
【Vue】指令修饰符 && 样式绑定 && 计算属性computed && 侦听器watch
前端·javascript·vue.js·前端框架
踢球的打工仔4 小时前
typescript-接口的基本使用(一)
android·javascript·typescript
qq_366086224 小时前
SQL Server 之 Full-Text Search 全文搜索
运维·服务器·数据库
徐小夕@趣谈前端4 小时前
NO-CRM 2.0正式上线,Vue3+Echarts+NestJS实现的全栈CRM系统,用AI重新定义和实现客户管理系统
前端·javascript·人工智能·开源·编辑器·echarts
catino4 小时前
图片、文件上传
前端