SpyBara
Go Premium

sub-agents.md 2026-09-09 22:58 UTC to 2026-09-10 23:00 UTC

This page contains 351 additions and 119 deletions.

2026
Thu 10 23:00 Sat 12 03:02 Fri 18 23:58 Tue 22 23:59 Fri 25 23:58

建立自訂 subagents

在 Claude Code 中建立和使用專門的 AI subagents,用於特定任務的工作流程和改進的上下文管理。

Subagents 是專門的 AI 助手,用於處理特定類型的任務。當側面任務會用搜尋結果、日誌或檔案內容淹沒您的主要對話時,請使用一個 subagent,而您不會再次參考這些內容:subagent 在自己的上下文中執行該工作,並僅返回摘要。當您持續產生相同類型的工作者並使用相同指令時,定義自訂 subagent。

每個 subagent 在自己的 context window 中執行,具有自訂系統提示、特定工具存取和獨立權限。當 Claude 遇到與 subagent 描述相符的任務時,它會委派給該 subagent,該 subagent 獨立工作並返回結果。若要在實踐中查看上下文節省,context window visualization 會逐步說明一個 subagent 在自己的獨立視窗中處理研究的工作階段。

Subagents 可以幫助您:

  • 保留上下文,將探索和實現保持在主要對話之外
  • 強制執行約束,限制 subagent 可以使用的工具
  • 跨專案重複使用配置,使用使用者層級的 subagents
  • 專門化行為,針對特定領域使用專注的系統提示
  • 控制成本,將任務路由到更快、更便宜的模型,如 Haiku

Claude 使用每個 subagent 的描述來決定何時委派任務。當您建立 subagent 時,請寫一個清晰的描述,以便 Claude 知道何時使用它。

這些描述會佔用上下文,因此請保持簡短。當您的 subagents(除了內建的 subagents 外)的合併描述超過 15,000 個 tokens 時,Claude Code 會在啟動時顯示 警告,並顯示總 token 計數。修剪您的 subagents 的 description 欄位,並將詳細資訊移至每個 subagent 的系統提示中,該提示僅在該 subagent 執行時載入。

內建 subagents

Claude Code 包括內建 subagents,Claude 在適當時會自動使用。每個都繼承父對話的權限;大多數以受限的工具集執行。

Explore 和 Plan 會跳過您的 CLAUDE.md 檔案和父工作階段的 git status,以保持研究快速且經濟高效。其他所有內建和自訂 subagent 都會載入兩者。如需了解到達 subagent 的完整詳細資訊,請參閱啟動時載入的內容。

一個快速、唯讀的代理,針對搜尋和分析程式碼庫進行最佳化。

  • Model:繼承自主要對話,在 Claude API 上限制為 Opus,因此 Explore 永遠不會在比您已為工作階段選擇的模型更昂貴的模型上執行,除非您設定 CLAUDE_CODE_SUBAGENT_MODEL 並強制將其套用至每個 subagent
  • Tools:唯讀工具;Write 和 Edit 被拒絕
  • Purpose:檔案發現、程式碼搜尋、程式碼庫探索

自 v2.1.198 起,Explore 繼承主要對話的模型,而不是始終在 Haiku 上執行。在 Claude API 上,繼承的模型限制為 Opus:主要對話在更高層級上會在 Opus 上執行 Explore,而主要對話在 Sonnet 或 Haiku 上會在相同模型上執行 Explore。在任何其他提供者上,例如 Amazon Bedrock、Google Cloud 的 Agent Platform、Microsoft Foundry 或 AWS 上的 Claude Platform,Explore 直接繼承主要對話的模型。

一個名為 Explore 的使用者或專案 subagent 會覆蓋內建的,並保留其自己的 model 欄位,因此定義一個具有 model: haiku 的以保持探索在較低成本的模型上。

當 Claude 需要搜尋或理解程式碼庫而不進行更改時,它會委派給 Explore。這樣可以將探索結果保持在主要對話上下文之外。

當呼叫 Explore 時,Claude 指定一個徹底程度:quick 用於目標查詢,medium 用於平衡探索,或 very thorough 用於全面分析。

內建 subagents 在互動式工作階段中預設會被註冊。若要限制它們:

當工作階段沒有 general-purpose subagent 可回退時,省略 subagent_type 的 Agent 工具呼叫會失敗,並出現 subagent_type is required 錯誤。

除了這些內建 subagents 之外,您可以建立自己的 subagents,具有自訂提示、工具限制、權限模式、hooks 和 skills。以下部分展示如何開始和自訂 subagents。

快速入門:建立您的第一個 subagent

Subagents 是具有 YAML frontmatter 的 Markdown 檔案。若要建立一個,請要求 Claude 為您撰寫,或 自行撰寫檔案。

自 v2.1.198 起,/agents 命令不再開啟互動式建立精靈;執行它會列印提醒,要求您詢問 Claude 或直接編輯 .claude/agents/。Subagent 檔案、frontmatter 欄位以及 .claude/agents/ 和 ~/.claude/agents/ 位置保持不變;只有終端精靈被移除。

本逐步指南建立一個使用者層級的 subagent,用於審查程式碼並提出改進建議。

1

要求 Claude 建立 subagent

在 Claude Code 中,描述您想要的 subagent 及其儲存位置:

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、description、tools 清單、model 和系統提示的檔案。

2

檢查檔案

開啟 ~/.claude/agents/code-improver.md 並確認 frontmatter 符合您的要求。結果如下所示:

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

因為檔案位於 ~/.claude/agents/,所以 subagent 在您機器上的每個專案中都可用。若要改為將其範圍限制在一個專案,請將其移至該專案的 .claude/agents/ 目錄。選擇 subagent 範圍 比較了兩者。

3

試試看

要求 Claude 委派給新的 subagent:

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

Claude 委派給您的新 subagent,它掃描程式碼庫並返回改進建議。在文字記錄中,委派會顯示為工具呼叫列,顯示 subagent 的名稱,後面跟著簡短的工作描述,例如 code-improver(Suggest code improvements)。

如果 Claude 找不到新的 subagent,請重新啟動 Claude Code 並再試一次。這只在 ~/.claude/agents/ 在工作階段開始前不存在時發生,因為執行中的工作階段不會偵測到新建立的 agents 目錄。

現在您有一個 subagent,可以在機器上的任何專案中使用它來分析程式碼庫並提出改進建議。

您也可以手動撰寫 subagent 檔案、透過 CLI 旗標定義它們,或透過外掛程式分發它們。以下部分涵蓋所有配置選項。

配置 subagents

Subagent 的檔案位置決定了誰可以使用它,其 frontmatter 決定了它可以做什麼。本節涵蓋 subagent 檔案的位置以及它們支援的每個欄位。

選擇 subagent 範圍

根據範圍將 subagent 檔案儲存在不同位置。當多個 subagents 共享相同名稱時,Claude Code 使用來自優先級較高位置的那個。

Location Scope Priority 如何建立
受管設定 組織範圍 1(最高) 透過 managed settings 部署
--agents CLI 標誌 目前工作階段 2 啟動 Claude Code 時傳遞 JSON
.claude/agents/ 目前專案 3 詢問 Claude,或手動建立檔案
~/.claude/agents/ 所有您的專案 4 詢問 Claude,或手動建立檔案
Plugin 的 agents/ 目錄 啟用外掛程式的位置 5(最低) 使用 plugins 安裝

專案 subagents(.claude/agents/)非常適合特定於程式碼庫的 subagents。將它們簽入版本控制,以便您的團隊可以協作使用和改進它們。

專案 subagents 是透過從目前工作目錄向上走來發現的,因此會掃描那裡和儲存庫根目錄之間的每個 .claude/agents/。自 v2.1.178 起,當這些巢狀目錄中的多個定義相同的 name 時,Claude Code 使用最接近工作目錄的定義。

使用 --add-dir 或 /add-dir 新增的目錄時,Claude Code 也會載入其 .claude/agents/ 資料夾,與您的專案 subagents 一起。請參閱 Additional directories 以了解哪些其他配置類型從 --add-dir 載入。若要跨專案共享 subagents 而不使用 --add-dir,請使用 ~/.claude/agents/ 或 plugin。

使用者 subagents(~/.claude/agents/)是在所有專案中可用的個人 subagents。

Claude Code 會遞迴掃描 .claude/agents/ 和 ~/.claude/agents/,因此您可以將定義組織到子資料夾中,例如 agents/review/ 或 agents/research/。子目錄路徑不會影響 subagent 的識別或呼叫方式,因為身份僅來自 name frontmatter 欄位。

