跳轉到主要內容
這個單元解決什麼問題Subagent 是擁有獨立 context window 的子任務執行容器,可指定模型、收斂工具權限、必要時用 git worktree 物理隔離,最終只把結論回傳給主流程。Claude Code v2.1 起採「兩層」結構:內建子代理(Explore、Plan、general-purpose 自動叫用)加自訂子代理(你寫 Markdown frontmatter 定義)。本單元講如何從零寫一個可用的 Subagent、如何選模型與最小權限、何時用 isolation: worktree 隔離平行衝突,以及釐清它與 Skill 的分工。

學習目標

  • 說出 Claude Code v2.1 起「兩層 Subagent」結構:內建(Explore、Plan、general-purpose)與自訂(Markdown 檔),以及各自適用的場景。
  • 寫出正確的 Subagent frontmatter,含 modeltoolspermissionModeskillsisolation 等欄位,並說明各欄位的取值依據。
  • 判斷一個子任務該用哪個模型、給哪些工具、何時需要 isolation: worktree、要不要預載 skills、是否需要 permissionMode
  • 說明 Subagent 與 Skill 的分工:Skill 是程序,Subagent 是執行容器;Skill 用 context: fork 把同一段程序丟到 Subagent 內執行,Subagent 用 skills: 預載程序到自己的 context。
  • 能在主流程 prompt 中正確叫用 Subagent(描述觸發或 @-mention 顯式叫用),並取回結論。

1. Subagent 是什麼

Subagent 是一個有獨立 context window、可指定模型與工具組合的子任務執行單元。主對話把工作丟進去,Subagent 在自己的 context 內跑完整個任務,最後只回傳結論給主對話(截至 2026-06 依官方 subagents 章節 [1])。 它解決的核心問題:把會把主對話 context 灌爆的副作用,關進獨立的 context 裡。把 200 個檔案掃過一次找出所有 deprecated import、跑大量 grep 蒐集資訊、執行 10 分鐘的測試並回傳失敗摘要。如果這些都在主對話做,幾萬 token 就被搜尋結果灌掉,模型在後面輪次還要付 attention 成本去掃過它們。Subagent 在自己 context 內做完,把摘要丟回來,主對話只需要付一次摘要的成本 兩個關鍵事實先記住:
  • Subagent 不能 spawn 另一個 Subagent(無巢狀)。需要分工時由主對話平行叫用多個 Subagent,或用 agent team(見 04-11)。
  • Subagent 的 system prompt 是你寫的 frontmatter 後的 Markdown body,不是 Claude Code 的完整 system prompt。你給的指令品質直接決定 Subagent 的行為。
與 01-4 上下文工程的銜接01-4 把 context window 比作 RAM:成本隨對話線性累積。Subagent 是「把大任務關到 swap partition」,主 RAM 只看到最終結論,沒看到中間的搜尋噪音。Subagent 與 Skill 的差別在於後者是把「程序描述」放進當前 context,Subagent 是把「整個執行過程」放到隔離 context。

2. 兩層結構:內建 + 自訂

Claude Code v2.1 起 Subagent 採「兩層」結構([1]):
內容觸發方式用途
內建Explore、Plan、general-purpose,外加 statusline-setup、claude-code-guide 等輔助模型依任務語意自動叫用,使用者不直接面對探索、規劃、複雜多步任務
自訂你寫的 Markdown 檔,存於 ~/.claude/agents/.claude/agents/、plugin agents/、managed settings 或 claude --agents CLI模型依 description 自動叫用、或主對話用 @subagent-name 顯式叫用特定領域的專用工作者

2.1 內建 Subagent

名稱模型工具用途
ExploreHaiku(快速、低延遲)唯讀工具(Write / Edit 拒絕)檔案搜尋、codebase 探索
Plan繼承主對話唯讀工具plan mode 下的研究(避免無限巢狀)
general-purpose繼承主對話全部工具探索加修改混合的複雜多步任務
statusline-setupSonnet(輔助)/statusline 設定狀態列時
claude-code-guideHaiku(輔助)回答 Claude Code 本身功能問題
Explore 與 Plan 有個特殊設計:它們跳過 CLAUDE.md 與父 session 的 git status,讓研究保持快速、便宜。其他內建與全部自訂 Subagent 都會載入 CLAUDE.md [1]。 叫用 Explore 時可以指定徹底程度(thoroughness level):quick(目標式查詢)、medium(平衡)、very thorough(全面分析)。

