💬 hippo:這是 Claude Code 官方文件精讀系列的其中一篇。


一、這個功能是什麼

Subagents(子代理) 是在自己的 context window(上下文視窗)中獨立執行的專門 AI 助手。你可以把它理解為一個「專家團隊」——主對話是專案經理,subagent 是各領域的專家,接到任務後在自己的獨立空間裡執行,完成後再將結果摘要回報回來。

關鍵特徵:每個 subagent 擁有自己的系統提示詞、特定的工具存取權限與獨立的權限控制。Claude 會根據你定義的 description 欄位,自動判斷何時應該將任務委派給哪個 subagent。

為什麼需要 subagent,而不是在主對話裡處理所有事情?

  • 保留上下文:探索程式碼庫、執行測試這類操作會產生大量中間輸出,放在獨立的 context window 裡執行可避免汙染主對話
  • 強制約束:透過 tools 與 disallowedTools 限制它能使用的工具,例如程式碼審查者只給予唯讀權限
  • 跨專案重用:放在 ~/.claude/agents/ 下的使用者層級 subagent 在所有專案皆生效
  • 專門化行為:為特定領域客製化系統提示詞,例如資料科學家、資料庫分析師
  • 控制成本:透過 model 欄位將任務路由到成本更低的模型(如 Haiku)

內建 subagent 一覽:

代理 模型 工具限制 用途
Explore Haiku 唯讀(拒絕 Write/Edit) 快速唯讀探索程式碼庫,徹底度有 quick/medium/very thorough 三個等級
Plan 繼承父對話 唯讀(拒絕 Write/Edit) Plan 模式下自動呼叫,收集規劃所需的上下文
General-purpose 繼承父對話 全部 處理複雜的多步驟任務
statusline-setup Sonnet 執行 /statusline 時 設定狀態列
Claude Code Guide Haiku 詢問 Claude Code 功能時 回答關於 Claude Code 功能的問題

二、官方教學精讀

2.1 快速入門:/agents 指令

官方新增了互動式管理指令 /agents,可以用來:

  • 檢視所有可用的 subagent(內建、使用者、專案、外掛)
  • 透過引導流程建立新的 subagent,或讓 Claude 自動產生
  • 編輯現有 subagent 的設定與工具存取權限
  • 刪除自訂 subagent
  • 檢視同名 subagent 的優先權覆蓋情況

也可以使用非互動指令 claude agents 在命令列列出所有 subagent,依來源分組並標註優先權覆蓋情況。這是官方推薦的 subagent 建立與管理方式。

2.2 設定檔格式與工具控制

檔案格式

每個 subagent 是一個帶有 YAML frontmatter 的 Markdown 檔案,frontmatter 定義組態設定,正文撰寫系統提示詞:

1
2
3
4
5
6
7
8
9
10
11
---
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
memory: project
---

You are a senior code reviewer ensuring high standards.
As you review code, update your agent memory with patterns,
conventions, and recurring issues you discover.

只有 name 與 description 是必填的,其餘皆為選填。檔案存放的位置決定了作用範圍與優先權:

位置 作用範圍 優先權 說明
Managed settings 組織層級 1(最高) 由組織管理員透過 managed settings 部署
CLI --agents 旗標 目前工作階段 2 JSON 格式,啟動時傳入
專案 .claude/agents/ 目前專案 3 建議納入版本控制,團隊共用
使用者 ~/.claude/agents/ 所有專案 4 個人設定,跨專案生效
Plugin 的 agents/ 目錄 啟用 plugin 的專案 5(最低) 隨 plugin 安裝

工具控制三種方式

subagent 的工具存取有三種控制手段,可以組合使用:

1. tools(允許清單)——只給予需要的工具:

1
2
3
4
5
---
name: safe-researcher
description: 唯讀研究代理
tools: Read, Grep, Glob, Bash
---

此設定只有 Read、Grep、Glob 與 Bash,無法編輯或寫入檔案。

2. disallowedTools(拒絕清單)——繼承所有工具,但排除少數幾個:

1
2
3
4
5
---
name: no-writes
description: 繼承所有工具,除了檔案寫入
disallowedTools: Write, Edit
---