在整個樹中保持 name 值唯一:如果一個 .claude/agents/ 目錄下的兩個檔案(包括其子資料夾)宣告相同的名稱,Claude Code 只會載入其中一個,由檔案系統讀取順序選擇,而不是有文件記載的優先級。在巢狀專案目錄中,最接近工作目錄的定義獲勝,如上所述。/doctor 設定檢查會報告同一目錄中共享名稱的檔案,並建議重新命名或移除除一個以外的所有檔案。在 v2.1.205 之前,/doctor 開啟診斷畫面,列出重複項並顯示哪個定義處於活動狀態。

外掛程式 agents/ 目錄也會遞迴掃描。與專案和使用者範圍不同,外掛程式 agents/ 目錄內的子資料夾成為 scoped identifier 的一部分:外掛程式 my-plugin 中位於 agents/review/security.md 的檔案註冊為 my-plugin:review:security。

CLI 定義的 subagents 在啟動 Claude Code 時作為 JSON 傳遞。它們僅存在於該工作階段,不會儲存到磁碟,使其適用於快速測試或自動化指令碼。您可以在單一 --agents 呼叫中定義多個 subagents:

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."
}
}'

--agents 標誌接受 JSON,具有 prompt 欄位加上這些 frontmatter 欄位:description、tools、disallowedTools、model、permissionMode、mcpServers、hooks、maxTurns、skills、initialPrompt、memory、effort、background 和 isolation。使用 prompt 作為系統提示,等同於基於檔案的 subagents 中的 markdown 主體。JSON 中的每個頂級鍵是代理的名稱。不要以 - 開頭的名稱。

關於 Claude Code 對無法載入的值所做的操作,以及跳過該檢查的標誌和環境變數,請參閱 Invalid --agents configuration。

受管 subagents 由組織管理員部署。將 markdown 檔案放在 managed settings directory 內的 .claude/agents/ 中,使用與專案和使用者 subagents 相同的 frontmatter 格式。受管定義優先於具有相同名稱的專案和使用者 subagents。

外掛程式 subagents 來自您已安裝的 plugins。它們與您的自訂 subagents 一起自動載入,並在 @-mention 類型提前中以其範圍名稱出現。請參閱 plugin components reference 以了解建立外掛程式 subagents 的詳細資訊。

來自任何這些範圍的 subagent 定義也可用於 agent teams:當產生隊友時,您可以參考 subagent 類型,Claude Code 會將該定義的部分應用於隊友。請參閱 agent teams 以了解在每個顯示模式中應用哪些部分。

編寫 subagent 檔案

Subagent 檔案使用 YAML frontmatter 進行配置,後面跟著 Markdown 中的系統提示:

---
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 定義 subagent 的中繼資料和配置。主體成為指導 subagent 行為的系統提示。Subagents 只接收此系統提示加上基本環境詳細資訊(如工作目錄),而不是 Claude Code 系統提示。

在 non-interactive mode 中,傳遞 --append-subagent-system-prompt 以將您的文字附加到每個 subagent 的系統提示末尾,包括巢狀 subagents,除了 forked subagent,它重新使用對話自己的提示。需要 Claude Code v2.1.205 或更高版本。如果您的文字太長而無法在命令列上傳遞,請將其儲存到檔案並使用 --append-subagent-system-prompt-file 傳遞路徑。檔案標誌需要 Claude Code v2.1.261 或更高版本。

一個 subagent 在主要對話的目前工作目錄中啟動。在 subagent 內,cd 命令不會在 Bash 或 PowerShell 工具呼叫之間持續,也不會影響主要對話的工作目錄。若要改為給 subagent 儲存庫的隔離副本,請設定 isolation: worktree。

具有 isolation: worktree 的 subagent 在其 worktree 內執行其 Bash 和 PowerShell 命令。一個工作目錄解析到您的主要簽出的命令(例如,因為 subagent 執行時 worktree 目錄被移除)會失敗並出現錯誤。在 v2.1.203 之前,此類命令可能在主要簽出中執行。

此工作目錄檢查涵蓋包含您啟動 Claude Code 的目錄的整個儲存庫。當您的工作階段在其自己的連結 worktree 中執行時,檢查也涵蓋該 worktree 連結的主要簽出。在 v2.1.210 之前,檢查僅涵蓋啟動目錄本身。一個工作目錄解析到同一儲存庫中其他地方的命令(例如當您從 monorepo 子目錄啟動 Claude Code 時的儲存庫根目錄)在那裡執行,而不是失敗。

對於 Bash 命令,Claude Code 也以兩種方式檢查命令本身:

  • 它阻止將 git 重定向到主要簽出的命令。
  • 當它無法從命令文字驗證命令執行的任何 git 都保留在 worktree 內時,它拒絕命令,例如當命令名稱在執行時計算時。

重定向向量和形狀規則列在 How Claude Code enforces isolation 下。PowerShell 命令僅獲得工作目錄檢查。

Monitor 命令經過與 Bash 命令相同的工作目錄和命令內容檢查。

當主要對話本身在 worktree 中隔離執行時,Claude Code 對工作階段和它產生的每個 subagent 應用相同的檢查,包括沒有 isolation: worktree 的 subagents;請參閱 How Claude Code enforces isolation。

支援的 frontmatter 欄位

以下欄位可用於 YAML frontmatter。只有 name 和 description 是必需的。

Field 必需 Description
name 是 使用小寫字母和連字號的唯一識別碼。Hooks 將此值作為 agent_type 接收。檔案名稱不必相符。名稱不能包含 :,這是為 plugin-scoped identifiers 保留的,例如 my-plugin:reviewer。Claude Code 不會載入名稱包含一個的檔案,並將錯誤記錄到除錯日誌。在 v2.1.218 之前,此類名稱被接受
description 是 Claude 何時應委派給此 subagent
tools 否 Tools subagent 可以使用。如果省略,繼承 subagents 可用的每個工具。如果清單中沒有條目解析為工具,subagent 通常 fails to launch 並出現命名條目的錯誤。若要將 Skills 預載入上下文,請使用 skills 欄位而不是在此列出 Skill
disallowedTools 否 要拒絕的工具,從繼承或指定的清單中移除
model 否 Model 使用:sonnet、opus、haiku、fable、完整模型 ID(例如,claude-opus-5)或 inherit。當您省略它時,Claude Code 在 subagent model order 中選擇模型
permissionMode 否 Permission mode:default、acceptEdits、auto、dontAsk、bypassPermissions、plan 或 manual 作為 default 的別名。manual 別名需要 Claude Code v2.1.200 或更高版本。針對 plugin subagents 被忽略
maxTurns 否 subagent 停止前的最大代理轉數。當 subagent 達到限制時,Claude Code 傳回其輸出標記為部分,Claude 可以 resume it 以繼續。部分標記需要 Claude Code v2.1.246 或更高版本
skills 否 Skills 在啟動時預載入到 subagent 的上下文中。注入完整技能內容,而不僅僅是描述。Subagents 仍然可以透過 Skill 工具呼叫未列出的專案、使用者和外掛程式技能
mcpServers 否 MCP servers 可用於此 subagent。每個條目要麼是參考已配置伺服器的伺服器名稱(例如,"slack"),要麼是內聯定義,其中伺服器名稱為鍵,完整 MCP server config 為值。針對 plugin subagents 被忽略
hooks 否 Lifecycle hooks 限定於此 subagent。針對 plugin subagents 被忽略
memory 否 Persistent memory scope:user、project 或 local。啟用跨工作階段學習
background 否 設定為 true 以即使 Claude 要求在前景執行也保持此 subagent 在背景。其中 fork mode 開啟時,Claude Code 已經在 background 中執行 Claude 產生的 subagents
effort 否 此 subagent 活動時的努力程度。覆蓋工作階段努力程度。預設:從工作階段繼承。選項:low、medium、high、xhigh、max;可用的層級取決於模型
isolation 否 設定為 worktree 以在臨時 git worktree 中執行 subagent,為其提供儲存庫的隔離副本,預設從您的 default branch 分支,而不是父工作階段的 HEAD。如果 subagent 不進行任何更改,worktree 會自動清理
color 否 Subagent 在任務清單和文字中的顯示顏色。接受 red、blue、green、yellow、purple、orange、pink 或 cyan
initialPrompt 否 當此代理作為主工作階段代理執行時(透過 --agent 或 agent 設定),自動提交為第一個使用者轉數。Commands 和 skills 會被處理。前置於任何使用者提供的提示
experimental 否 實驗選項的對應。將其 cacheTtl 鍵設定為 5m 或 1h 以選擇此 subagent 請求的 prompt cache lifetime,在 cache lifetime precedence 中 frontmatter 的位置。Claude Code 忽略任何其他值,在您的 Claude 訂閱使用使用額度時忽略 1h,並僅從 subagent 檔案讀取欄位。需要 Claude Code v2.1.248 或更高版本

在 experimental 對應內寫入 cacheTtl,而不是在 frontmatter 的頂級。