2.2 自訂 Subagent 與內建的差別

自訂 Subagent 的本體是一個 Markdown 檔,包含 YAML frontmatter(設定)與 body(system prompt)。可以建在多個 scope,scope 決定它在哪些 session 可用與優先序。 最重要的設計差異:
  • 內建 Subagent 跑唯讀任務為主(Plan、Explore),general-purpose 是唯一可寫的內建。
  • 自訂 Subagent 完全由你決定:可唯讀、可寫、可指定模型、可預載 Skill、可用 worktree 隔離。

3. 放置位置與優先序

自訂 Subagent 可放在五個 scope,優先序高到低 [1]:
位置範疇優先序建立方式
Managed settings組織全機器1(最高)管理者部署
--agents CLI flag當前 session2啟動 Claude Code 時傳 JSON
.claude/agents/當前專案(進版控)3互動式或手動
~/.claude/agents/你所有專案4互動式或手動
Plugin agents/ 目錄Plugin 啟用範圍內5(最低)隨 plugin 安裝
Claude Code 會遞迴掃描 .claude/agents/~/.claude/agents/,所以可以分子目錄組織(agents/review/agents/research/)。目錄路徑不影響 Subagent 識別,識別只看 frontmatter 的 name 欄位。同一 scope 內若兩個檔案宣告同名 name,Claude Code 會保留其中一個、丟掉另一個且不警告 [1]。 Plugin 的 agents/ 也遞迴掃描,但子目錄會變成 scoped identifier 的一部分my-plugin/agents/review/security.md 在 plugin my-plugin 內識別為 my-plugin:review:security [1]。
專案級 vs 使用者級怎麼選專案級(.claude/agents/)進版控、團隊共享,適合「這個 codebase 專用」的 Subagent。使用者級(~/.claude/agents/)跨專案可用,適合「我個人在所有工作都會用」的 Subagent,例如個人慣用的 code review agent。
Plugin 內 Subagent 限制三個 frontmatter 欄位安全考量,Plugin Subagent 不支援 hooksmcpServerspermissionMode 欄位,會被忽略 [1]。需要這三個時,把 agent 檔複製到 .claude/agents/~/.claude/agents/。另一條路是在 settings.jsonpermissions.allow 加規則,但該規則適用整個 session,無法只限 plugin agent。

4. frontmatter 完整參考

Subagent 檔案格式(截至 2026-06,依官方 subagents 章節 [1]):
---
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.
只有 namedescription 必填,其餘選填。完整欄位:
欄位必填用途
name唯一識別(小寫字母與連字符)。SubagentStart hook 收到的 agent_type 是這個值 [1]
description模型判斷何時委派給這個 Subagent 的依據
toolsSubagent 可用工具的白名單。省略時繼承全部工具。若要預載 Skill,skills 欄位,不要把 Skill 列在 tools [1]
disallowedTools黑名單,從繼承或指定清單中移除
modelsonnet / opus / haiku / 完整模型 ID / inherit(預設)
permissionModedefault / acceptEdits / auto / dontAsk / bypassPermissions / plan
maxTurnsSubagent 在此輪 agentic turn 數上限
skills預載 Skill 名稱清單到 Subagent context;full content 注入
mcpServers此 Subagent 專用的 MCP servers,可 inline 或 reference 已連線的 server
hooks此 Subagent 生命週期專屬 hooks
memory持久化記憶範圍:user / project / local
background預設背景模式 false;設 true 一律以 background task 跑
effort覆寫 session effort:low / medium / high / xhigh / max
isolationworktree 在暫時 git worktree 跑 Subagent
colorUI 顯示色:red / blue / green / yellow / purple / orange / pink / cyan
initialPrompt當此 agent 作為主 session 跑(--agentagent 設定)時的第一句 user turn
v2.1.63 起 Task 改為 Agent在 v2.1.63,Task tool 改命名為 Agent([1])。舊的 Task(...) 在 settings 與 agent 定義中仍可作為 alias 用。tools: Agent(worker, researcher) 是新語法,限制此 Subagent 可 spawn 哪些類型。