3. PreToolUse hooks(條件規則)——最精細的控制,依據條件動態決定:

1
2
3
4
5
6
7
8
9
10
11
12
13
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---

You are a database analyst with read-only access.

這裡雖然開放了 Bash 工具,但透過 hook 腳本驗證每條指令只允許執行 SELECT 查詢,粒度比單純限制工具更細緻。

當 tools 與 disallowedTools 同時設定時,解析順序是先套用 disallowedTools 移除被拒工具,再從剩餘工具池中解析 tools。

進階設定欄位

欄位 必填 說明
name 是 唯一識別碼,僅限小寫字母與連字號
description 是 告知 Claude 何時應該委派的自然語言描述,建議使用 “Use proactively” 明確觸發時機
tools 否 允許清單;支援 Agent(agent_type) 語法限制可生成的子代理類型
disallowedTools 否 拒絕清單;與 tools 同時設定時先套用 disallowedTools 再解析 tools
model 否 模型選擇:sonnet/opus/haiku/完整模型 ID/inherit,預設為 inherit
memory 否 持久記憶作用範圍:user/project/local,啟用後自動載入 MEMORY.md 前 200 行
skills 否 啟動時注入完整技能內容(subagent 不繼承父對話技能,必須明確列出)
mcpServers 否 MCP 伺服器清單,支援內嵌定義(限定於此 subagent)與字串參照(共用父連線)
permissionMode 否 權限模式:default/acceptEdits/auto/dontAsk/bypassPermissions/plan
maxTurns 否 subagent 停止前的最大代理輪數
effort 否 推理深度層級:low/medium/high/max(僅 Opus 4.6 支援 max)
isolation 否 設為 worktree 時在暫存 git worktree 中執行,若無修改則自動清理
background 否 設為 true 時始終在背景執行
initialPrompt 否 作為主工作階段代理(--agent)執行時自動送出的首個使用者輪次
color 否 在任務清單與對話紀錄中的顯示顏色:red/blue/green/yellow/purple/orange/pink/cyan
hooks 否 限定於此 subagent 的生命週期 hooks(PreToolUse/PostToolUse/Stop)

model 解析的 4 層優先權鏈:CLAUDE_CODE_SUBAGENT_MODEL 環境變數 > 每次呼叫的 model 參數 > frontmatter 的 model 欄位 > 主對話的模型。

permissionMode 的優先權規則:如果父層設定了 bypassPermissions,子代理無法覆蓋;如果父層使用 auto 模式,subagent 會繼承 auto 模式且其 permissionMode 欄位會被忽略——分類器會以與父工作階段相同的 block/allow 規則評估 subagent 的工具呼叫。

memory 三層作用範圍:

層級 儲存位置 特點
user ~/.claude/agent-memory/<name>/ 全域,所有專案共用
project .claude/agent-memory/<name>/ 可納入版本控制,團隊共用
local .claude/agent-memory-local/<name>/ 不提交至 git,個人本機使用

啟用 memory 後,subagent 會自動取得 Read/Write/Edit 工具,並自動載入 MEMORY.md 前 200 行或 25KB(以先到達者為準)作為上下文,同時附帶指令要求在超出限制時整理 MEMORY.md。這讓 subagent 能夠跨多次工作階段累積知識。官方推薦預設使用 project 作用範圍,方便透過版本控制與團隊分享。

mcpServers 兩種形式:

1
2
3
4
5
6
7
8
9
10
# 內聯定義:限定此 subagent,啟動時連線,完成時中斷
mcpServers:
- playwright:
type: stdio
command: npx
args: ["-y", "@playwright/mcp@latest"]

# 字串參照:共享父工作階段已有的 MCP 連線
mcpServers:
- github

內嵌定義適合僅需特定 subagent 使用的 MCP 服務,避免消耗主對話的上下文;字串參照則是共用父工作階段已經建立的連線。

2.3 呼叫方式、執行模式與常見模式

三種呼叫方式

1. 自然語言(由 Claude 決定是否委派):在提示中提及 subagent,Claude 會依據 description 欄位判斷是否需要委派。