---
name: repo-auditor
description: Audits a large repository and reports what it finds
experimental:
  cacheTtl: 1h
---

Subagent 檔案 Claude Code 跳過

Claude Code 跳過專案、使用者或受管 agents 目錄中的檔案,或在您使用 --add-dir 新增的目錄下的檔案,而不在工作階段中報告它,當 frontmatter 有以下任何問題時:

  • 沒有 name:Claude Code 將檔案視為保存在您的代理旁邊的文件。
  • 開啟 --- 不是檔案的第一行:Claude Code 讀取檔案為沒有 frontmatter,並將其視為文件。
  • name 以 - 開頭或包含 ::Claude Code 跳過檔案並將錯誤寫入除錯日誌。請參閱上表中的 name 列。
  • name 但沒有 description:Claude Code 跳過檔案並將原因寫入除錯日誌。
  • 不解析的 YAML:Claude Code 不從檔案讀取任何欄位,跳過它,並將解析錯誤寫入除錯日誌。

若要查看除錯日誌,請使用 --debug 執行 Claude Code。

一個 plugin subagent,其 frontmatter 沒有 name 或不解析,仍然在其檔案名稱下載入。

在工作階段前檢查 `agents` 目錄

若要找到 agents 目錄中 frontmatter 不解析的檔案,請針對目錄執行 claude plugin validate,例如 .claude/agents 或 ~/.claude/agents。Claude Code 僅檢查 您命名的目錄,並且不會標記 frontmatter 解析但沒有 name 的檔案。需要 Claude Code v2.1.233 或更高版本。

選擇模型

model 欄位控制 subagent 使用的模型:

  • Model alias:使用可用的別名之一:sonnet、opus、haiku 或 fable
  • Full model ID:使用完整模型 ID,例如 claude-opus-5 或 claude-sonnet-5。接受與 --model 標誌相同的值
  • inherit:使用與主要對話相同的模型

當 Claude 呼叫 subagent 時,它也可以為該特定呼叫傳遞 model 參數。Claude Code 按此順序解析 subagent 的模型:

  1. 每次呼叫的 model 參數
  2. Subagent 定義的 model frontmatter,其中 inherit 選擇主要對話的模型
  3. CLAUDE_CODE_SUBAGENT_MODEL 環境變數,當您將其設定為模型別名或模型 ID 時
  4. 主要對話的模型

設定 CLAUDE_CODE_SUBAGENT_MODEL 本身不會改變內建 Explore 和 Plan subagents 執行的模型。若要改變它,請參閱 Run every subagent on one model。

在 v2.1.251 之前,CLAUDE_CODE_SUBAGENT_MODEL 在此順序中排在第一位,並覆蓋每次呼叫參數和 frontmatter,包括 model: inherit。

將變數設定為 inherit 與不設定相同。在 v2.1.196 之前,該值強制 subagents 使用主要對話的模型,並忽略其他來源。

Claude Code 根據您組織的 availableModels 允許清單檢查每次呼叫參數、frontmatter 和環境變數值。對於被阻止的值,它替換另一個模型:

  • 當被阻止的值是家族別名(例如 opus)時,Claude Code 在允許清單允許的該家族的最新版本上執行 subagent,遵循與 /model 相同的 substitution rules and provider scope。在 v2.1.222 之前,Claude Code 也在被阻止的家族別名的繼承模型上執行 subagent。
  • 對於任何其他被阻止的值,在該替換不操作的提供者上,或當允許清單允許該家族沒有版本時,Claude Code 改為在繼承模型上執行 subagent。如果您設定 CLAUDE_CODE_SUBAGENT_MODEL,Claude Code 首先嘗試該模型,在這些相同的規則下。

在互動工作階段中,Claude Code 顯示警告,命名請求的模型和 subagent 執行的模型,對於任一替換。

若要檢查 subagent 執行的模型,請執行 /tasks。Claude Code 在 subagent 的列上命名模型,並在 subagent 的定義或它分叉的技能設定 effort 時新增 effort level。需要 Claude Code v2.1.242 或更高版本。

每次呼叫 model 參數也適用於 subagent resumed or sent a follow-up message 時,因此 subagent 保持在該模型上。在 v2.1.211 之前,恢復會丟棄每次呼叫值,subagent 恢復為其定義的 model 欄位或,沒有一個,主要對話的模型。

自 v2.1.198 起,subagents 也繼承主要對話的 extended thinking 配置:如果思考在您的工作階段中開啟,它對 subagent 也開啟,如果關閉,它保持關閉。沒有每個 subagent 的思考設定。在 v2.1.198 之前,subagents 執行時禁用擴展思考,無論主要對話的設定如何。

在一個模型上執行每個 subagent

CLAUDE_CODE_SUBAGENT_MODEL 是預設值,因此 subagent 的定義或 Claude 傳遞的模型仍然優先於它。若要將一個模型應用於每個 subagent、teammate 和 workflow agent,也將 CLAUDE_CODE_SUBAGENT_MODEL_FORCE 設定為 1。需要 Claude Code v2.1.257 或更高版本。

  • 如果您設定兩個變數,subagents 在 CLAUDE_CODE_SUBAGENT_MODEL 中的模型上執行。
  • 如果您僅設定 CLAUDE_CODE_SUBAGENT_MODEL_FORCE,subagents 在主要對話的模型上執行。

例如,若要在 Haiku 上執行每個 subagent,請在 settings file 的 env 區塊中設定兩個變數:

{
  "env": {
    "CLAUDE_CODE_SUBAGENT_MODEL": "haiku",
    "CLAUDE_CODE_SUBAGENT_MODEL_FORCE": "1"
  }
}

若要檢查設定是否生效,請在 subagent 執行時執行 /tasks。Subagent 的列顯示它執行的模型。

當 CLAUDE_CODE_SUBAGENT_MODEL_FORCE on 時,Claude Code 忽略每個 subagent 定義的 model 欄位,包括內建 Explore 和 Plan subagents,Claude 無法在啟動 subagent 時傳遞模型。兩種 subagent 仍然在主要對話的模型上執行:

當您僅設定 CLAUDE_CODE_SUBAGENT_MODEL_FORCE 時,內建 Explore subagent 保持其 model cap。

控制 subagent 功能

您可以透過工具存取、權限模式和條件規則來控制 subagents 可以執行的操作。

可用工具

Subagents 繼承主要對話中可用的 built-in tools 和 MCP 工具,由兩個過濾器縮小:第一個從每個 subagent 移除工具的簡短清單,第二個減少在 background 中執行的 subagents 的內建工具集,這是預設值。Forks 跳過兩個過濾器,並接收主要對話的確切工具池。第一個過濾器移除這些工具,即使在 tools 欄位中列出:

  • Agent,當 subagent 在 depth limit 時;在 fork 中工具保持列出但傳回錯誤而不是產生
  • AskUserQuestion
  • EndConversation,只能結束主要對話;請參閱 EndConversation tool behavior
  • EnterPlanMode
  • ExitPlanMode,除非 subagent 的 permissionMode 是 plan
  • ScheduleWakeup
  • TaskOutput
  • WaitForMcpServers
  • Workflow

第二個過濾器適用於在背景中執行的 subagents。除了 Agent 和 ExitPlanMode,它們遵循第一個過濾器的條件,無論 subagent 在哪裡執行,背景 subagent 保持每個 MCP 工具,但只有這些內建工具:Read、Grep、Glob、Bash、PowerShell、Edit、Write、NotebookEdit、WebFetch、WebSearch、TodoWrite、Skill、ToolSearch、EnterWorktree、ExitWorktree、Monitor、TaskStop、SendMessage 和 Artifact。Claude Code 從背景 subagent 移除每個其他內建工具,無論繼承或在 tools 欄位中列出,因此相同的定義可以在前景和背景中解析為不同的工具。移除報告沒有錯誤,除非它使 tools 清單 resolving to nothing。

ListAgents 遵循這些過濾器,如同任何內建工具:前景 subagent 在啟用跨工作階段訊息的工作階段中繼承它,背景 subagent 不保持它。

agent teams 中的隊友另外保持任務工具和 cron 工具:TaskCreate、TaskGet、TaskList、TaskUpdate、CronCreate、CronDelete 和 CronList。

在 session without the Task tools 中,Claude Code 也不向 subagents 提供任務工具,即使 subagent 執行不同的模型。進程內隊友遵循您的工作階段相同的方式,而在其自己的 split pane 中的隊友作為單獨的 Claude Code 程序執行,因此其自己的模型決定。

若要限制工具,請使用 tools 欄位作為允許清單或 disallowedTools 欄位作為拒絕清單。此範例使用 tools 來僅允許 Read、Grep、Glob 和 Bash。Subagent 無法編輯檔案、寫入檔案或使用任何 MCP 工具:

---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---