4.1 model 解析順序

當 Claude 叫用 Subagent 時,模型依下列順序解析 [1]:
1

CLAUDE_CODE_SUBAGENT_MODEL 環境變數

最高優先序,可在啟動環境統一指定所有 Subagent 的模型,覆寫一切。
2

該次叫用的 model 參數

呼叫端在叫用時傳入的 model 參數,優先於 frontmatter。
3

Subagent frontmatter model

Subagent 檔案內宣告的 model 欄位。model: inherit(預設)等同跟主對話用同模型。
4

主對話的模型

以上都未指定時,fallback 到主對話當前使用的模型。
重複性高、結構明確的子任務用便宜模型(Haiku),推理要求高的留給 Sonnet / Opus。這是 Subagent 最直接的省錢切入點。

4.2 工具白名單 vs 黑名單

tools 給白名單、disallowedTools 給黑名單。兩個都設時,先套黑名單,再從剩下的套白名單 [1]。 白名單範例(嚴格限制):
---
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
---
Subagent 不可用的工具清單即使列在 tools 內,下列工具也不能用於 Subagent [1]:
  • Agent(Subagent 不能 spawn 另一個 Subagent)
  • AskUserQuestion
  • EnterPlanMode
  • ExitPlanMode(除非 permissionMode: plan
  • ScheduleWakeup
  • WaitForMcpServers

4.3 限制可 spawn 的 Subagent 類型

當 agent 作為主 thread 跑(claude --agent),可 spawn 其他 Subagent。tools: Agent(worker, researcher) 限定可 spawn 哪些類型 [1]:
---
name: coordinator
description: Coordinates work across specialized agents
tools: Agent(worker, researcher), Read, Bash
---
這是白名單:只能 spawn workerresearcher。想允許任何類型用 tools: Agent, Read, Bash(不加括號)。完全不列 Agent 時,該 agent 不能 spawn 任何 Subagent。這個限制只對主 thread agent 生效;Subagent 本身不能 spawn 任何 Subagent(無巢狀),所以 Agent(agent_type) 在 Subagent frontmatter 內無作用 [1]。

4.4 permissionMode 細節

模式行為
default標準權限檢查與 prompt
acceptEdits自動接受工作目錄與 additionalDirectories 內的檔案編輯
autoAuto mode:背景 classifier 審查指令與受保護目錄寫入
dontAsk自動拒絕權限 prompt(顯式允許的工具仍可用)
bypassPermissions跳過所有權限 prompt
planPlan mode(唯讀探索)
父 session 模式優先若主 session 用 bypassPermissionsacceptEdits,Subagent 不能覆寫([1])。若主 session 用 auto mode,Subagent 繼承 auto mode,frontmatter 內的 permissionMode 被忽略:classifier 用與主 session 相同的規則評估 Subagent 工具呼叫。bypassPermissions 跳過所有權限 prompt,包括對 .git.claude.vscode.idea.husky.cargo 的寫入。Root 與 home 目錄的 rm -rf 仍會 prompt 作為電路斷路器 [1]。

4.5 skills:預載 Skill 內容到 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.
每個列出的 Skill 完整內容會在 Subagent 啟動時注入 context。這控制「預載哪些」,不是控制「可呼叫哪些」:沒列的 Skill,Subagent 還是可以透過 Skill tool 在執行中發現並叫用 project / user / plugin Skill [1]。 預載有反向限制:不能預載設了 disable-model-invocation: true 的 Skill,因為預載與模型可叫用共用同一組 Skill 集。若列出的 Skill 缺失或停用,Claude Code 跳過並在 debug log 寫 warning [1]。
Subagent 預載 Skill vs Skill 跑在 Subagent這是同一底層機制的兩種視角([1]):
  • Subagent frontmatter skills: [...]:Subagent 控 system prompt,把 Skill 內容載入。
  • Skill frontmatter context: fork + agent: ...:Skill 內容變成指定 agent 的 task prompt,agent 在乾淨 context 跑。
兩者底層是一個東西,只是寫法反過來。

4.6 isolation: worktree

isolation: worktree 讓 Subagent 在暫時的 git worktree 內跑,給它 repo 的一個隔離複本(從預設分支 fork,不是父 session 的 HEAD)[1]。
---
name: refactor-agent
description: Refactor a module in isolation
isolation: worktree
tools: Read, Edit, Write, Bash
---
worktree 行為:
  • Subagent 啟動時自動建一個暫時 worktree。
  • Subagent 的寫入只發生在這個 worktree,不影響主工作目錄。
  • 若 Subagent 沒做任何改動,worktree 自動清除 [1]。
  • 若有改動,你需要決定合併、保留、丟棄。
cd 在 Subagent 內不持久Subagent 內的 cd 不會跨 Bash / PowerShell 工具呼叫保留,也不影響主 session 的工作目錄 [1]。需要隔離工作目錄請用 isolation: worktree

5. 唯讀 vs 可寫、worktree 隔離何時用

判準只有一個:這個 Subagent 會不會改檔案或外部狀態?
類型任務工具worktree
唯讀搜尋、review、summarize、analyzeReadGlobGrep禁用 Write / Edit不需要
可寫(無平行衝突)重構、文件生成、單檔修改包含 Write / Edit不需要(同一 Subagent 自己)
可寫(多 Subagent 平行)多個 Subagent 同時改不同檔案包含 Write / Edit需要,每個 Subagent 各自 worktree
不可信輸入處理外部文件、URL、PR 內容最小集強烈建議(隔離爆炸半徑)
worktree 操作模式:
# 1. 為每個 Subagent 建獨立 worktree
git worktree add ../agent-A -b agent-A-branch
git worktree add ../agent-B -b agent-B-branch

# 2. Subagent 各自在 ../agent-A、../agent-B 內作業

# 3. 結束後合併或比較
git diff main agent-A-branch
git merge agent-A-branch
判斷清單
  1. 這個 Subagent 會寫檔或動外部狀態嗎?否,不需要 worktree。
  2. 同一批平行跑的 Subagent 會寫入重疊路徑嗎?是,需要 worktree。
  3. Subagent 會處理不可信內容(外部文件、隨機 PR)嗎?是,worktree 作為爆炸半徑隔離。

6. 與 Skill 的配合:程序 vs 容器

這是 Subagent 與 Skill 最容易混淆的地方。澄清它們的分工:
維度SkillSubagent
本質程序定義(步驟、判準、格式)執行容器(context、模型、工具、隔離)
載入時機模型判斷語意相關時叫用模型依 description 委派,或 @-mention
誰執行當前對話的 Claude(主對話或 Subagent)Subagent 自己
可重入同一個 Skill 在不同對話重複用同一個 Subagent 定義可被多個 session 委派
適合「這個流程要這樣跑」「這個任務丟到獨立 context 跑」

6.1 三種典型配合

只用 Skill:程序在主對話跑,沒隔離需求。例:「依這個寫作風格重寫文件」。 只用 Subagent:子任務程序簡單到寫在 Subagent 描述裡即可,沒複用需求。例:「搜尋 codebase 找所有用到 deprecated API 的地方」。 Skill + Subagent 搭配:兩條路徑。 路徑 A:Subagent 預載 Skill(skills: [...]
---
name: code-reviewer
description: Reviews code for team conventions
skills:
  - api-conventions
  - testing-standards
---

You are a code reviewer. Apply the preloaded conventions and standards.
路徑 B:Skill 用 context: fork 丟到 Subagent
# SKILL.md in a Skill directory
---
description: 研究某個主題並回傳引用清單
context: fork
agent: Explore
---

Research $ARGUMENTS thoroughly:
1. Use Glob and Grep to find relevant files
2. Read and analyze
3. Summarize with specific file references
兩條路徑底層是同一個機制,差別是「誰定義程序、誰定義容器」[1]。
context: fork 需要 Skill 內含明確任務Skill 內容若只是「遵守這些 API 慣例」(規範式、沒有明確任務),context: fork 會讓 Subagent 收到「慣例」但沒「要做什麼」,回傳空結果。context: fork 適合有明確步驟的程序型 Skill [1]。

7. 叫用 Subagent

7.1 自動叫用

Claude 讀 Subagent 的 description,當任務語意匹配時自動委派。寫好 description 是觸發的關鍵。
觸發描述寫法對照太泛,會誤觸:
description: 幫我處理各種任務
太窄,會漏觸:
description: 幫我把週末研究日誌轉成 markdown
剛好:
description: 在 Python codebase 找型別錯誤、未使用 import、與公開函式缺 docstring 的問題。Use when reviewing Python files or after a refactor.

7.2 顯式叫用:@-mention

主對話用 @subagent-name 顯式叫用。例:「用 @code-reviewer 看看這個 PR 改了什麼」。 Plugin 內的 Subagent 用 namespaced 識別:@my-plugin:review:security [1]。

7.3 背景模式

background: true 讓 Subagent 一律以 background task 跑,可與主對話並行;Subagent 完成時 Claude Code 會通知主對話 [1]。

8. 工具對照

各家工具對「獨立 context 子代理」的對應機制差異顯著(截至 2026-06):
概念Anthropic Claude(主範本)OpenAI CodexGoogle AntigravityGitHub Copilot CLICursor(短提)
自訂 Subagent 格式Markdown frontmatter 檔~/.codex/agents/*.toml(個人)/ .codex/agents/*.toml(專案)加 config.toml[agents] 全域參數,必填 name/description/developer_instructions [6].agents/agents/*.md frontmatter [需確認原始出處]不適用主流程(CLI 為單代理).cursor/agents/ 與內建 Subagent [需確認原始出處]
內建子代理Explore(Haiku 唯讀)、Plan(繼承 唯讀)、general-purpose(繼承 全工具)系統層 provider agent系統層 sub-agent不適用Composer、Background Agent 等 [需確認原始出處]
指定模型model: sonnet/opus/haiku/inherit/<id>設定式設定式設定式設定式
工具收斂tools 白名單 + disallowedTools 黑名單設定式設定式工具白名單 / 黑名單設定式
隔離機制isolation: worktree環境層環境層環境層環境層
預載 Skillskills: [...] frontmatter不適用設定式不適用不適用
權限模式permissionMode: default/acceptEdits/auto/dontAsk/bypassPermissions/plan設定式設定式設定式設定式
持久化記憶memory: user/project/local不適用Memory 機制不適用不適用
顯式叫用@subagent-name/agent 指令設定式設定式@agent
命名澄清
  • Claude Code 的 Subagent 工具名:v2.1.63 起從 Task 改為 Agent(舊 Task(...) 仍可作 alias)([1])。tools: Agent(worker, researcher) 限制可 spawn 類型是 v2.1 後的標準寫法。
  • OpenAI Codex 的 Subagent 已對官方查證 [6]:config.toml[agents] 定全域參數(max_threads / max_depth / job_max_runtime_seconds),各角色為 ~/.codex/agents/*.toml(個人)或 .codex/agents/*.toml(專案)。它沒有 ~/.codex/prompts/*.md,也沒有 codex.md,持久指令走 AGENTS.mdAntigravity、Cursor 的對應機制仍以各家當前文件為準,標「需確認原始出處」項目待查證。
  • GitHub Copilot CLI 截至 2026-06 為單代理模型,不在 Subagent 概念下提供一等公民機制;雲端 coding agent 是另一條路線。
  • Cursor 為第三方 IDE(Anysphere),本 Playbook 僅短提一欄。

9. 動手做

30 分鐘練習
  1. 寫唯讀 Subagent:建 ~/.claude/agents/api-explorer.md,frontmatter 給 tools: Read, Glob, Grepmodel: haiku,body 寫「掃描 src/api/ 下的端點、回報每個的 method、路徑、認證需求」。用 /agents 確認它出現在 Library。
  2. 寫可寫 Subagent:建 .claude/agents/doc-fixer.md,frontmatter 給 tools: Read, Edit, Grepmodel: haikupermissionMode: acceptEdits,body 寫「把所有 .md 內的 TODO 換成連結到 issues 的錨點」。在同一專案下用 @doc-fixer 顯式叫用。
  3. 隔離測試:用 isolation: worktree 寫一個 Subagent,讓它改一個檔;觀察 worktree 自動建立、Subagent 改完後 worktree 還在、與主工作目錄的差異。沒改動時應自動清除。
  4. Skill + Subagent:寫一個 Skill 用 context: forkagent: Explore;叫用 Skill 觀察它在獨立 context 跑,結果摘要回傳主對話。
  5. 預載 Skill:寫一個 Subagent 用 skills: [api-conventions],啟動 session 後觀察 Skill 內容是否已在 Subagent context(從 Subagent 內問「你看到 api-conventions 嗎」驗證)。

10. 常見誤區

反模式清單
  • 每個 Subagent 都用最強模型:重複性高的子任務用 Haiku 系列即可;Opus 留給真正需要深度推理的場景,否則成本線性累積。
  • 給 Subagent 過寬工具權限:唯讀任務給了 WriteBash,等於白費隔離的意義,也增加供應鏈風險。預設用白名單列最小集。
  • 把 Skill 程序寫進 Subagent 描述卻沒複用需求:若只用一次,不必強行拆成 Skill,直接在 Subagent body 寫明程序更直接。
  • isolation: worktree 對唯讀任務:沒寫入就不需要 worktree;加了只是浪費磁碟與建置時間。
  • 沒設計 description 就期待模型觸發:模型觸發靠語意比對,描述太模糊、太技術、太空泛都會漏觸。
  • 把 Subagent 當 Thread 來用:Subagent 是一次性容器,任務結束就消滅。需要持續對話、可定址代理,請用 agent team(見 04-11)。
  • 在 Subagent body 內放敏感資訊:Subagent body 進 context、若進版控則對所有人可見。機密應用環境變數或動態注入。

自我檢核

自我檢核
  1. 你能說出 Claude Code v2.1 Subagent 的兩層結構,以及內建三個(Explore、Plan、general-purpose)各自的模型與工具預設嗎?
  2. 你能寫出一個 frontmatter 完整、description 觸發精準的 Subagent 嗎?
  3. 你能對手邊一個真實子任務說清楚:它的 model 選擇依據、tools 最小集、是否需要 isolation: worktreepermissionMode 該不該用哪個,以及它有沒有用 skills 預載 Skill?
  4. 你能分清 Subagent 與 Skill 的關係嗎?什麼時候該只用其中一個、什麼時候該搭配?

來源與延伸閱讀

事實主張依官方文件,快變動項標註截至 2026-05。
  • [1] Anthropic, “Create custom subagents,” code.claude.com, 2026. (含兩層結構、frontmatter 完整參考、isolation: worktreeskills 預載、memory 持久化、v2.1.63 Task 改為 Agent 命名) https://code.claude.com/docs/en/subagents (截至 2026-06)
  • [2] Anthropic, “Extend Claude with skills,” code.claude.com, 2026. (含 Skill 與 Subagent 透過 context: forkskills: 預載的兩條配合路徑) https://code.claude.com/docs/en/skills (截至 2026-06)
  • [3] Anthropic, “Plugins reference,” code.claude.com, 2026. (Plugin Subagent 限制 hooks / mcpServers / permissionMode 三欄位) https://code.claude.com/docs/en/plugins-reference (截至 2026-06)
  • [4] Anthropic, “Worktrees,” code.claude.com, 2026. (isolation: worktree 機制與 base branch 預設行為) https://code.claude.com/docs/en/worktrees (截至 2026-06)
  • [5] Agent Skills Open Standard, “Agent Skills,” 2026. (Skill 與 Subagent 互通的開放標準) https://agentskills.io (截至 2026-06)
  • [6] OpenAI, “Subagents,” developers.openai.com/codex, 2026. (config.toml[agents] 全域參數 max_threads / max_depth / job_max_runtime_seconds;獨立 agent TOML 於 ~/.codex/agents/(個人)與 .codex/agents/(專案),必填 name / description / developer_instructions,選填 model / sandbox_mode / mcp_servers;無 prompts/*.mdcodex.md,持久指令用 AGENTS.mdhttps://developers.openai.com/codex/subagents (截至 2026-06)