1
Use the test-runner subagent to fix failing tests

2. @-mention(保證執行):輸入 @ 後從自動完成清單中選擇 subagent,確保指定的 subagent 被執行。

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

也可以手動輸入:@agent-<name> 參照本機 subagent,@agent-<plugin-name>:<agent-name> 參照外掛 subagent。外掛的 subagent 在自動完成中會顯示為 <plugin-name>:<agent-name>。

3. --agent 旗標(工作階段範圍替換):subagent 的系統提示詞將完全替換預設的 Claude Code 系統提示詞,整個工作階段都在該 subagent 的上下文中執行。

1
claude --agent code-reviewer

也可以在 .claude/settings.json 中設為預設值:

1
2
3
{
"agent": "code-reviewer"
}

前景 vs 背景

特性 前景 subagent 背景 subagent
執行方式 阻塞主對話直到完成 並行執行,不阻塞主對話
權限互動 權限提示與釐清問題會傳遞給你 繼承預先核准的權限,自動拒絕未預先核准的操作
釐清問題 可以與你互動 工具呼叫失敗,但 subagent 會繼續執行
觸發方式 預設行為,或要求 “run in foreground” 要求 “run in background”,或於 frontmatter 設定 background: true
切換 執行中按 Ctrl+B 移至背景 —

停用背景任務:

1
export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

常見模式

1. 隔離高輸出量操作:讓測試執行器在獨立上下文中執行測試,僅將摘要回傳給主對話,避免大量測試輸出汙染主上下文。

2. 並行研究:同時啟動多個 subagent 探索程式碼庫的不同模組,各自獨立作業,最後再彙整結果。

3. 串聯 subagents:由一個 coordinator subagent 依序呼叫多個專用 subagent,完成多步驟工作流程:

1
2
3
4
5
---
name: coordinator
description: Coordinates work across specialized agents
tools: Agent(worker, researcher), Read, Bash
---

這裡的 Agent(worker, researcher) 語法限制了 coordinator 只能生成 worker 與 researcher 兩種子代理。使用不帶括號的 Agent 則允許生成任何類型的子代理。如果 tools 中完全省略 Agent,該代理便無法生成任何子代理。注意:此限制僅適用於透過 claude --agent 作為主執行緒執行的代理;subagent 本身無法再生成子代理,因此 Agent(agent_type) 在 subagent 定義中無效。

Hooks 設定

subagent 的 hooks 分為兩個層級:

Frontmatter 內(僅限此 subagent):

事件 觸發時機
PreToolUse subagent 使用工具之前
PostToolUse subagent 使用工具之後
Stop subagent 完成時(自動轉換為 SubagentStop)

settings.json 專案層級(全域):

事件 Matcher 觸發時機
SubagentStart Agent type name 任意 subagent 開始執行時
SubagentStop Agent type name 任意 subagent 完成時
1
2
3
4
5
6
7
8
9
10
11
12
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./scripts/setup-db-connection.sh" }
]
}
]
}
}

若要停用特定 subagent,可在 settings.json 中搭配 permissions.deny 與 Agent(name),或透過 CLI 旗標設定:

1
2
3
4
5
{
"permissions": {
"deny": ["Agent(Explore)", "Agent(my-custom-agent)"]
}
}
1
claude --disallowedTools "Agent(Explore)"

與 Skills 和 /btw 的差異

機制 執行位置 工具存取 適用情境
Subagent 獨立 context window 可限定 大量輸出、工具限制、成本控制
Skills 主對話上下文中 繼承主對話 可重用提示,在主上下文執行
/btw 檢視既有上下文 無工具存取 快速回顧既有內容,不執行新操作

subagent 不繼承父對話的 skills,必須在 frontmatter 中明確列出。

可恢復 subagent

每次執行都會建立全新執行個體與全新上下文。若要接續既有的 subagent 工作而非重新開始,可以請 Claude 恢復它。恢復後的 subagent 會保留完整對話歷史,從上次停止的位置繼續執行。

subagent 完成後,Claude 會取得 agent ID。透過 SendMessage 工具(需啟用 CLAUDE_CODE_SUBAGENT_MODEL 環境變數與 agent teams),將 agent ID 填入 to 欄位即可恢復。已停止的 subagent 收到 SendMessage 時會在背景自動恢復,不需要重新呼叫 Agent。