此範例使用 disallowedTools 來繼承 subagent 的工具池,除了 Write 和 Edit。Subagent 保留 Bash、MCP 工具和其餘池:

---
name: no-writes
description: Inherits the available tools except file writes
disallowedTools: Write, Edit
---

如果兩者都設定,disallowedTools 首先應用,然後 tools 針對剩餘的池進行解析。同時列在兩者中的工具會被移除。

當 tools 清單中沒有任何內容解析為工具時,例如因為每個條目都拼寫錯誤或命名一個對 subagents 不可用的工具,Claude Code 通常拒絕啟動 subagent,Agent 工具傳回命名未解析條目的錯誤;請參閱 Agent would be spawned with zero tools 以了解訊息以及如何修復每個條目。在 v2.1.208 之前,該 subagent 啟動時沒有工具,可能會傳回空的或令人困惑的結果。

除了確切的工具名稱之外,兩個欄位還接受 MCP 伺服器層級的模式:mcp__<server> 或 mcp__<server>__* 授予或移除來自命名伺服器的每個工具。在 disallowedTools 中,mcp__* 也會移除來自任何伺服器的每個 MCP 工具。此範例移除來自 github MCP 伺服器的每個工具,同時保留來自其他伺服器的工具和其池中的內建工具:

---
name: local-only
description: Inherits every tool except those from the github MCP server
disallowedTools: mcp__github
---

限制可以產生的 subagents

當代理以 claude --agent 作為主執行緒執行時,它可以使用 Agent 工具產生 subagents。若要限制它可以產生的 subagent 類型,請在 tools 欄位中使用 Agent(agent_type) 語法。

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

這是一個允許清單:只有 worker 和 researcher subagents 可以產生。如果代理嘗試產生任何其他類型,請求失敗,代理在其提示中只看到允許的類型。若要在允許所有其他類型的同時阻止特定代理,請改用 permissions.deny。

若要允許產生任何 subagent 而不受限制,請使用不帶括號的 Agent:

tools: Agent, Read, Bash

如果 Agent 完全從 tools 清單中省略,代理無法產生任何 subagents。

Agent(agent_type) 允許清單語法僅適用於以 claude --agent 作為主執行緒執行的代理。在 subagent 定義中,在 tools 中列出 Agent 讓該 subagent 產生自己的 subagents,同時 depth limit 允許它,但括號內的任何類型清單都會被忽略。

將 MCP 伺服器限定於 subagent

使用 mcpServers 欄位為 subagent 提供對主要對話中不可用的 MCP 伺服器的存取。此處定義的內聯伺服器在 subagent 啟動時連接,受 trust rule for the agent file's folder 約束,並在完成時斷開連接。字串參考共享父工作階段的連接。

清單中的每個條目要麼是內聯伺服器定義,要麼是參考工作階段中已配置的 MCP 伺服器的字串:

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

內聯定義使用與 .mcp.json 伺服器條目相同的架構,由伺服器名稱鍵入,並支援 stdio、http、sse 和 ws 類型。

若要將 MCP 伺服器保持在主要對話之外,並避免其工具描述在那裡消耗上下文,請在此處內聯定義它,而不是在 .mcp.json 中。Subagent 獲得工具;父對話不獲得。

Claude Code 從您專案的 .claude/agents/ 目錄中的代理檔案,或在 --add-dir 目錄的 .claude/agents/ 中載入內聯伺服器,僅在您 trust the folder the agent file came from 後。在 v2.1.238 之前,Claude Code 載入這些伺服器而不檢查信任。

  • 不計算的信任:父資料夾的信任,以及 -p 或 SDK 工作階段為 hooks in settings files 獲得的自動信任
  • 直到那時:Claude Code 跳過該代理檔案中的每個內聯伺服器,並將 ~/.claude.json 的確切 projects["<path>"].hasTrustDialogAccepted 鍵寫入除錯日誌
  • --add-dir 目錄:您受信任工作區儲存庫外的目錄需要其自己的信任條目,因為其 .claude/agents/ 檔案不繼承您工作區的信任

Claude Code 載入兩種伺服器而不檢查代理檔案來自的資料夾的信任:

  • 參考您已配置的伺服器的名稱
  • 來自 ~/.claude/agents/ 中代理檔案的內聯伺服器,在您使用 --agents 或 SDK agents 選項傳遞的伺服器中,或受管設定提供的伺服器中

自 v2.1.153 起,適用於主工作階段的 MCP 限制也涵蓋在 subagent frontmatter 中宣告的伺服器:

當其中之一阻止伺服器時,Claude Code 會跳過它並顯示警告,命名被阻止的伺服器。

受管設定限制適用於每個 subagent,無論其如何定義。--strict-mcp-config 不會過濾您透過 --agents 或 SDK agents 選項內聯傳遞的伺服器,因為這些是明確的呼叫者輸入。

權限模式

設定 permissionMode 以選擇 subagent 執行的權限模式。使用模式的配置值,因此手動模式是 default。如果您不設定它,subagent 繼承主要對話的模式,該模式在 Pro、Max 和 Team 計畫上開始為 auto mode,除非您的設定或您的組織改變它。

主要對話的權限模式決定 Claude Code 是否使用您設定的值:

  • 當主要對話在 bypassPermissions、acceptEdits 或 auto mode 時,subagent 執行在該相同模式中,Claude Code 忽略您設定的 permissionMode。在自動模式下,分類器使用主要對話的阻止和允許規則評估 subagent 的工具呼叫。
  • 當主要對話在 default、dontAsk 或 plan 模式時,subagent 執行在您設定的權限模式中,除了 bypassPermissions。宣告 bypassPermissions 的 subagent 改為保持主要對話的模式。bypassPermissions 例外需要 Claude Code v2.1.267 或更高版本。

permissionMode 接受這些值,以及 manual 作為 default 的別名:

Mode Behavior
default 手動模式:提示權限
acceptEdits 自動接受檔案編輯和工作目錄或 additionalDirectories 中路徑的常見檔案系統命令
auto Auto mode:背景分類器審查命令和受保護目錄寫入
dontAsk 自動拒絕權限提示。明確允許的工具仍然工作;AskUserQuestion、標記為 requiresUserInteraction 的 MCP 工具,以及您的組織設定為 ask 的連接器工具(在該設定到達 Claude Code 的工作階段中)會被拒絕,即使您已允許它們
bypassPermissions Skip permission prompts。Subagent 僅在主要對話也處於此模式時才在此模式中執行
plan Plan mode(唯讀探索)

將技能預載入 subagents

使用 skills 欄位在啟動時將技能內容注入到 subagent 的上下文中。這為 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.

每個列出的技能的完整內容被注入到 subagent 的上下文中。此欄位控制哪些技能被預載入,而不是 subagent 可以存取哪些技能:沒有它,subagent 仍然可以在執行期間透過 Skill 工具發現和呼叫專案、使用者和外掛程式技能。若要防止 subagent 完全呼叫技能,請從 tools 清單中省略 Skill 或將其新增到 disallowedTools。

您無法預載入設定 disable-model-invocation: true 的技能,因為預載入來自 Claude 可以呼叫的相同技能集。這包括捆綁的 /verify 技能:只有您可以執行它,因此它也無法被預載入。

如果列出的技能遺失或已停用,例如由您的組織政策,Claude Code 會跳過它並將警告記錄到除錯日誌。

啟用持久記憶

memory 欄位為 subagent 提供一個在對話之間存活的持久目錄。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.

根據記憶應該應用的廣泛程度選擇範圍:

Scope Location 使用時機
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 的知識是特定於專案的,但不應簽入版本控制

Subagent 記憶是 auto memory 的一部分:如果您關閉自動記憶,使用 autoMemoryEnabled 設定或 CLAUDE_CODE_DISABLE_AUTO_MEMORY,memory 欄位沒有效果,subagent 啟動時沒有記憶說明或下面描述的記憶工具存取。

當記憶啟用時:

  • Subagent 的系統提示包括讀取和寫入記憶目錄的說明。
  • Subagent 的系統提示還包括記憶目錄中 MEMORY.md 的前 200 行或 25KB(以先到者為準),以及如果超過該限制則策劃 MEMORY.md 的說明。
  • Read、Write 和 Edit 工具會自動啟用,以便 subagent 可以管理其記憶檔案。
持久記憶提示
  • project 是建議的預設範圍。它使 subagent 知識可透過版本控制共享。

  • 要求 subagent 在開始工作前查閱其記憶:"Review this PR, and check your memory for patterns you've seen before."

  • 要求 subagent 在完成任務後更新其記憶:"Now that you're done, save what you learned to your memory." 隨著時間的推移,這會建立一個知識庫,使 subagent 更有效。

  • 直接在 subagent 的 markdown 檔案中包括記憶說明,以便它主動維護自己的知識庫:

    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.
    

