Claude Code新增sub-agents功能,开发者可创建针对特定任务的智能助手。直接提升自动化编程能力和工作流自定义度。
将探索和实现工作移出主对话,避免混乱信息污染你的工作空间。
通过控制子代理可以使用哪些工具,你可以强制执行安全策略和工作流限制。
创建一次,在任何地方使用。同步到版本控制以便与团队共享。
针对特定任务(代码审查、调试、数据分析)优化代理的能力。
使用 Haiku 执行低价值工作,为复杂任务保留 Opus。
Model: 从主对话继承,在 Claude API 上限制为 Opus,所以 Explore 永远不会以比你为会话选择的更昂贵的模型运行
Tools: 只读工具;Write 和 Edit 被禁用
Purpose: 文件发现、代码搜索、代码库探索
Model: 从主对话继承
Tools: 只读工具;Write 和 Edit 被禁用
Purpose: 用于规划的代码库研究
Model: 从主对话继承
Tools: 子代理可用的每个工具
Purpose: 复杂研究、多步骤操作、代码修改
要阻止特定的内置类型,请将其添加到 permissions.deny,如"禁用特定子代理"中所示。
要防止 Claude 委派给任何子代理,请用 permissions.deny 拒绝 Agent 工具本身。
要仅删除内置的 Explore 和 Plan 子代理,请设置 CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1。Claude 将直接读取和探索文件而不是委派给它们。需要 Claude Code v2.1.198 或更高版本。
在非交互模式和 Agent SDK 中,设置 CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1 以删除所有内置类型,仅提供你自己的。
Create a personal code-improver subagent in ~/.claude/agents/ 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. Make it read-only and have it use Sonnet.
Claude 会创建文件:
---
name: code-improver
description: Scans files and suggests improvements for readability, performance, and best practices. Use after writing or modifying code.
tools: Read, Grep, Glob
model: sonnet
---
You are a code improvement specialist. For each issue you find, explain
the problem, show the current code, and provide an improved version.
然后调用它:
Use the code-improver agent to suggest improvements in this project
使用 CLI 的 --agents 标志:
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."
}
}'
或从文件加载:
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."
}
}
'@
在 ~/.claude/agents/ 中创建 markdown 文件。监听器仅覆盖会话启动时存在的目录,因此在新的 agents 目录中创建范围的第一个代理文件后,需要重启以加载它。
使用 --disable-slash-commands 启动的会话根本不会监听这些目录。
---
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.
模型通过以下优先级决定(从高到低):
--model 标志相同的值模型也可以通过以下方式指定(按优先级):
CLAUDE_CODE_SUBAGENT_MODEL 环境变量(如果设置为模型别名或模型 ID)在 frontmatter 中声明允许的工具:
---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---
使用 disallowedTools 从继承的工具集中移除工具:
---
name: no-writes
description: Inherits the available tools except file writes
disallowedTools: Write, Edit
---
按前缀拒绝整个 MCP 服务器:
---
name: local-only
description: Inherits every tool except those from the github MCP server
disallowedTools: mcp__github
---
限制哪些代理可以生成其他代理:
---
name: coordinator
description: Coordinates work across specialized agents
tools: Agent(worker, researcher), Read, Bash
---
完整的 tools 声明:
tools: Agent, Read, Bash
代理可以作为子代理通过 Agent 工具或 @-提及生成,也可以作为通过 --agent 或 agent 设置启动的主会话生成。
---
name: browser-tester
description: Tests features in a real browser using Playwright
mcpServers:
# Inline definition: scoped to this subagent only
- playwright:
type: stdio
command: npx
args: ["-y", "@playwright/mcp@latest"]
# Reference by name: reuses an already-configured server
- github
---
Use the Playwright tools to navigate, screenshot, and interact with pages.
---
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.
---
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.
当子代理定义了 memory: user 时:
范围建议:project 是推荐的默认范围。它使子代理知识通过版本控制可共享。
使用子代理内存:
Update your agent memory as you discover codepaths, patterns, library
locations, and key architectural decisions. This builds up institutional
knowledge across conversations. Write concise notes about what you found
and where.
在子代理的 frontmatter 中:定义仅在该子代理处于活跃状态时运行的钩子
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
示例验证脚本:
#!/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
使脚本可执行:
chmod +x ./scripts/validate-readonly-query.sh
在 settings.json 中:定义会话范围的钩子,也会在子代理内触发。工具事件,如 PreToolUse 和 PostToolUse,为子代理的工具调用触发,方式与在主对话中相同,SubagentStart 和 SubagentStop 在子代理启动或完成时触发。
自然语言:在你的提示中命名子代理;Claude 决定是否委派
Use the test-runner subagent to fix failing tests
Have the code-reviewer subagent look at my recent changes
@-提及:保证子代理为一个任务运行
@"code-reviewer (agent)" look at the auth changes
会话范围:整个会话使用该子代理的系统提示、工具限制和模型,通过 --agent 标志或 agent 设置
启动专用子代理会话:
claude --agent code-reviewer
或启动命名子代理:
claude --agent security-reviewer
或从插件加载:
claude --agent my-plugin:security-reviewer
在 settings.json 中设置默认代理:
{
"agent": "code-reviewer"
}
前台子代理阻止主对话直到完成。权限提示在出现时传递给你。
后台子代理在你继续工作时并发运行。从 v2.1.186 开始,当后台子代理到达需要权限的工具调用时,提示会在你的主会话中显示,并命名正在提问的子代理。批准以让子代理继续,或按 Esc 拒绝该单个工具调用而不停止子代理。在 v2.1.186 之前,后台子代理自动拒绝任何会提示的工具调用。
要求 Claude 在后台或前台运行任务
Run the test suite in the background
使用快捷键:按 Ctrl+B 将运行的任务移到后台
如果速率限制、过载或服务器错误中断了已生成文本输出的子代理,Agent 工具返回该部分输出,并注明子代理被中断且未完成其任务。未生成任何内容或其唯一输出仅为工具调用的子代理以"Agent terminated early due to an API error"失败,随后是错误详情。在 v2.1.199 中,中断仅为工具调用形状的速率限制、过载或服务器错误返回了仅包含中断说明的空部分结果。
子代理被标记为失败,Claude 在其结束时收到的消息命名 API 错误并包括子代理的最后输出,所以部分工作不会丢失。
Claude Code 会扫描子代理的输出,查找试图模仿系统响应的文本。
反斜杠插入:扫描将反斜杠插入模仿 Claude Code 自己输出的文本中,如 <system-reminder> 标签或以"Human:"或"Assistant:"开头的行,使模仿读起来像普通文本,而不是被误认为是对话的一部分。
标记行:扫描以[harness: subagent output matched instruction-shaped pattern(s):开头的行。当报告模仿 <system-reminder> 这样的标签或提及 bypassPermissions 或 --dangerously-skip-permissions 这样的权限设置时。权限设置提及获得标记行,但文本本身保持原样编写。
Research the authentication, database, and API modules in parallel using separate subagents
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
Use a subagent to run the test suite and report only the failing tests with their error messages
在 settings.json 中配置最大嵌套深度:
{
"env": {
"CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "2"
}
}
版本历史:
每个会话最多 50 个子代理。包括仅读取文件并报告的 Explore 运行,以及处理完整代码库的 general-purpose 代理。
最多 16 个子代理可以同时运行(受你的 CPU 核心数限制)。
一个你用 /subtask 启动的会话内 fork 在运行时占用一个插槽,永远不会被限制阻止。
恢复已完成的子代理会占用一个新插槽而不检查限制,所以恢复可以将运行计数推过限制。
系统提示:代理自己的提示加 Claude Code 附加的环境详情,而不是完整的 Claude Code 系统提示。自定义子代理在 markdown 正文或 prompt 字段中定义它们。内置代理有预定义的提示。
任务消息:Claude 在交接工作时编写的委派提示。
CLAUDE.md 文件:主对话加载的 CLAUDE.md 层级的每个级别,包括 ~/.claude/CLAUDE.md、项目规则、CLAUDE.local.md 和托管策略文件。内置的 Explore 和 Plan 代理跳过这个。
Git 状态:在父会话启动时获取的快照。当工作目录不是 Git 存储库或当 includeGitInstructions 为 false 时不存在。Explore 和 Plan 无论如何都跳过它。
预加载 skills:代理的 skills 字段中命名的任何 skill 的完整内容。内置代理不预加载 skills。
兄弟名册:一个系统提醒,列出主要和会话中的每个其他命名代理,每个都是 SendMessage 的有效 to 值。需要 Claude Code v2.1.206 或更高版本。仅当子代理的工具包括 SendMessage 且至少有一个其他代理有名称(无论 Claude 在生成它时是否命名它还是它作为代理团队队友运行)时出现。它是子代理启动时获取的快照,所以稍后命名的代理不会出现。
输出风格:子代理运行自己的系统提示,所以你的输出风格不会塑造其响应,除非在 fork 中。
自动内存:主对话的自动内存未加载。要给子代理其自己的持久内存,请使用 memory 字段。
上下文窗口大小:子代理的上下文窗口由其自己的模型大小,而不是父级的。委派到具有较小窗口的模型给该子代理较小的窗口。
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 Code 后恢复子代理。
Claude Code 在清理期后删除子代理记录,默认 30 天。
{
"type": "system",
"subtype": "compact_boundary",
"compactMetadata": {
"trigger": "auto",
"preTokens": 167189
}
}
Claude 可以通过显式请求 fork 子代理类型来生成 fork。当 Claude 不请求一个类型时,它仍然获得 general-purpose 子代理,命名的子代理,如 Explore 仍然像往常一样生成。
每个子代理都在后台运行,无论它是 fork 还是命名子代理。设置 CLAUDE_CODE_DISABLE_BACKGROUND_TASKS 为 1 以保持子代理同步。
/subtask draft unit tests for the parser changes so far
通过 /workflows 或 /observe 查看实时进度。在 fork 完成时获得通知。
每个子代理应该在一个特定的任务中表现出色:
---
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
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.
Claude 使用描述来决定何时委派。使描述详细和特定:
"Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code."
仅授予必要的权限以保证安全和专注:
---
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.
与验证脚本配对:
#!/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
使脚本可执行:
chmod +x ./scripts/validate-readonly-query.sh
在代码库中共享项目子代理,使你的团队能够使用相同的优化配置:
{
"permissions": {
"deny": ["Agent(Explore)", "Agent(my-custom-agent)"]
}
}
从命令行禁用代理:
claude --disallowedTools "Agent(Explore)"
在子代理的 frontmatter 中:定义仅在该子代理处于活跃状态时运行的钩子
---
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"
---
在 settings.json 中定义会话范围的钩子,也会在子代理内触发:
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./scripts/setup-db-connection.sh" }
]
}
],
"SubagentStop": [
{
"hooks": [
{ "type": "command", "command": "./scripts/cleanup-db-connection.sh" }
]
}
]
}
}
通过插件分发子代理以在团队或项目间共享子代理。
通过 Agent SDK 以编程方式运行 Claude Code,用于 CI/CD 和自动化。
使用 MCP 服务器为子代理提供对外部工具和数据的访问。