對話紀錄(transcript)獨立於主對話持久化儲存:主對話壓縮不會影響 subagent;工作階段重啟後可透過恢復同一個工作階段繼續;自動清理週期由 cleanupPeriodDays 設定控制(預設 30 天)。對話紀錄檔案路徑為 ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl。

自動壓縮預設在容量約達 95% 時觸發。可透過 CLAUDE_AUTOCOMPACT_PCT_OVERRIDE 環境變數設定較低的百分比(例如 50)以提前觸發。壓縮事件會記錄在對話紀錄檔案中,preTokens 欄位顯示壓縮前的 token 用量。

2.4 官方範例精講

程式碼審查者:唯讀 + 結構化輸出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
---
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
memory: project
---

You are a senior code reviewer ensuring high standards.
As you review code, update your agent memory with patterns,
conventions, and recurring issues you discover.

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

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

這個範例展示了幾個重點:tools 只提供了唯讀工具(Read/Grep/Glob/Bash),不包含 Edit/Write,因此它只能檢視而不能修改;memory: project 讓它在審查過程中逐步累積程式碼庫的模式與慣例;輸出依 Critical/Warnings/Suggestions 三個層級分類,結構清晰明確。

除錯器:可修改 + 完整工作流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
---
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

Focus on fixing the underlying issue, not the symptoms.

相較於 code-reviewer,debugger 多了 Edit 工具——因為它需要修改程式碼來修復 bug。工作流程也相當完整:診斷→定位→修復→驗證。

資料科學家:領域專用 + model 路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
---
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

這裡透過 model: sonnet 將任務路由至 Sonnet 模型,適合資料分析這類不需要最強推理能力的情境,藉此有效控制成本。官方更新後的描述更為具體:聚焦於 SQL 與 BigQuery 情境,強調查詢效率與成本控制。

資料庫查詢驗證器:以 Hook 實現條件控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
name: db-reader
description: Execute read-only database queries
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.

驗證腳本 validate-readonly-query.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

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

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

exit 0

這個範例比單純限制 tools 更為強大:雖然開放了 Bash 工具,但透過 PreToolUse hook 在每次呼叫前驗證指令內容,只放行 SELECT 查詢。這種條件式控制是 tools/disallowedTools 做不到的——它們只能控制「能不能用 Bash」,而 hook 能控制「Bash 裡能執行什麼」。


三、hippo 的實戰經驗

💬 hippo:以下是我實際使用中的踩坑經驗:

單一職責是第一原則

剛開始使用 subagent 時,我寫了幾個「全能型」設定——既做程式碼審查、又跑測試、還寫文件。結果 Claude 經常搞不清楚什麼時候該用哪一個,呼叫時機混亂,輸出品質也不穩定。

後來改依單一職責拆分:test-runner(只負責跑測試)、changelog-writer(只負責更新變更日誌)、code-reviewer(只負責程式碼審查)。關鍵在於在 description 裡用 “Use proactively after code changes” 這樣的措辭明確標示觸發時機,讓 Claude 的判斷更加準確。

memory 跨工作階段累積知識

為 code-reviewer 加上 memory: project 後,它會在每次審查時將程式碼庫的模式、團隊慣例與常見問題寫入 MEMORY.md。幾輪迭代下來,審查品質明顯提升——因為它已經「記住」了專案特有的風格與反模式。

這項特性特別適合需要反覆執行、且具備領域知識累積價值的 subagent。如果是一次性任務,例如 changelog-writer,就不需要啟用 memory。

選擇策略:主對話 vs subagent vs Skill

情境 選擇 原因
快速修個 bug 主對話 需要頻繁來回互動,共用上下文
執行完整測試套件 subagent 輸出量龐大,只關心最終摘要
可重用的審查清單 Skill 在主上下文執行,共用工具與上下文
快速回顧先前討論 /btw 無需工具,僅檢視既有內容

系列導覽


本文精讀自 Subagents - Claude Code Docs

最後更新:2026-04-09