使用 hooks 的條件規則

為了更動態地控制工具使用,請使用 PreToolUse hooks 在執行前驗證操作。當您需要允許工具的某些操作同時阻止其他操作時,這很有用。

此範例建立一個只允許唯讀資料庫查詢的 subagent。PreToolUse hook 在每個 Bash 命令執行前執行 command 中指定的指令碼:

---
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 透過 stdin 將 hook 輸入作為 JSON 傳遞 給 hook 命令。驗證指令碼讀取此 JSON,提取 Bash 命令,並 以代碼 2 退出 以阻止寫入操作:

#!/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

在 macOS 和 Linux 上,使指令碼可執行,否則 hook 失敗而不是阻止任何內容:

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

若要測試規則,要求 subagent 執行 UPDATE 陳述式:指令碼以代碼 2 退出,Claude Code 阻止命令,subagent 看到 Blocked: Only SELECT queries are allowed 訊息。

請參閱 Hook input 以了解完整的輸入架構,以及 exit codes 以了解退出代碼如何影響行為。在 Windows 上,在 PowerShell 中編寫 hook 指令碼,並在 hook 條目中新增 shell: powershell,如 running hooks in PowerShell 所示。

禁用特定 subagents

您可以透過將 subagents 新增到您的 settings 中的 deny 陣列來防止 Claude 使用特定 subagents。使用格式 Agent(subagent-name),其中 subagent-name 與 subagent 的 name 欄位相符。

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

這適用於內建和自訂 subagents。您也可以使用 --disallowedTools CLI 標誌:

claude --disallowedTools "Agent(Explore)"

請參閱 Permissions documentation 以了解有關權限規則的更多詳細資訊。

為 subagents 定義 hooks

Subagents 可以定義在 subagent 生命週期期間執行的 hooks。有兩種方式來配置 hooks:

  • 在 subagent 的 frontmatter 中:定義只在該 subagent 活動時執行的 hooks
  • 在 settings.json 中:定義在 subagents 啟動或停止時在主工作階段中執行的 hooks。工具事件(例如 PreToolUse 和 PostToolUse)對 subagent 的工具呼叫的觸發方式與在主要對話中相同,SubagentStart 和 SubagentStop 在 subagent 啟動或完成時觸發

來自 settings files、managed policy settings 和 plugins 的 Hooks 都適用於 subagents 內,因此 settings.json 中的 PreToolUse hook 也在 subagent 使用的每個工具之前執行。

Subagent frontmatter 中的 Hooks

直接在 subagent 的 markdown 檔案中定義 hooks。這些 hooks 只在該特定 subagent 活動時執行,並在完成時清理。

若要讓專案層級 subagent 的 frontmatter hooks 執行,請接受包含代理檔案的資料夾的 workspace trust dialog。來自 ~/.claude/agents/ 中使用者層級 subagents 的 Hooks 以及來自您使用 --agents 傳遞的定義的 Hooks,無需此步驟即可執行。如果您使用 --add-dir 從您受信任工作區儲存庫外新增資料夾,單獨信任該資料夾:其 .claude/agents/ hooks 不繼承工作區的授予。

直到您信任資料夾,subagent 仍然執行,但 Claude Code 跳過其 frontmatter hooks 並將錯誤記錄到除錯日誌,解釋如何信任資料夾。這是比設定檔案中 hooks 的規則更嚴格的規則:信任父資料夾不夠,-p 工作階段不計為受信任。What runs before you trust a folder 比較兩者。在 v2.1.218 之前,frontmatter hooks 可以從您未信任的資料夾執行,包括在非互動工作階段中。

支援所有 hook events。subagents 最常見的事件是:

Event Matcher input 何時觸發
PreToolUse Tool name 在 subagent 使用工具之前
PostToolUse Tool name 在 subagent 使用工具之後
Stop (none) 當 subagent 完成時(在執行時轉換為 SubagentStop)

此範例使用 PreToolUse hook 驗證 Bash 命令,並在檔案編輯後使用 PostToolUse 執行 linter:

---
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 呼叫時,frontmatter 中的 Stop hooks 會自動轉換為 SubagentStop 事件。

用於 subagent 事件的專案層級 hooks

在 settings.json 中配置 hooks,以回應主工作階段中的 subagent 生命週期事件。

Event Matcher input 何時觸發
SubagentStart Agent type name 當 subagent 開始執行時
SubagentStop Agent type name 當 subagent 完成時

兩個事件都支援匹配器以按名稱針對特定代理類型。匹配器值是專案層級和使用者層級 subagents 的代理 frontmatter name,或 plugin subagents 的外掛程式範圍識別碼,例如 my-plugin:db-agent。範圍名稱包含冒號,因此它被評估為 unanchored regular expression;使用 ^ 和 $ 錨定它,如 ^my-plugin:db-agent$,以僅匹配該代理。

此範例僅在 db-agent subagent 啟動時執行設定指令碼,並在任何 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" }
        ]
      }
    ]
  }
}

連字號匹配器(如 db-agent)在 Claude Code v2.1.195 或更高版本上精確匹配。在較早的版本上,它被評估為 unanchored regular expression,也會針對任何包含它的代理類型觸發,例如 prod-db-agent;在這些版本上使用 ^db-agent$ 錨定它。

請參閱 Hooks 以了解完整的 hook 配置格式。

使用 subagents

理解自動委派

Claude 根據您請求中的任務描述、subagent 配置中的 description 欄位和目前上下文自動委派任務。為了鼓勵主動委派,在 subagent 的 description 欄位中包括「use proactively」之類的短語。

保持描述簡潔:當您的 subagents 的合併描述超過 15,000 個 token 限制 時,Claude Code 會顯示啟動警告,但仍會載入每個 subagent。

明確呼叫 subagents

當自動委派不夠時,您可以自己要求 subagent。三種模式從一次性建議升級到工作階段範圍的預設:

  • 自然語言:在提示中命名 subagent;Claude 決定是否委派
  • @-mention:保證 subagent 為一個任務執行
  • 工作階段範圍:整個工作階段使用該 subagent 的系統提示、工具限制和模型,透過 --agent 標誌或 agent 設定

對於自然語言,沒有特殊語法。命名 subagent,Claude 通常會委派:

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

@-mention subagent。 輸入 @ 並從預輸入中選擇 subagent,就像您 @-mention 檔案一樣。這確保該特定 subagent 執行,而不是將選擇留給 Claude:

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

您的完整訊息仍然會傳送給 Claude,它根據您要求的內容為 subagent 編寫任務提示。@-mention 控制 Claude 呼叫哪個 subagent,而不是它接收什麼提示。

由啟用的 plugin 提供的 Subagents 在預輸入中顯示為其限定名稱,例如 my-plugin:code-reviewer 或 my-plugin:review:security(當 plugin 將 agents 組織到子資料夾 時)。名為背景 subagents 目前在工作階段中執行也出現在預輸入中,在名稱旁邊顯示其狀態。

您也可以手動輸入提及而不使用選擇器:@agent-<name> 用於本地 subagents,或 @agent- 後跟外掛程式 subagents 的限定名稱,例如 @agent-my-plugin:code-reviewer。當您輸入此形式時,預輸入會顯示檔案符合而不是代理。代理提及在您提交時仍會解析。

將整個工作階段作為 subagent 執行。 傳遞 --agent <name> 以啟動一個工作階段,其中主執行緒本身採用該 subagent 的系統提示、工具限制和模型:

claude --agent code-reviewer

Subagent 的系統提示完全替換預設 Claude Code 系統提示,就像 --system-prompt 一樣。CLAUDE.md 檔案和專案記憶仍然透過正常訊息流載入。代理名稱在啟動標題中顯示為 @<name>,以便您可以確認它是活動的。

這適用於內建和自訂 subagents,選擇在您恢復工作階段時持續:Claude Code 會恢復代理的工具限制和模型以及對話。如果代理在您恢復時不再存在,工作階段會繼續使用預設工具,並顯示 警告命名代理。對於任一情況下的系統提示,請參閱 已恢復對話中的系統提示標誌。

對於外掛程式提供的 subagent,您可以只傳遞代理名稱,Claude Code 會找到它:

claude --agent security-reviewer

如果多個外掛程式提供具有相同名稱的代理,傳遞限定名稱以消除歧義:

claude --agent my-plugin:security-reviewer

如果外掛程式將代理放在其 agents/ 目錄的子資料夾中,請在限定名稱中包括子資料夾,例如 claude --agent my-plugin:review:security。

若要使其成為專案中每個工作階段的預設值,請在 .claude/settings.json 中設定 agent:

{
  "agent": "code-reviewer"
}

如果兩者都存在,CLI 標誌會覆蓋設定。

在前景或背景中執行 subagents

Subagents 可以在前景或背景中執行:

  • 前景 subagents 阻止主要對話直到完成。權限提示會在出現時傳遞給您。
  • 背景 subagents 在您繼續工作時並行執行。當背景 subagent 到達需要權限的工具呼叫時,Claude Code 會在您的主要工作階段中出現提示,並命名要求的 subagent。批准以讓 subagent 繼續,或按 Esc 拒絕該單一工具呼叫而不停止 subagent。在 v2.1.186 之前,背景 subagents 自動拒絕任何會提示的工具呼叫。

對於 Claude 使用 Agent 工具產生的每個 subagent,Claude Code 會從適用的第一個情況中選擇前景或背景:

  • 如果進行中的 agent team 隊友產生了 subagent,Claude Code 會在前景中執行它。當隊友設定 background: true 時,Claude Code 會拒絕並出現錯誤以產生隊友的 subagent。當 fork 模式 關閉且您未 關閉背景任務 時,Claude Code 也會在隊友設定 run_in_background: true 時拒絕並出現錯誤。
  • 如果您將 CLAUDE_CODE_DISABLE_BACKGROUND_TASKS 設定為 1,Claude Code 會在前景中執行 subagent,在每種工作階段中以及無論 fork 模式是否開啟。
  • 當 fork 模式 開啟時(在互動式工作階段中預設開啟),Claude Code 會在背景中執行 subagent,fork 和非 fork subagents 都是如此,Claude 無法要求前景。
  • 當 fork 模式關閉時,Claude 預設在背景中執行 subagent,在需要結果才能繼續時在前景中執行。Fork 模式在 非互動模式 中使用 -p 和在 Agent SDK 中關閉,除非您開啟它。若要在 Claude 需要結果時將特定 subagent 保持在背景中,請將其 frontmatter background 欄位設定為 true。

對於具有 context: fork 的技能,Claude Code 會遵循 在 subagent 中執行技能 中的規則,無論 fork 模式是否開啟。

背景 subagents 執行時使用的 內建工具集 比前景 subagents 更小,除了對話 forks 和 已恢復 的前景 subagents。

背景 subagents 在您的主要工作階段中出現每個權限提示。當您使用持續超過該單一工具呼叫的選擇(例如持續整個工作階段的授予)回答其中一個提示時,Claude Code 會將您的答案應用於整個工作階段,包括您的主要對話。

背景 subagent 可以留下背景 Bash 或 PowerShell 命令 在其回合結束後執行。當該命令結束時,Claude Code 會向 subagent 發送通知。

背景 subagent 的結果在稍後的回合中作為完成通知到達 Claude。Claude 在報告 subagent 的結果之前等待該通知,如果您先詢問進度,它會報告 subagent 仍在執行。在 v2.1.211 之前,Claude 有時會報告尚未完成的背景 subagent 的結果。

您也可以自己引導這個:

  • 當 fork 模式關閉時,要求 Claude 在背景或前景中執行任務
  • 按 Ctrl+B 將執行中的任務放在背景中

Claude Code 會根據 subagent 如何結束,以兩種方式之一清除提示輸入下方 subagent 面板中背景 subagent 的列:

  • 當 subagent 成功完成時,Claude Code 會立即移除其列,除了在 螢幕閱讀器模式 中,在頁腳中顯示 /tasks to see subagents 30 秒。在這 30 秒內,執行 /tasks 並在 subagent 上按 Enter 以開啟其文字。在 v2.1.232 之前,Claude Code 在 subagent 完成後保持列 30 秒,與失敗的相同,並顯示無頁腳提示。
  • 當 subagent 失敗或您停止它時,Claude Code 會保持其列 30 秒。若要更快清除列,請選擇它並按 x。

完成的背景 subagent 保持列在 /tasks 中,標記為完成並排序在執行中的工作下方,與頁腳提示相同的 30 秒。其詳細檢視在 subagent 完成時保持開啟。失敗或您停止的 Subagents 會離開列表。在 v2.1.208 之前,完成的 subagent 在完成時立即離開列表,其詳細檢視關閉。

Subagent 名稱

Claude 可以透過在 Agent 工具呼叫上傳遞 name 參數來給 subagent 命名,並可能自行執行此操作,而不先詢問您。該名稱使 subagent 可定址:Claude 可以在完成後 按名稱訊息或恢復它。

在啟用 agent teams 的互動式工作階段中,Claude 從主要對話產生的具有 name 的 subagent 會作為隊友啟動,除非呼叫是 fork 或在呼叫本身上傳遞 isolation。subagent 的 frontmatter 中的 isolation 值不會阻止它,隊友然後在主要工作階段的工作目錄中執行。請參閱 Claude 如何啟動 agent teams。

Subagents 中的 API 錯誤

當某些東西 在中途切斷 subagent 的回應,且部分回應包含文字但沒有工具呼叫時,Claude Code 會提示 subagent 繼續而不是結束執行。這也發生在互動式工作階段中。執行僅在這些延續用完時才在錯誤上結束。

自 v2.1.199 起,subagent 的執行因 API 錯誤(例如使用限制或重複的伺服器錯誤)而結束時,會將該失敗報告回 Claude,而不是將錯誤文字作為 subagent 的發現返回。Claude 接收的內容取決於 subagent 執行的位置:

  • 前景:如果速率限制、過載或伺服器錯誤切斷已經產生文字輸出的 subagent,Agent 工具會返回該部分輸出,並附註 subagent 被切斷且未完成其任務。未產生任何內容或其唯一輸出為工具呼叫的 subagent 會失敗,並顯示 Agent terminated early due to an API error,後跟錯誤詳細資訊。在 v2.1.199 中,切斷工具呼叫專用形狀的速率限制、過載或伺服器錯誤返回了只包含切斷注記的空部分結果。
  • 背景:subagent 被標記為失敗,Claude 在其結束時接收的訊息命名 API 錯誤並包括 subagent 的最後輸出,所以部分工作不會丟失。

當您配置 後備模型鏈 且 subagent 遇到鏈涵蓋的失敗(例如其模型不可用)時,Claude Code 會將 subagent 切換到鏈中接受請求的第一個模型。Subagent 會繼續工作而不是在錯誤上結束。

一旦基礎 API 錯誤清除,要求 Claude 重試任務或 恢復 subagent。

Subagent 輸出掃描

Claude Code 在 Claude 讀取 subagent 的最終報告之前掃描它。Subagent 可能已讀取您從未審查過的檔案、網頁或命令輸出,這些來源的文字可能包含針對主要對話的指令。掃描永遠不會移除或改寫任何內容;它會進行您可能在報告中注意到的兩種更改:

  • 反斜線插入:掃描會在模仿 Claude Code 自己輸出的文字中插入反斜線,例如 <system-reminder> 標籤或以 Human: 或 Assistant: 開頭的行,以便模仿讀作普通文字而不是被誤認為是對話的一部分。
  • 標記行:當報告模仿 <system-reminder> 之類的標籤或提及 bypassPermissions 或 --dangerously-skip-permissions 之類的權限設定時,掃描會前置以 [harness: subagent output matched instruction-shaped pattern(s): 開頭的行。權限設定提及會獲得標記行,但文字本身保持原樣。

掃描不會判斷內容是否惡意,也不會改變報告中的指令可以做什麼:報告導致 Claude 進行的工具呼叫仍然會通過工作階段的 權限檢查 和 沙箱化。它不是 限制 subagent 可以到達的內容 的替代品。

常見模式

隔離高容量操作

subagents 最有效的用途之一是隔離產生大量輸出的操作。執行測試、獲取文件或處理日誌檔案可能會消耗大量上下文。透過將這些委派給 subagent,詳細輸出保留在 subagent 的上下文中,而只有相關摘要返回到主要對話。

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

每個 subagent 獨立探索其領域,然後 Claude 綜合發現。當研究路徑彼此不相依時,這效果最好。

對於需要持續並行執行或不適合一個上下文視窗的工作,請在 個別工作階段 中執行它,並讓 Claude 在它們之間傳遞發現。

鏈接 subagents

對於多步驟工作流程,要求 Claude 按順序使用 subagents。每個 subagent 完成其任務並將結果返回給 Claude,然後將相關上下文傳遞給下一個 subagent。

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

在 subagents 和主要對話之間選擇

在以下情況下使用 主要對話:

  • 任務需要頻繁的來回或反覆改進
  • 多個階段共享重要上下文,例如規劃、實現和測試
  • 您正在進行快速、有針對性的更改
  • 延遲很重要。不是 fork 的 subagent 從頭開始,可能需要時間收集上下文

在以下情況下使用 subagents:

  • 任務產生您不需要在主要上下文中的詳細輸出
  • 您想強制執行特定的工具限制或權限
  • 工作是自包含的,可以返回摘要

當您想要可重複使用的提示或在主要對話上下文中執行的工作流程而不是隔離的 subagent 上下文時,請改為考慮 Skills。

對於關於對話中已有內容的問題,請使用 /btw 而不是 subagent。它看到您的完整上下文,但沒有工具存取,答案不會新增到歷史記錄。

讓 subagents 產生自己的 subagents

預設情況下,subagent 可以產生自己的 subagents,最多在主要對話下方三層。在深度限制處,Claude Code 會從除 fork 外的每個 subagent 中扣留 Agent 工具,所以限制處的 subagent 會自行執行委派的工作並返回一個摘要。fork 在限制處保持其繼承的工具列表中的 Agent,但工具會返回錯誤而不是產生。

嵌套 subagents 適合委派的任務本身分裂成並行子任務,例如審查者 subagent 為每個發現分派驗證者,所以中間輸出永遠不會到達主要對話。只有頂級 subagent 的摘要返回給您。

若要改變限制,請將 CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH 設定為您想要在主要對話下方的 subagent 層數。例如,settings.json 中的此項目將嵌套限制為兩層:

{
  "env": {
    "CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "2"
  }
}

使用此值,您的 subagents 可以委派給自己的第二層,該第二層無法進一步委派。設定 1 以關閉嵌套。

嵌套 subagent 的配置方式與頂級 subagent 相同,並從相同的 scopes 解析。若要防止一個 subagent 在嵌套開啟時產生,例如應保持唯讀的審查者,請從其 tools 列表中省略 Agent 或將其新增到 disallowedTools。

Claude Code 在提示輸入下方的 subagent 面板中將嵌套 subagents 顯示為樹,並用 (+N) 計數標記面板中仍有後代的每一列。打開一列以查看該 subagent 的同級和直接子代,以及返回到 main 的路徑。

並行 subagent 限制

兩個限制控制 subagent 使用,每個都有自己的變數:這個限制阻止 Claude 在太多執行時產生更多 subagents,深度限制 限制 subagents 嵌套的深度。對於 Claude 在工作階段中可以產生的 subagents 總數沒有限制。

預設情況下,當 20 個 subagents 在工作階段中執行時,使用 Agent 工具產生另一個會失敗,並顯示 Concurrent subagent limit reached,錯誤告訴 Claude 不要重試。當執行計數降至限制以下時,產生再次成功。若要改變限制,請將 CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS 設定為任何正整數。啟用 ultracode 的工作階段被豁免:限制在那裡不被強制執行。需要 Claude Code v2.1.217 或更新版本。

限制僅阻止 Claude 使用 Agent 工具產生的 subagents,但其他執行佔用相同的插槽:

  • 您使用 /subtask 啟動的進行中 fork 在執行時佔用一個插槽,永遠不會被限制阻止。
  • 恢復已完成的 subagent 會佔用一個新插槽而不檢查限制,所以恢復可以將執行計數推過限制。

其他功能執行的代理,例如 workflow 代理和 agent team 隊友,遵循自己的限制。

管理 subagent 上下文

啟動時載入的內容

每個 subagent 都以新鮮、隔離的上下文視窗開始。它看不到您的對話歷史記錄、您已經呼叫的技能或 Claude 已經讀取的檔案。Claude 撰寫一條委派訊息來總結任務,subagent 從那裡開始工作。例外是 fork,它繼承父對話而不是從頭開始。

非 fork subagent 的初始上下文包含:

  • 系統提示:代理自己的提示加上 Claude Code 附加的環境詳細資訊,而不是 Claude Code 系統提示。自訂 subagents 在 markdown 正文 或 prompt 欄位中定義它們。內建代理有預定義的提示。
  • 任務訊息:Claude 在交接工作時編寫的委派提示。
  • CLAUDE.md 檔案:主要對話載入的 CLAUDE.md 層級 的每個級別,包括 ~/.claude/CLAUDE.md、專案規則、CLAUDE.local.md 和受管理的政策檔案。內建的 Explore 和 Plan 代理跳過這個。
  • Git 狀態:在父工作階段開始時拍攝的快照。當工作目錄不是 Git 儲存庫或當 includeGitInstructions 為 false 時不存在。Explore 和 Plan 無論如何都跳過它。
  • 預載入的技能:代理的 skills 欄位 中命名的任何技能的完整內容。內建代理不預載入技能。
  • 同級名單:系統提醒,列出 main 和工作階段中的每個其他命名代理,每個都是 SendMessage 的有效 to 值。需要 Claude Code v2.1.206 或更新版本。名單僅在 subagent 的工具包括 SendMessage 且至少有一個其他代理有名稱時出現,無論 Claude 在產生時命名它還是它作為 agent teams 隊友執行。它是在 subagent 啟動時拍攝的快照,所以稍後命名的代理不會出現。

Explore 和 Plan 是唯一省略 CLAUDE.md 和 git 狀態的 subagents。沒有 frontmatter 欄位或每個代理設定來改變哪些代理跳過它們。

主要對話使用完整 CLAUDE.md 上下文讀取 Explore 和 Plan 結果,所以大多數規則不需要到達 subagent 本身。如果規則必須,例如「忽略 vendor/ 目錄」,在您委派時給 Claude 的提示中重新陳述它。

某些主要對話狀態永遠不會到達非 fork subagent:

  • 輸出風格:subagent 執行自己的系統提示,所以您的 輸出風格 不會塑造其回應,除了在 fork 中。
  • 自動記憶:主要對話的 自動記憶 不會被載入。若要給 subagent 自己的持久記憶,請使用 memory 欄位。
  • 上下文視窗大小:subagent 的上下文視窗由其自己的模型調整大小,而不是父級的。委派給具有較小視窗的模型會給該 subagent 較小的視窗。

恢復 subagents

每個 subagent 呼叫都會建立一個新實例而不是繼續較早的實例。若要繼續現有 subagent 的工作而不是重新開始,請要求 Claude 恢復它。

恢復的 subagents 保留其完整對話歷史記錄,包括所有先前的工具呼叫、結果和推理。如果 subagent 產生了 自己的背景 subagents,該歷史記錄包括它執行時它們傳遞的結果。Subagent 從停止的地方精確繼續,而不是從頭開始。

  • 當 subagent 完成時,Claude 接收其代理 ID。
  • 內建的 Explore 和 Plan 代理是一次性的,不返回代理 ID,所以 Claude 無法恢復它們。當您需要繼續工作時,請使用 general-purpose 或自訂 subagent。
  • 當 subagent 在其 maxTurns 限制處停止時,Claude Code 會將返回的輸出標記為部分。對於返回代理 ID 的 subagents,Claude Code 也會在結果中注意 Claude 可以訊息 subagent 以從停止的地方繼續。

Claude 使用 SendMessage 工具,將代理的 ID 或名稱作為 to 欄位來恢復它。SendMessage 不需要啟用 agent teams;只有結構化的團隊協議訊息,例如 shutdown_request 和 plan_approval_response,才需要啟用。除了 subagents 和隊友,在啟用跨工作階段訊息的工作階段中,Claude 可以使用相同的工具訊息 您的其他 Claude Code 工作階段,在此機器上或 超越它。

若要恢復 subagent,請要求 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 使用 SendMessage 工具向已完成的 subagent 發送訊息時,subagent 在背景中恢復,無需新的 Agent 呼叫。同樣適用於 Claude 使用 TaskStop 工具停止的 subagent,一旦其停止的執行已退出。恢復的執行保持 subagent 首次執行時的工具集,並可以繼續讀取 原始執行預熱的提示快取。

具有 SendMessage 工具的 subagent 也可以發送該訊息。在互動式工作階段中,恢復的代理然後報告回恢復它的 subagent,而不是您的主要對話。該 subagent 在完成自己的工作之前等待結果。當 subagent 訊息它報告給的代理(例如自己的啟動器)時,Claude Code 會恢復該代理而不重定向其結果。

您自己停止的 subagent,使用 /tasks 中的 x 或 SDK stop_task 請求,不會自動恢復。如果 Claude 向它發送訊息,訊息會被拒絕,Claude 會被告知代理已被取消。

當 該 subagent 的列仍在 subagent 面板中 時,輸入到其文字中以自己恢復它。之後,來自 Claude 的訊息可以再次自動恢復它。需要 Claude Code v2.1.191 或更新版本。

恢復在相同 ID 下啟動代理的新執行,所以已經失敗或完成的 subagent 在任務列表和 Agent SDK 的任務事件中再次顯示為執行中。在 v2.1.205 之前,它在恢復的執行工作時保持顯示其較早的失敗或完成狀態。

自 v2.1.199 起,SendMessage 檢查名稱是否仍然指向它在對話中較早時到達的同一代理。如果較新的代理已取得該名稱,例如重新產生的背景代理重複使用了它,Claude Code 會拒絕發送,而不是將其傳遞給錯誤的代理,錯誤會報告該名稱現在到達的代理,以便 Claude 可以重新定位。若要在較早的代理仍在執行時到達它,Claude 會透過其產生結果中的代理 ID 來定址它。檢查的範圍是目前對話,並在 /clear 時重置。

自 v2.1.198 起,subagent 將來自啟動它的代理的訊息視為正常任務方向,包括中途任務課程更正,並在其自己的權限設定內對其進行操作。無論誰發送訊息,兩個限制仍然成立:來自任何代理的任何訊息都不計為您對待處理權限提示的批准,任何代理訊息都無法改變 subagent 的權限設定、CLAUDE.md 或配置。只有權限系統或您自己的訊息可以授予批准。

您也可以要求 Claude 提供代理 ID,如果您想明確參考它,或在 ~/.claude/projects/{project}/{sessionId}/subagents/ 的文字檔案中找到 ID。每個文字都儲存為 agent-{agentId}.jsonl。

Subagent 文字獨立於主要對話持續存在:

  • 主要對話壓縮:當主要對話壓縮時,subagent 文字不受影響。它們儲存在單獨的檔案中。
  • 工作階段持續性:Subagent 文字在其工作階段內持續存在。您可以透過恢復相同工作階段在重新啟動 Claude Code 後 恢復 subagent。
  • 自動清理:Claude Code 在 cleanupPeriodDays 保留期後刪除 subagent 文字,預設為 30 天,遵循 保留掃描規則。

自動壓縮

Subagents 支援使用與主要對話相同的邏輯進行自動壓縮。壓縮在相同條件下觸發,CLAUDE_AUTOCOMPACT_PCT_OVERRIDE 也適用於 subagents。請參閱 environment variables 以了解何時覆蓋生效。

壓縮事件記錄在 subagent 文字檔案中:

{
  "type": "system",
  "subtype": "compact_boundary",
  "compactMetadata": {
    "trigger": "auto",
    "preTokens": 167189
  }
}

preTokens 值顯示壓縮發生前使用了多少個 tokens。

Fork 目前的對話

Fork 是一個 subagent,它繼承到目前為止的整個對話,而不是從頭開始。這會放棄 subagents 否則提供的輸入隔離:fork 看到與主工作階段相同的系統提示、工具、模型和訊息歷史記錄,因此您可以將側面任務交給它,而無需重新解釋情況。Fork 自己的工具呼叫仍然保持在您的對話之外,只有其最終結果返回,因此您的主要上下文視窗保持乾淨。當任何其他 subagent 需要太多背景才能有用時,或當您想從相同的起點並行嘗試多種方法時,使用 fork。

Claude 透過 Agent 工具要求 fork subagent 類型來啟動 fork。您可以透過fork 模式控制是否可以啟動,預設在互動式工作階段中啟用。

您可以使用 /subtask 後跟任務自己啟動 fork,無論 fork 模式是否啟用。在 v2.1.161 到 v2.1.211 版本中,命令是 /fork。Claude Code 從任務的前幾個詞命名 fork。以下範例 forks 對話以在您在主工作階段中繼續實現時草擬測試案例:

/subtask draft unit tests for the parser changes so far

Fork 出現在提示下方的面板中,並在您繼續工作時在背景中執行。完成後,其結果作為訊息到達您的主要對話。下一部分涵蓋面板控制項,用於在 forks 執行時觀察和引導它們。

觀察和引導執行中的 forks

執行中的 forks 出現在提示輸入下方的面板中,主工作階段有一行,每個 fork 有一行。

當 fork 成功完成時,Claude Code 會移除其行。Claude Code 會保留失敗或您停止的 fork 的行 30 秒,與任何其他背景 subagent 相同。在 v2.1.232 之前,Claude Code 也會將完成的 fork 的行保留 30 秒。

使用這些鍵與面板互動:

Key Action
↑ / ↓ 在行之間移動
Enter 開啟選定 fork 的文字記錄並向其發送後續訊息
x 停止執行中的選定 fork,或如果不再執行則關閉其行。在主工作階段行或使用 Enter 開啟其文字記錄的 fork 行上,x 會改為輸入到提示中
Esc 將焦點返回到提示輸入

使用 fork 或 subagent 的文字記錄開啟時,後續訊息和 skills 會傳送到該代理,但內建命令仍在您的主要對話中執行。從 v2.1.199 開始,在該檢視中輸入 /model 或 /fast 會顯示通知,表示它會變更主要對話的模型或快速模式,而不是檢視的代理,而不是以無聲方式執行。

Forks 與其他 subagents 的區別

Fork 繼承主工作階段在產生時擁有的所有內容。任何其他 subagent 從其定義開始新鮮。

Fork 非 fork subagent
Context 完整對話歷史記錄 新鮮上下文,帶有您傳遞的提示
系統提示和工具 與主工作階段相同 來自 subagent 的定義檔,針對背景執行進行篩選
Model 與主工作階段相同 來自 subagent 的 model 欄位
Permissions 提示出現在您的終端中 Prompts surface in your main session 在背景中執行時
Prompt cache 與主工作階段共享 單獨的快取

因為 fork 的系統提示和工具定義與父級相同,其第一個請求重複使用父級的 prompt cache。這使得 forking 比為需要相同上下文的任務產生新 subagent 更便宜。

當 Claude 透過 Agent 工具產生 fork 時,它可以傳遞 isolation: "worktree",以便 fork 的檔案編輯被寫入單獨的 git worktree 而不是您的簽出。Fork 無法產生進一步的 forks。

開啟或關閉 fork 模式

Claude Code 在互動式工作階段中預設開啟 fork 模式,在非互動模式中預設關閉,使用 -p 和在 Agent SDK 中。互動式預設需要 Claude Code v2.1.232 或更新版本。在較早版本中,設定 CLAUDE_CODE_FORK_SUBAGENT 為 1 以開啟 fork 模式。

您可以從 Claude Code 如何處理 Agent 工具來判斷 fork 模式是否開啟:

  • Claude 可以透過要求 fork subagent 類型來產生 fork。當 Claude 不要求類型時,如果工作階段仍有該類型,它會取得通用 subagent。從定義產生的 subagents,例如 Explore,照常工作。
  • Claude Code 在背景中執行 Claude 產生的 subagents,forks 和非 fork subagents 都是如此,除了保持在前景的情況。Claude Code 也會移除 Agent 工具的 run_in_background 參數,因此 Claude 無法要求前景。

設定 CLAUDE_CODE_FORK_SUBAGENT 環境變數以覆蓋預設值:

  • 1 在非互動模式和 Agent SDK 中也開啟 fork 模式
  • 0 在每種工作階段中關閉 fork 模式

要保持 fork 模式開啟但停止 Claude 產生 forks,請使用 Agent(fork) 規則拒絕 fork subagent 類型。Claude Code 仍在背景中執行 Claude 產生的 subagents,除了相同的保持在前景的情況。

範例 subagents

這些範例展示了建立 subagents 的有效模式。將它們用作起點,或使用 Claude 生成自訂版本。

程式碼審查者

一個唯讀 subagent,審查程式碼而不修改它。此範例展示如何設計一個具有有限工具存取(無 Edit 和 Write)和詳細提示的專注 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。與程式碼審查者不同,這個包括 Edit,因為修復錯誤需要修改程式碼。提示提供了從診斷到驗證的清晰工作流程。

---
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。此範例展示如何為典型編碼任務之外的專門工作流程建立 subagents。它明確設定 model: sonnet 以進行更有能力的分析。

---
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。此範例展示如何在需要比 tools 欄位提供的更精細控制時使用 PreToolUse hooks。

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

Claude Code 透過 stdin 將 hook 輸入作為 JSON 傳遞 給 hook 命令。驗證指令碼讀取此 JSON,提取正在執行的命令,並根據 SQL 寫入操作清單檢查它。如果檢測到寫入操作,指令碼 以代碼 2 退出 以阻止執行並透過 stderr 向 Claude 返回錯誤訊息。

在專案中的任何位置建立驗證指令碼。路徑必須與 hook 配置中的 command 欄位相符:

#!/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

在 Windows 上,使用 PowerShell 編寫驗證指令碼,並將 shell: powershell 新增至 hook 項目。請參閱 在 PowerShell 中執行 hooks。

Hook 透過 stdin 接收 JSON,Bash 命令在 tool_input.command 中。退出代碼 2 阻止操作並將錯誤訊息反饋給 Claude。請參閱 Hooks 以了解退出代碼和 Hook input 以了解完整的輸入架構。

系統提示告訴 subagent 拒絕寫入請求,因此 hook 是一個後備:如果 subagent 嘗試寫入,Claude Code 會阻止命令,subagent 會看到 Blocked: Write operations not allowed. Use SELECT queries only. 訊息。

後續步驟

現在您理解了 subagents,請探索這些相關功能: