claude@cli:~/docs$ cat claude-code.md

Claude Code: Hooks 如何運作?

# Hooks 會在 Claude Code 工作流程的特定時間點執行確定性的 shell 指令。與提示 Claude 執行動作不同,hooks 無論模型行為如何都保證會執行。對於落實團隊標準與自動化重複性工作,hooks 不可或缺。請參閱決策框架中的「該用哪種 Hook 類型?」決策樹,其中涵蓋…

author: words: 5986 read_time: 55m updated: 2026-11-29 08:10

Part 3 of New to Claude Code

Hooks 會在 Claude Code 工作流程的特定時間點執行確定性的 shell 指令。與提示 Claude 執行動作不同,hooks 無論模型行為如何都保證會執行。對於落實團隊標準與自動化重複性工作,hooks 不可或缺。請參閱決策框架中的「該用哪種 Hook 類型?」決策樹,其中涵蓋…

最後更新: 2026-11-29 · 55 分鐘閱讀 · 5K+ words

$ less claude-code.md

Hooks 會在 Claude Code 工作流程的特定時間點執行確定性的 shell 指令。與提示 Claude 執行動作不同,hooks 無論模型行為如何都保證會執行。對於落實團隊標準與自動化重複性工作,hooks 不可或缺。請參閱決策框架中的「該用哪種 Hook 類型?」決策樹,其中涵蓋 command、prompt 與 agent 三種 hooks。

為什麼用 hooks 而不是提示詞:告訴 Claude「編輯檔案後一律執行 Prettier」有時會奏效。但 Claude 可能忘記、優先追求速度,或認定這次變更「太小」而略過。Hooks 則保證執行:每一次 Edit 或 Write 都會觸發您的格式化工具,每一次,毫無例外。就合規、安全與團隊標準而言,確定性勝過機率性。3

可用的事件

事件 時機 可否阻擋 用途
PreToolUse 工具執行前 可 驗證、記錄或阻擋操作
PostToolUse 工具完成後 否 格式化輸出、執行 linter、觸發建置
PostToolUseFailure 工具失敗後 否 記錄失敗、發送警示、提供修正回饋
PostToolBatch 一批平行工具呼叫完成後、下一次模型呼叫前 可 在模型呼叫之間為代理迴圈建立檢查點或中止3
UserPromptSubmit 使用者送出提示 可 加入脈絡、驗證輸入、注入資料
UserPromptExpansion 輸入的指令展開為提示 可 稽核或否決 skill/斜線指令的展開;stdout 會加入脈絡3
PreSkillShellCommand skill 或指令載入期間,在其內嵌的 ! shell 指令執行之前 可 記錄或拒絕注入的指令(PreToolUse hooks 永遠看不到這些指令):exit 2 或 permissionDecision: "deny" 會略過該指令,skill 仍會載入;它無法核准或變更指令。請同時比對 Bash 與 PowerShell,使用非 async 的 command、http 或 mcp_tool hook,並設定 onFailure: "block"(v2.1.332+;較舊的版本若在設定檔中發現此事件,會在啟動時開啟警告對話框)529
Notification 觸發警示 否 自訂通知處理
MessageDisplay 顯示助理訊息文字 否 透過 displayContent 轉換或隱藏螢幕上的文字——僅影響顯示,逐字稿不變(v2.1.152+)264
Stop Claude 完成回應 可 防止過早停止、強制執行完成條件。包含 last_assistant_message(v2.1.47+)
SubagentStart Subagent 啟動 否 記錄 agent 類型、透過 additionalContext 注入脈絡
SubagentStop Subagent 完成 可 防止 subagent 停止、強制執行品質關卡。包含 last_assistant_message(v2.1.47+)
TeammateIdle Agent 團隊成員閒置 可 在隊友停止前強制執行品質關卡(v2.1.33+)
TaskCreated 透過 TaskCreate 建立任務 可 強制執行任務命名與範圍規則;exit 2 會回復建立動作(v2.1.84+)。自 v2.1.268 起,任務工具僅在 Opus 4.7、Sonnet 4.6、Haiku 4.5 及更早的模型上預設開啟;在較新的模型上(背景與雲端工作階段除外),此事件只有在 CLAUDE_CODE_ENABLE_TODO_TOOLS=1 或 --allowedTools TaskCreate 將其開啟後才會觸發(v2.1.233 首先在較新模型上關閉了它們)129251213315
TaskCompleted 任務標記為完成 可 強制執行完成條件、執行測試(v2.1.33+)
SessionStart 工作階段開始 否 環境設定、載入脈絡、設定環境變數
SessionEnd 工作階段結束 否 清理、最終記錄
Setup --init-only,或搭配 -p 的 --init/--maintenance;一般啟動時絕不觸發 否 從 CI 或指令碼進行一次性環境設定(v2.1.10+)52316
InstructionsLoaded 載入 CLAUDE.md 或 .claude/rules/*.md 否 記錄載入了哪些指示檔案;此事件沒有輸出管道,因此無法封鎖或新增上下文(v2.1.69+)316
ConfigChange 工作階段中設定檔變更 可 稽核設定變更、強制執行安全政策(v2.1.49+)
DirectoryAdded 工作階段中註冊了新的工作目錄 否 回應 /add-dir 或 SDK 的 register_repo_root 控制請求——載入各儲存庫的脈絡、重新設定 linter 範圍、稽核範圍擴張(v2.1.219+)193
CwdChanged 工作目錄變更 否 重新載入 direnv 風格的環境(v2.1.83+)121
FileChanged 受監看的檔案在磁碟上變更 否 回應受監看檔案的變更:matcher 指名要監看的檔案,以管線符號分隔(例如 .envrc 與 .env),而 SessionStart、CwdChanged 或 FileChanged hook 可透過 watchPaths 加入更多檔案(v2.1.83+)121316
WorktreeCreate 正在建立 worktree 可 自訂 VCS 設定(取代預設的 git 行為)(v2.1.50+)
WorktreeRemove 由您的 WorktreeCreate hook 建立的 worktree 正在被移除 可 自訂 VCS 清理;若之後目錄仍然存在,任何非零的結束代碼都會讓移除失敗(v2.1.50+)316
PreCompact 脈絡壓縮前 可(v2.1.105+) 驗證、記錄、阻擋壓縮(exit 2 或 {"decision":"block"});自 v2.1.314 起輸出截斷於 10,000 個字元,因此過大的 hook 不會導致壓縮失敗或重複執行281
PostCompact 脈絡壓縮後 否 記錄、快取重用最佳化(v2.1.76+)116
Elicitation MCP 伺服器請求結構化輸入 可 攔截/覆寫 MCP 的 elicitation 對話框(v2.1.76+)116
ElicitationResult 使用者回應 MCP 的 elicitation 可 驗證/轉換 elicitation 的回應(v2.1.76+)116
StopFailure 回合因 API 錯誤結束(速率限制、驗證失敗) 否 錯誤警示、重試邏輯(v2.1.78+)118
PermissionRequest 工具呼叫需要權限決定 僅限 JSON 自訂核准邏輯;不採用 exit 2,因此請以 hookSpecificOutput.decision.behavior: "deny" 拒絕316
PermissionDenied Auto mode 拒絕工具呼叫 否 記錄拒絕事件;回傳 hookSpecificOutput.retry: true 告知模型可以重試(分類器未給出判定時會被忽略)(v2.1.89+)125316
PreModelSwitch 在您或用戶端請求的模型切換之前:/model 與各選擇器、/config 的 Model 設定、會變更模型的快速模式切換、SDK 或 Remote Control 的 set_model 可 阻擋、確認或為模型切換計價。matcher 比對的是由 to_model 推導出的標準名稱(別名、帶日期的 ID 與 Bedrock ID 都會解析為該名稱;精確名稱、以豎線分隔的清單與正規表示式皆可使用);輸入包含 from_model/to_model 以及快取成本欄位(context_tokens、prompt_cache_warm、cache_ttl、estimated_cache_write_usd)。Exit 2 或 permissionDecision: "deny" 會取消切換,"ask" 會提示使用者,而 hook 在預設 30 秒逾時被取消時會阻擋切換。Claude Code 自行發起的切換不會執行此 hook(v2.1.251+)203205
PostModelSwitch 工作階段的模型變更後,包括 Claude Code 自行發起的變更:自動回退、opusplan 階段變更、恢復工作階段時還原的模型 否 針對特定模型的指引:exit 0 時的純文字 stdout(或 JSON 的 additionalContext)會在切換後的下一次請求中作為脈絡交付給 Claude。與 PreModelSwitch 相同的標準名稱 matcher 與輸入,另加 source 值 auto 與 resume;預設 30 秒逾時(v2.1.251+)203205

SessionStart 的 source 值。 SessionStart hook 的輸入包含 source 欄位,告訴您工作階段是如何開始的:"startup"、"resume"、"clear" 或 "compact"。截至 v2.1.214,以 fork 方式誕生的工作階段會回報 source: "fork" 而非 "resume",這是 v2.1.212 將 /fork 改為背景執行後,在 hook 端的對應變更。若 SessionStart hook 會依 source 分支處理(例如只在 "resume" 時重新注入脈絡),請更新其比對清單,將 "fork" 也納入。187 截至 v2.1.251,當 source 為 "resume" 或 "fork",且逐字稿中至少包含一則 Claude 先前的回應時,SessionStart hooks 還會收到四個恢復成本欄位:seconds_since_last_response、context_tokens(第一次請求作為提示重新送出的內容量)、prompt_cache_likely_expired(當最後一次回應早於工作階段的快取 TTL,或之後的壓縮取代了已快取的對話時為 true),以及 estimated_cache_write_usd。有了這些欄位,hook 就能在第一次請求前,回報恢復一段過時對話的成本。203205

Hook 設定

在設定檔(~/.claude/settings.json、.claude/settings.json、.claude/settings.local.json)、plugin 的 hooks/hooks.json,或 skill 與 subagent 的 frontmatter 中定義 hooks:316

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/validate-bash.sh"
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/inject-context.sh"
          }
        ]
      }
    ]
  }
}

比對器

matcher 欄位決定哪些工具會觸發 hook:502

  • {"matcher": "*"}:比對所有工具
  • {"matcher": "Bash"}:比對 Bash 工具
  • {"matcher": "Edit|Write"}:比對 Edit 或 Write
  • {"matcher": "mcp__github__.*"}:比對 github MCP 伺服器的所有工具
  • {"matcher": ""}:比對全部,等同於 "*" 或省略 matcher;不支援比對器的事件(例如 UserPromptSubmit)會忽略此欄位並一律觸發

使用 | 可同時比對多個工具(Edit|Write)。以逗號分隔的比對器(例如 Bash,PowerShell)也可使用(v2.1.191+)。175 只由字母、數字、_、-、空格、, 與 | 組成的比對器會以精確字串(或一組精確字串)比較,絕不會以子字串比對;其他任何形式都是未錨定的 JavaScript 正規表示式。(code-reviewer 這類帶連字號的名稱自 v2.1.195 起適用精確比對規則。)若要比對某個 MCP 伺服器的所有工具,必須加上 .*:mcp__github__.*、mcp__brave-search__.*。單獨的 mcp__github 不會比對到任何工具。176316

截至 v2.1.214,hook 的 if: 路徑條件以 cwd 為範圍。 影響權限允許規則的同一項單段範圍變更(請參閱權限規則語法)同樣適用於 hook 的 if: 條件:像 dir/** 這樣的條件現在只會比對 <cwd>/dir,而不是整個目錄樹中的每一個 dir/。若想恢復任意深度的比對,請寫成 **/dir/**。187 自 v2.1.314 起,諸如 Monitor(tail *) 的條件會比對 Monitor 工具的 shell 指令,方式與 Bash(tail *) 比對 Bash 的指令相同;比對 Bash 的 hooks 也會在這些指令上執行,可以在其中封鎖或詢問,但無法核准或改寫。281

Hook 輸入/輸出協定

Hooks 透過 stdin 接收 JSON:

{
  "session_id": "abc-123",
  "transcript_path": "/Users/you/.claude/projects/my-project/abc-123.jsonl",
  "cwd": "/Users/you/my-project",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite"
  },
  "tool_use_id": "toolu_01ABC123"
}

每個事件都帶有 session_id、transcript_path、cwd 與 hook_event_name;大多數事件也帶有 permission_mode。其他欄位則依事件而定。316

Hook 事件資訊擴充(v2.1.69+): 當 hook 事件由子代理程式或 --agent 工作階段觸發時,所有事件現在都會包含 agent_id 與 agent_type 欄位;狀態列 hook 指令中則多了一個 worktree 欄位。108

Stop/SubagentStop hooks(v2.1.47+) 會額外收到 last_assistant_message 欄位,內含 Claude 的最終回應文字,因此 hooks 無需解析逐字稿檔案即可檢查輸出:

{
  "session_id": "abc-123",
  "last_assistant_message": "I've completed the refactoring. Here's what changed..."
}

不封鎖的柔性回饋(v2.1.163+): Stop 與 SubagentStop hooks 可以在其 JSON 輸出中回傳 hookSpecificOutput.additionalContext,將回饋交給 Claude 並讓該回合繼續進行,而不會把回應標記為 hook 錯誤。另一個手段是 exit-2 封鎖,它會被視為錯誤,並計入連續封鎖上限;additionalContext 則是一條引導管道,用於傳達「你漏了這些,請繼續」之類的指引,而不會與迴圈相互牴觸。261

結束代碼決定行為: - 0:成功:Claude Code 會套用 hook 印出的所有 JSON 輸出欄位,除非這些欄位封鎖或拒絕該動作,否則動作會繼續進行。只有在 hook 印出單一 JSON 物件、且周圍除空白字元外別無其他內容時,stdout 才會被視為 JSON 輸出;其他任何內容都會被當作純文字或解析失敗。在 UserPromptSubmit、UserPromptExpansion、SessionStart 與 PostModelSwitch 事件上,純文字 stdout 會被加入為 Claude 可以看見並據以行動的上下文;在 PreCompact 上,stdout 則會成為壓縮摘要的指示。以 0 結束的 hook,其 stderr 絕不會讓 Claude 看到。274316 - 2:在可封鎖的事件上為封鎖性錯誤:操作停止,stderr 會回饋給 Claude。在無法封鎖的事件上,效果各不相同:PostToolUse 與 PostToolUseFailure 仍會將 stderr 顯示給 Claude,有幾個事件只會顯示給您,而 PermissionRequest、Setup、Notification 與 PermissionDenied 等事件則會忽略 exit 2(請參閱上方的「可否阻擋」欄)。316 - 1、3 等:非封鎖性錯誤:操作繼續進行,除非該 hook 屬於失敗即封鎖動作的類型,例如 onFailure 設為 "block" 的 hook。當 stdout 為純文字或空白時,<hook name> hook error 通知(出現在 PreToolUse 等事件上)會顯示 Failed with non-blocking status code:(以非封鎖狀態碼失敗:),後面接著 hook 的 stderr,若通知將內容截斷,其餘部分可在除錯日誌中找到;通過驗證的 JSON 仍會被套用,而結束代碼則被忽略(對於失敗即封鎖動作的 hook,該次執行會改計為一次失敗)。274

失敗即封鎖(v2.1.295+): 預設情況下,hook 若無法啟動、逾時、以 0 或 2 以外的代碼結束、收到 HTTP 錯誤、其 MCP 伺服器斷線或其 MCP 工具回傳錯誤,或印出未通過 JSON 驗證的輸出,都屬於非封鎖性錯誤,因此路徑打錯的政策 hook 會讓所有操作一律放行。在 command 或 http hook 上(自 v2.1.328 起也包括 mcp_tool hook)設定 "onFailure": "block",上述每一種失敗就會等同於該事件上的結束代碼 2:PreToolUse 失敗會封鎖工具呼叫,UserPromptSubmit 失敗會封鎖提示,而在 PermissionRequest 上則會拒絕該請求。錯誤行會顯示 failed; blocking because onFailure is "block"(逾時後則為 timed out),後面接著 hook 自身的輸出。以結束代碼 1 結束、卻附帶允許該動作之 JSON 的 command hook,仍會被計為失敗;若要回傳 JSON 決定,請以 0 結束。此欄位在 Stop、SubagentStop、TaskCompleted 與 TeammateIdle hooks 上會被忽略(這些事件上的結束代碼 2 會讓 Claude 回頭繼續工作),在 async 或 asyncRewake command hooks 上也會被忽略。另一個值為 "continue"。未設定此欄位時,失敗屬於非封鎖性錯誤,但有一個例外:在沒有 Git Bash 的 Windows 上,shell 形式的 PreToolUse、PermissionRequest 或 PreSkillShellCommand command hook 若失敗,可能會封鎖該動作,而在該 hook 上設定 "onFailure": "continue" 可讓呼叫繼續進行。235237274529

Skill 的 shell 指令有了專屬事件(v2.1.332)。 skill 或指令可以在載入期間執行 shell 指令(即內嵌 Bash 執行中所示的 ! 行),而 PreToolUse hooks 不會對這些指令觸發,PreSkillShellCommand 則會。其輸入包含 tool_name(Bash 或 PowerShell)、tool_input.command、command_name(正在載入的 skill 或指令)、command_source 與 invoked_by。此 hook 會在對注入指令進行權限檢查之後執行,因此看到的是通過檢查的指令;在 bypassPermissions 模式下也會執行。請在設定檔或 plugin 中定義它:skill 在工作階段中首次載入時,其注入的指令執行時並不會套用該 skill 自身 frontmatter 中的 hooks。在 auto mode 下,需要核准的指令不會在 skill 載入期間執行;Claude 之後可以將其作為工具呼叫執行,這會觸發 PreToolUse,因此請在兩個事件上都保留封鎖指令碼。此事件上的 prompt 或 agent hook 無法執行,Claude Code 會封鎖該 hook 所比對到的每個指令。527529

{
  "hooks": {
    "PreSkillShellCommand": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh", "args": [], "onFailure": "block" }
        ]
      }
    ]
  }
}

此指令碼就是 hooks 參考文件在「Hook 的解析方式」一節中建立的那一個,參考文件也說明可在此事件上重複使用。請將其儲存為專案中的 .claude/hooks/block-rm.sh,並以 chmod +x .claude/hooks/block-rm.sh 設為可執行;您的 PATH 中需要有 jq:

#!/bin/bash
# .claude/hooks/block-rm.sh
COMMAND=$(jq -r '.tool_input.command')

if echo "$COMMAND" | grep -q 'rm -rf'; then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Destructive command blocked by hook"
    }
  }'
else
  exit 0  # no decision; normal permission flow applies
fi

同一個檔案可用於兩個事件:當同一個指令碼在兩個事件上執行時,請將 hookEventName 保留為 PreToolUse;以結束代碼 2 結束的指令碼在任一事件上也都會封鎖。在 PreSkillShellCommand 上,hook 可以封鎖指令,但無法核准或變更指令。529

若需進階控制,hook 可在 stdout 印出 JSON 並以 0 結束。對於非 async 的 hook,stdout 上不要再印出其他內容:shell 設定檔在啟動時 echo 出的一行文字,就足以讓 Claude Code 無法把該物件當作 JSON 讀取。參考文件描述了三類欄位:每個事件都接受的通用欄位(部分事件會捨棄這些欄位,或將 systemMessage 送到逐字稿以外的地方;參考文件中各事件的章節會說明具體情形)、部分事件用來封鎖或提供回饋的頂層 decision 與 reason,以及 hookSpecificOutput,這是供需要更細緻控制的事件使用的巢狀物件,必須附帶設為事件名稱的 hookEventName 欄位。通用欄位如下:274

欄位 預設值 說明
continue true false 會在 hook 執行後讓 Claude 完全停止處理。它不會封鎖 PreToolUse 的工具呼叫:若要封鎖,請同時回傳 permissionDecision: "deny"
stopReason 無 當 continue 為 false 時顯示給使用者的訊息;它會留在對話中,因此若對話繼續,Claude 會看到它
suppressOutput false 沒有作用
systemMessage 無 顯示給使用者的警告;在 Agent SDK 與 --output-format stream-json 輸出中,可能會以 SDKInformationalMessage 的形式送達
terminalSequence 無 由 Claude Code 代表 hook 發出的終端機逸出序列(桌面通知、視窗標題、響鈴);僅限 OSC 0、1、2、9、99、777 與 BEL,若值包含其他內容則會被忽略;只會在介面顯示於畫面上的互動式工作階段中寫入,在 -p 模式與 Agent SDK 中會被忽略
{
  "continue": false,
  "stopReason": "The deploy window is closed. Nothing else runs until it reopens.",
  "systemMessage": "deploy-gate stopped this turn"
}

在 PreToolUse 上,單靠此輸出並不會阻止 hook 所檢查的工具呼叫:參考文件指出 continue: false「不會封鎖 PreToolUse 的工具呼叫」。必須阻止該呼叫的防護機制,應在 hookSpecificOutput 中回傳 permissionDecision: "deny"(如下一個範例),或以結束代碼 2 結束。此欄位在不同事件上的行為也不同:在 Stop 與 SubagentStop 上,它優先於結束代碼 2,因此該回合會結束;在 TaskCreated 上,Claude Code 會忽略它。274

PreToolUse 決定控制(建議格式): PreToolUse hooks 使用 hookSpecificOutput 進行更細緻的控制:四種結果(allow、deny、ask、defer),再加上修改工具輸入與注入上下文的能力:87316

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "Command validated and modified",
    "updatedInput": {
      "command": "npm test -- --coverage --ci"
    },
    "additionalContext": "Note: This database has a 5-second query timeout."
  }
}
欄位 值 說明
permissionDecision "allow"、"deny"、"ask"、"defer" allow 會略過權限提示(拒絕與詢問規則仍然適用,任何模式都不會自動核准的操作也仍會提示),deny 封鎖,ask 提示使用者,defer 會結束該回合,讓外層包裝的 -p 程序稍後恢復該呼叫(v2.1.89+;多個 hook 的優先順序為 deny > defer > ask > allow)316
permissionDecisionReason 字串 ask:在提示中顯示給使用者。deny:顯示給 Claude。allow 與 defer:僅寫入除錯日誌316
updatedInput 物件 在執行前修改工具輸入;截至 v2.1.300,它會如同 Claude 自身的輸入一樣接受驗證:未知的鍵會被丟棄,而被工具拒絕的輸入會導致該呼叫被拒絕270
additionalContext 字串 注入到 Claude 該回合的上下文中43

注意: 頂層的 decision 與 reason 欄位在 PreToolUse 上已被棄用。請改用 hookSpecificOutput.permissionDecision 與 hookSpecificOutput.permissionDecisionReason。其他事件(PostToolUse、Stop 等)仍使用頂層的 decision。87

UserPromptSubmit 工作階段標題(v2.1.94+): UserPromptSubmit hooks 可透過 hookSpecificOutput.sessionTitle 設定工作階段標題。138

UserPromptSubmit 在展開前執行(v2.1.299)。 UserPromptSubmit hooks 會在 skill 或自訂斜線指令展開之前執行,因此封鎖提示的 hook 也會一併阻止該指令內嵌的 ! shell 行;UserPromptExpansion 仍會在展開本身時觸發。在 skill 自身 frontmatter 中宣告的 UserPromptSubmit hook,會從呼叫該 skill 的提示之後的下一個提示開始執行。268269

Async Hooks(2026年1月)

Hooks 現在可以在背景執行,而不會阻擋 Claude Code 的執行流程。在 command hook 的設定中加入 async: true:79421

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/notify-slack.sh",
            "async": true
          }
        ]
      }
    ]
  }
}

何時該使用非同步 hooks: - 不應拖慢工作階段的通知(Slack、電子郵件、Pushover) - 可在背景執行的日誌記錄與遙測 - 非關鍵的後續處理(分析、備份)

何時不該使用非同步 hooks: - 格式化(必須在下一次編輯前完成) - 驗證(失敗時必須阻擋) - 任何需要修改工具輸入/輸出的 hook

以提示為基礎與以 Agent 為基礎的 Hooks(v2.1.32+)

除了 shell 命令 hooks(type: "command")之外,Claude Code 還支援兩種由 LLM 驅動的 hook 類型,透過 AI 推理而非腳本來評估條件。87

Prompt hooks(type: "prompt")會向 Claude 模型(預設為 Claude Code 用於背景工作的模型)送出單輪提示。模型回傳 { "ok": true } 表示允許,或回傳 { "ok": false, "reason": "..." } 表示阻擋:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all requested tasks are complete and tests pass.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

HTTP hooks(type: "http")會將事件的 JSON 輸入以 POST 請求送到指定 URL,並接收 JSON 回應。適用於 webhooks、外部通知服務,或以 API 為基礎的驗證(v2.1.63+):102

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "http",
            "url": "https://api.example.com/notify",
            "headers": {
              "Authorization": "Bearer $MY_TOKEN"
            },
            "allowedEnvVars": ["MY_TOKEN"]
          }
        ]
      }
    ]
  }
}

HTTP hooks 使用與命令 hooks 相同的決策格式(回傳含 decision 與 reason 的 JSON)。啟用沙箱時,這些請求會經由沙箱網路代理轉送。不支援 SessionStart/Setup 事件。

Agent hooks(type: "agent")會產生一個具備工具存取權(Read、Grep、Glob)的 subagent,進行多輪驗證。當檢查需要實際檢視檔案或測試輸出時,不妨使用這種類型:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "agent",
            "prompt": "Verify all unit tests pass. Run the test suite and check results. $ARGUMENTS",
            "timeout": 120
          }
        ]
      }
    ]
  }
}

使用 $ARGUMENTS 作為 hook 的 JSON 輸入的預留位置。兩種類型都接受 model(預設:Claude Code 用於背景工作的模型;自 v2.1.330 起,prompt hook 的 model 接受 haiku 或 sonnet 等別名527)與以秒為單位的 timeout(prompt 預設 30,agent 預設 60)。Agent hooks 屬於實驗性功能。兩者皆可使用的事件:PreToolUse、PostToolUse、PostToolUseFailure、PostToolBatch、PermissionDenied、UserPromptSubmit、UserPromptExpansion、Stop、SubagentStop、TaskCreated、TaskCompleted、TeammateIdle。PermissionRequest 只接受 prompt hooks,且 prompt hook 的 ok: false 在該事件上沒有作用:請改由 command hook 拒絕。在 PermissionDenied 上,prompt 或 agent hook 的輸出會被捨棄,因為只有 command hook 能回傳 retry。317

PermissionRequest 不再執行 agent 類型的 hooks(v2.1.280)。 原因值得說清楚,因為它解釋了一類從未真正運作過的 hook:agent hook 的回答從來無法允許或拒絕請求,所以註冊在 PermissionRequest 上的 agent hook 所做的工作,結果都會被丟棄。Claude Code 現在不再默默接受這種設定,而是顯示錯誤,引導您改用 command 或 http hooks,因為它們能夠回傳裁決。如果您的設定檔或 plugin 中有 PermissionRequest agent hook,在此版本之前它也從未真正把關過任何事情,這個錯誤只是第一次有人告訴您而已。請將邏輯移植到 command hook。217

Hook 並行數(v2.1.312+)。 prompt 與 agent hooks 每個工作階段(含 subagents)最多同時執行 24 個,另加最多 12 個等待時間已超過其事件逾時值的 hook,而低於一秒的 timeout 一律以一秒計算。Command hooks 不受影響。hooks 參考文件說明的是每個事件的數字:符合條件的 hooks 會平行執行,當其中超過 12 個是 prompt 或 agent hooks 時,會同時執行 12 個,其餘的則在執行中的 hook 完成時陸續啟動。272273281317

MCP 工具 Hooks(v2.1.118+)

Hooks 現在可以透過 type: "mcp_tool" 直接呼叫 MCP 工具,不必再包一層呼叫伺服器的 Bash 子程序。149

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "mcp_tool",
            "server": "linear",
            "tool": "create_comment",
            "input": {"issue_id": "ENG-123", "body": "Auto-updated by Claude Code"}
          }
        ]
      }
    ]
  }
}

這與使用者已經設定好的 MCP 伺服器相得益彰:任何可從 /mcp 存取的工具,都能被 hook 呼叫。

PostToolUse Hooks 中的 duration_ms(v2.1.119+)

PostToolUse 與 PostToolUseFailure 的 hook 輸入現在包含 duration_ms,即工具的執行時間,不含權限提示與 PreToolUse hooks 所花的時間。149 適合用於偵測緩慢工具、稽核日誌,以及逐一工具的延遲指標。此欄位為選用,因此範例會將缺少的值視為 0:421

#!/bin/bash
# Stderr-flagged warning when an Edit takes more than 10 seconds
INPUT=$(cat)
DUR=$(jq -r '.duration_ms // 0' <<<"$INPUT")
FILE=$(jq -r '.tool_input.file_path // "?"' <<<"$INPUT")
if [ "$DUR" -gt 10000 ]; then
  echo "[slow-edit] ${DUR}ms — investigate $FILE" >&2
fi

所有工具皆可使用 updatedToolOutput(v2.1.121+)

PostToolUse hooks 起初只能透過 updatedMCPToolOutput 取代 MCP 工具的輸出(此欄位對 MCP 工具仍然有效)。截至 v2.1.121,hookSpecificOutput.updatedToolOutput 適用於任何 PostToolUse hook:內建工具(Bash、Read、Edit、Glob、Grep 等)、subagent 工具與 MCP 工具。建議優先使用此欄位,而非僅限 MCP 的欄位。316 使用情境:遮蔽任何工具輸出中的敏感內容、為下游使用者統一結構、在 agent 讀取結果前注入中繼資料。151

Hook 環境變數

Hooks 可以存取環境變數來解析路徑:87

變數 可用範圍 說明
$CLAUDE_PROJECT_DIR 所有 hooks 專案根目錄(路徑含空格時請加引號)
${CLAUDE_PLUGIN_ROOT} Plugin hooks Plugin 的根目錄
$CLAUDE_ENV_FILE SessionStart、Setup、CwdChanged、FileChanged(PowerShell hooks 中不提供)316 用於保存環境變數的檔案路徑,供後續 Bash 命令使用
$CLAUDE_CODE_REMOTE 所有 hooks 在遠端網頁環境中設為 "true"
$CLAUDE_EFFORT 所有 hooks + Bash 工具子程序 目前的努力程度。Hooks 也會透過 effort.level JSON 輸入欄位收到此值(v2.1.133+)。157
$CLAUDE_CODE_SESSION_ID Bash 與 PowerShell 工具子程序、hook 指令、stdio MCP 伺服器 與傳給 hooks 的 session_id 相同的工作階段 ID。讓長時間執行的 shell 能在同一工作階段中關聯輸出(v2.1.132+)。156318

從 SessionStart 保存環境變數:

#!/bin/bash
if [ -n "$CLAUDE_ENV_FILE" ]; then
  echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
fi
exit 0

Claude Code Hooks 與 Agent SDK Hooks 的差異

同樣的生命週期事件,包括 PreToolUse、PostToolUse、UserPromptSubmit、Stop、SubagentStop 以及上方清單中的其餘事件,存在於兩種取用模式中。搜尋 Agent SDK hook 生命週期的人經常落到這裡,因此這項區別值得獨立成一個標題。

Claude Code(CLI)hooks 正是本節所記載的內容:在 settings.json 中設定的處理程式,從 stdin 接收事件 JSON,並以結束代碼或 stdout 上的 JSON 回應。強制執行由 CLI 負責:PreToolUse 的拒絕會在工具呼叫執行前就將其阻擋,即使在 bypassPermissions 模式下亦然。3

Agent SDK hooks 則是供將 Claude Code 執行階段當作函式庫嵌入的 harness 使用的程式化介面。在 claude-agent-sdk-python 中,將 ClaudeAgentOptions 的 include_hook_events=True 設定後,HookEventMessage 物件(PreToolUse、PostToolUse、Stop 及其他事件)會與助理訊息和工具結果從同一個迭代器產出;TypeScript SDK 以 includeHookEvents 對應此功能,其控制協定也跟隨 CLI 的事件清單(TypeScript SDK 在 CLI 推出 DirectoryAdded 的同一版本中加入了該事件)。酬載結構與 CLI 的 stdin JSON 一致,包括 session_id、hook_event_name、tool_input 以及各事件專屬欄位,而 PreToolUse 的決策語意維持相同的優先順序(deny > defer > ask > allow)。3496

強制執行的注意事項是最值得牢記的部分。 SDK 端的 hook 強制執行已兩度被證實會在生命週期邊緣失效放行:一次是 TypeScript SDK 在 hook 回呼待處理期間收到呼叫端中止,卻被轉換為 hook 成功,使受 PreToolUse 把關的工具在中止後仍然執行(已於 0.3.208 修正);另一次是 Python SDK 的串流關閉路徑,讓背景任務發出的 SDK MCP 工具呼叫在無聲無息中繞過了 PreToolUse(已於 0.2.127 修正)。422 兩者皆已修復,但這種模式是結構性的:當傳輸在收集 hook 裁決之前就中斷時,被繞過的 hook 看起來與批准的 hook 一模一樣。如果 SDK hooks 把關任何與安全相關的事項,請鎖定目前的 SDK 版本,並保留一個 CLI 層級的 shell hook,作為您能夠證明有效的強制執行機制。Agent Architecture 指南深入說明了 SDK hook 介面、版本下限與 harness 模式。

回呼失敗時失敗即關閉(fail-closed)。 在大多數事件上,SDK hook 回呼若拋出例外、沒有回傳任何內容,或回傳的輸出未通過驗證,並不會阻止該操作:操作會照常進行,應用程式則會收到一則標記為 hook_callback_failed 的警告訊息,因此崩潰的 PreToolUse 防護會讓工具呼叫進入一般的權限流程。若要改為封鎖該操作,請在 TypeScript 中於比對器上設定 onFailure: "block",或在 Python 中於 HookMatcher 上設定 on_failure="block"(TypeScript Agent SDK v0.3.317 或更新版本、Python Agent SDK v0.2.177 或更新版本)。Stop、SubagentStop、TaskCompleted 與 TeammateIdle 會忽略此選項;設定此選項後,若查詢所連接的 Claude Code 無法遵循它,該查詢會在啟動時失敗。沒有意見的回呼請回傳 {},因為設定 "block" 後,沒有 return 的路徑會封鎖該操作。TypeScript SDK 0.3.325 也新增了標記為 hook_no_verdict 的 system/informational 警告,會在 PreToolUse hook 無法執行或回答、或逾時,卻沒有拒絕其工具呼叫時送出;這個標記見於 SDK changelog,而依2026年11月25日讀取的 Agent SDK hooks 文件,其中並未記載。549

HTTP hook 安全性(v2.1.51+):會將環境變數插入標頭的 HTTP hooks,現在必須明確列出 allowedEnvVars 清單。此舉可防止透過標頭值任意外洩環境變數。啟用沙箱時,HTTP hooks 也會經由沙箱網路代理路由,以強制套用網域允許清單。HTTP hooks 不支援 SessionStart/Setup 事件。96

{
  "hooks": {
    "PostToolUse": [{
      "hooks": [{
        "type": "http",
        "url": "https://api.example.com/notify",
        "headers": { "Authorization": "Bearer $MY_TOKEN" },
        "allowedEnvVars": ["MY_TOKEN"]
      }]
    }]
  }
}

Hook 工作區信任(v2.1.51+):statusLine 與 fileSuggestion 的 hook 指令,現在必須先通過工作區信任確認,才能在互動模式下執行,藉此封堵潛在的安全漏洞。96

實用的 Hook 範例

編輯後自動格式化 TypeScript 檔案:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(jq -r \".tool_input.file_path // empty\"); [[ \"$FILE\" == *.ts ]] && npx prettier --write \"$FILE\" || true'"
          }
        ]
      }
    ]
  }
}

記錄所有 bash 指令:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command' >> ~/.claude/bash-history.log"
          }
        ]
      }
    ]
  }
}

依路徑封鎖對敏感檔案的讀取與編輯:

#!/bin/bash
# .claude/hooks/protect-files.sh
data=$(cat)
path=$(echo "$data" | jq -r '.tool_input.file_path // empty')

if [[ "$path" == *".env"* ]] || [[ "$path" == *"secrets/"* ]] || [[ "$path" == *".pem"* ]]; then
  echo "Blocked: Cannot access sensitive file $path" >&2
  exit 2  # Exit 2 = block the tool call. Exit 1 = non-blocking error (hook failure only).
fi
exit 0

請將它註冊在三個檔案工具的 PreToolUse 上,這些工具的輸入帶有 file_path:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

此指令碼只檢查 tool_input.file_path,因此看不到 Bash 指令讀取了什麼。若要涵蓋這部分,請新增 Read 拒絕規則,它也會涵蓋 Claude Code 在 Bash 中能辨識的檔案指令(例如 cat);若要在作業系統層級對 shell 指令強制執行,請開啟沙箱並關閉在沙箱外的重試(sandbox.allowUnsandboxedCommands: false)。421

程式碼變更後執行測試:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(jq -r \".tool_input.file_path // empty\"); [[ \"$FILE\" == *.test.ts ]] || npm run test:affected'"
          }
        ]
      }
    ]
  }
}

自訂通知系統:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "notify-send 'Claude Code' 'Waiting for your input'"
          }
        ]
      }
    ]
  }
}

將動態情境注入提示:

#!/bin/bash
# .claude/hooks/inject-context.sh
# Add current git branch and recent commits to every prompt

branch=$(git branch --show-current 2>/dev/null)
commits=$(git log --oneline -3 2>/dev/null | tr '\n' ' ')

if [ -n "$branch" ]; then
  echo "[Context: Branch '$branch', Recent: $commits]"
fi
exit 0

Hook 除錯

啟用除錯模式以排解 hooks 的問題:

claude --debug

--debug 不會輸出到終端機。請讀取位於 ~/.claude/debug/<session-id>.txt 的日誌,或以 claude --debug-file <path> 啟動來指定檔案。316

除錯日誌會記錄: - 哪些 hooks 執行了、針對哪個事件與比對器,以及每次執行如何結束 - 每個 hook 的輸出,以及是否能解析為 JSON - 持續時間:自 v2.1.296 起,每個 command hook 都會留下一行以其執行時間結尾的 Hooks:,例如 Hooks: PostToolUse:Write [.claude/hooks/log-write.sh] finished with status 0 (31ms) - 設定 CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose 時,比對器數量與查詢比對情形

Hook 來源顯示(v2.1.75+):當 hook 需要使用者確認時,權限提示現在會顯示該 hook 的來源(settings、plugin 或 skill),更容易辨識是哪個元件在請求存取。115

元件範圍的 Hooks(v2.1.0+)

Hooks 可以透過 frontmatter 直接定義在 Skills、subagents 與斜線指令中。它們使用與設定中的 hooks 相同的格式,且可以使用任何 hook 事件。subagent 的 hooks 只在該 subagent 執行期間執行(其 Stop hook 會變成 SubagentStop);skill 的 hooks 會在呼叫該 skill 時註冊,並在工作階段的其餘時間持續執行。33317423

內嵌 hooks 的 Skill:

---
name: secure-deployment
description: Deployment skill with security validation
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: ".claude/hooks/validate-deploy.sh"
  PostToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: ".claude/hooks/log-deploy.sh"
  Stop:
    - hooks:
        - type: command
          command: ".claude/hooks/cleanup.sh"
          once: true  # Removed after its first successful run
---

每個比對器項目都包含一份 hooks: 清單,其中每個處理程式都帶有 type。扁平的項目(matcher 與 command 並列,且沒有 hooks: 清單)並不是這種格式:hooks 參考文件指出,frontmatter hooks 使用「與基於設定的 hooks 相同的設定格式」,而其 skill 範例也以這種方式將每個處理程式巢狀放在 hooks: 清單之下。317

once: true(僅限 skill frontmatter)會在 hook 第一次成功執行後將其移除,適合用於清理或收尾工作。執行失敗、以結束代碼 2 封鎖或逾時的執行,都會讓該 hook 保留原處。設定檔與 agent frontmatter 會忽略此欄位。317

Agent frontmatter hooks 需要工作區信任(v2.1.218)。在 agent 檔案 frontmatter 中宣告的 hooks,不再從未受信任的資料夾執行;包含該 agent 檔案的資料夾本身必須先通過工作區信任確認,其 hooks 才會執行。這封堵了一個漏洞:原本放進未受信任目錄的 agent 檔案,可以在沒有任何信任提示的情況下執行 hook 指令。此變更將 v2.1.51 針對 statusLine/fileSuggestion 的信任要求,延伸至 agent 範圍的 hooks。192 此要求涵蓋專案層級的 agent 檔案:來自 ~/.claude/agents/ 中 agents 的 hooks,以及透過 --agents 傳入之定義的 hooks,都不需經過這個步驟即可執行。495

長時間工作階段策略

對於整夜執行或無人值守的 Claude Code 工作階段,不妨設定 hooks,讓 Claude 不需人工介入也能保持正軌。關鍵在於:把 linting 與測試 hooks 當作護欄,強制 Claude 先修正問題再繼續。55

「測試不通過就不停止」模式:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "{ npm run lint && npm run typecheck; } 1>&2 || exit 2",
            "timeout": 60
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npm test 1>&2 || exit 2"
          }
        ]
      }
    ]
  }
}

結束代碼 2 才會把輸出送給 Claude:在 PostToolUse 上,Claude 會讀取 stderr;在 Stop 上,它還會讓 Claude 無法停止。一般的失敗(結束代碼 1)是 Claude 永遠看不到的非封鎖性錯誤,而以 0 結束的 hook,其 stdout 會寫入除錯日誌。timeout 的單位為秒。若 Stop hook 連續封鎖八次、其間沒有任何工具呼叫,Claude Code 會推翻它的封鎖;hook 指令碼可以從輸入中讀取 stop_hook_active,得知自己已經強制繼續過一次。319

整夜工作階段的策略:

  1. 事前檢查:使用 SessionStart hook 確認環境已就緒。Setup hook 在一般啟動時不會觸發;它只會在使用 claude --init-only 時,或在 -p 模式下搭配 --init 或 --maintenance 時執行316
  2. 持續驗證:PostToolUse hooks 在每次變更後執行測試
  3. 完成把關:Stop hooks 在 Claude 宣告「完成」前,驗證所有驗收條件
  4. 通知:當 Claude 完成或卡住時,Stop hooks 可透過 Slack/Pushover 通知您

在沙箱容器中搭配 --dangerously-skip-permissions,即可實現完全自主的整夜執行。Claude 會持續迭代,直到測試通過或用盡所有選項為止。


參考資料


  1. Claude Code 文件。Hooks 指南。2025年12月自 docs.anthropic.com 重新導向;標準網址於 2026年2月更新。 ↩↩↩↩↩

  2. Claude Code CHANGELOG,2.1.0 章節,擷取於2026年11月11日:「Added hooks support to agent frontmatter, allowing agents to define PreToolUse, PostToolUse, and Stop hooks scoped to the agent’s lifecycle」;「Added hooks support for skill and slash command frontmatter」;「Added support for once: true config for hooks」。該章節列出 109 項變更。2.1.1 隨後於2026年1月7日在 npm 上發布,沒有 CHANGELOG 章節。 ↩

  3. Claude Code CHANGELOG,2.1.9 章節,擷取於2026年11月11日:「Added support for PreToolUse hooks to return additionalContext to the model」;「Added ${CLAUDE_SESSION_ID} string substitution for skills to access the current session ID」;「Added auto:N syntax for configuring the MCP tool search auto-enable threshold, where N is the context window percentage (0-100)」;「Added plansDirectory setting to customize where plan files are stored」。 ↩

  4. Claude Code CHANGELOG,2.1.10 章節,擷取於2026年11月11日:「Added new Setup hook event that can be triggered via --init, --init-only, or --maintenance CLI flags for repository setup and maintenance operations」;「Added keyboard shortcut ‘c’ to copy OAuth URL when browser doesn’t open automatically during login」。 ↩

  5. @trq212,2025年10月9日,轉述一位同事的設定:「Daisy 讓 Sonnet 4.5 整夜執行 6 至 8 小時的訣竅:使用 hooks」;「用於 lint 與測試的 hooks,確保 Claude 執行測試,並提示它在測試通過之前不要停止」。 ↩

  6. Hooks 參考,Claude Code 文件,擷取於2026年11月11日,關於 command hook 的 async 欄位:「若為 true,會在背景執行而不阻塞。」 ↩

  7. Claude Code Docs。Hooks 參考:以提示為基礎的 hooks、以 agent 為基礎的 hooks、hook 環境變數($CLAUDE_PROJECT_DIR、$CLAUDE_ENV_FILE)、PreToolUse 的 hookSpecificOutput 格式。2026年2月。Claude Code Docs。建立自訂 subagents:--agents CLI 旗標、disallowedTools、maxTurns、mcpServers、delegate 權限模式。2026年2月。2026年2月12日存檔的 sub-agents 頁面列出的 permissionMode 值為 default、acceptEdits、delegate、dontAsk、bypassPermissions 或 plan。2026年11月10日擷取的頁面已沒有 delegate 值:「default、acceptEdits、auto、dontAsk、bypassPermissions、plan,或作為 default 別名的 manual」。 ↩↩↩↩

  8. Claude Code v2.1.51 版本說明,GitHub,2026年2月24日,擷取於2026年11月11日:「Env var interpolation now requires an explicit allowedEnvVars list in the hook configuration.」;「HTTP hooks are now routed through the sandbox network proxy when sandboxing is enabled, enforcing the domain allowlist. HTTP hooks are not supported for SessionStart/Setup events.」Claude Code CHANGELOG,2.1.51 章節,同次擷取:「Added claude remote-control subcommand for external builds, enabling local environment serving for all users.」;「Added support for custom npm registries and specific version pinning when installing plugins from npm sources」;「Updated plugin marketplace default git timeout from 30s to 120s and added CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to configure.」;「Tool results larger than 50K characters are now persisted to disk (previously 100K).」;「BashTool now skips login shell (-l flag) by default when a shell snapshot is available, improving command execution performance.」;「Fixed a security issue where statusLine and fileSuggestion hook commands could execute without workspace trust acceptance in interactive mode.」;「The /model picker now shows human-readable labels」。協調多個 Claude Code 工作階段組成的團隊,Claude Code 文件,同次擷取,涵蓋隊友的計畫核准,以及「使用 hooks 強制執行品質關卡」一節中的 TeammateIdle 與 TaskCompleted hooks。 ↩↩

  9. GitHub Releases。v2.1.63(2月28日):內建的 /simplify 與 /batch 斜線指令、worktree 共用的專案設定與自動記憶、ENABLE_CLAUDEAI_MCP_SERVERS=false 停用選項、HTTP hooks 的 type: http 處理器、/copy 的「一律複製完整回應」選項、VSCode 工作階段重新命名/移除、/clear 重設 skill 快取、多項記憶體洩漏修正、REPL bridge 競態條件修正。2026年2月28日。 ↩

  10. GitHub Releases。v2.1.69:/claude-api skill、InstructionsLoaded hook 事件、hook 事件中的 agent_id/agent_type/worktree、${CLAUDE_SKILL_DIR}、/reload-plugins、sandbox.enableWeakerNetworkIsolation、includeGitInstructions 設定、remote-control 自訂名稱、Voice STT 新增 10 種語言(共 20 種)、effort 層級顯示、Ctrl+U 退出 bash、數字鍵盤支援、Sonnet 4.5→4.6 自動遷移。70 多項錯誤修正。2026年3月5日。 ↩

  11. Claude Code CHANGELOG,2.1.75 章節(2026年3月13日),擷取於2026年11月11日:「Added 1M context window for Opus 4.6 by default for Max, Team, and Enterprise plans (previously required extra usage)」;「Added /color command for all users to set a prompt-bar color for your session」;「Added session name display on the prompt bar when using /rename」;「Added last-modified timestamps to memory files, helping Claude reason about which memories are fresh vs. stale」;「Added hook source display (settings/plugin/skill) in permission prompts when a hook requires confirmation」;「Breaking change: Removed deprecated Windows managed settings fallback at C:\ProgramData\ClaudeCode\managed-settings.json」。 ↩

  12. GitHub Releases。v2.1.76:MCP elicitation 支援:MCP 伺服器可在任務進行中透過互動式對話框(表單欄位或瀏覽器 URL)請求結構化輸入。新增 Elicitation 與 ElicitationResult hooks。-n/--name CLI 旗標可設定工作階段顯示名稱。worktree.sparsePaths 支援 monorepo 的 git sparse-checkout。PostCompact hook。/effort 斜線指令。工作階段品質問卷(feedbackSurveyRate)。錯誤修正:延遲載入工具在壓縮後遺失輸入 schema、計畫模式重新核准、語音模式按鍵、自動壓縮斷路器(最多 3 次嘗試)、透過 SSH 在 tmux 中複製到剪貼簿、Remote Control 工作階段穩定性。2026年3月14日。 ↩↩↩

  13. GitHub Releases v2.1.78。v2.1.78:StopFailure hook 事件、${CLAUDE_PLUGIN_DATA} 持久化外掛狀態、代理 frontmatter(effort/maxTurns/disallowedTools)、ANTHROPIC_CUSTOM_MODEL_OPTION、tmux 通知透傳、逐行回應串流。安全性:缺少沙箱相依套件時顯示明確警告。修正:超過 5MB 的大型工作階段截斷、無限 stop hook 迴圈、沙箱絕對路徑、WSL2 語音、VS Code 中的 Homebrew PATH。2026年3月17日。 ↩

  14. GitHub Releases v2.1.83。v2.1.83:managed-settings.d/ 插入式目錄、CwdChanged/FileChanged hook 事件、sandbox.failIfUnavailable、CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1、逐字稿搜尋、initialPrompt 代理 frontmatter、Ctrl+X Ctrl+E 外部編輯器別名、停止所有代理改為 Ctrl+X Ctrl+K、TaskOutput 已棄用。35 項以上錯誤修正。2026年3月25日。 ↩↩

  15. Claude Code CHANGELOG,2.1.89 章節(npm,2026年3月31日),擷取於2026年11月11日:「Added PermissionDenied hook that fires after auto mode classifier denials」;「Added CLAUDE_CODE_NO_FLICKER=1 environment variable to opt into flicker-free alt-screen rendering with virtualized scrollback」。v2.1.88 於2026年3月30日發布至 npm,其後撤下:npm registry 保留了其發布時間,但已不再列出該版本;GitHub 有該標籤但沒有發行版本;CHANGELOG 也沒有 2.1.88 章節,因此其項目列於 2.1.89 之下。 ↩

  16. GitHub Releases v2.1.84。v2.1.84:PowerShell 工具(Windows 選擇性啟用)、TaskCreated hook 事件、WorktreeCreate HTTP hook 支援、ANTHROPIC_DEFAULT 模型能力環境變數、CLAUDE_STREAM_IDLE_TIMEOUT_MS、allowedChannelPlugins 受管設定、rules/skills 中的 paths: YAML glob 清單、MCP 2KB 說明長度上限、閒置 75 分鐘以上後的返回提示、token 數量改用 1.5m 格式、CJK 輸入法修正。25 項以上錯誤修正。2026年3月26日。 ↩

  17. GitHub Releases v2.1.94。v2.1.94:透過 Mantle 使用 Bedrock(CLAUDE_CODE_USE_MANTLE=1),API/Bedrock/Vertex/Foundry/Team/Enterprise 的預設努力等級由 medium 改為 high,精簡版 Slack MCP 標頭,UserPromptSubmit hooks 的 hookSpecificOutput.sessionTitle,plugin skill 名稱取自 frontmatter,429 速率限制訊息顯示,macOS keychain 登入修正,plugin hook 修正,捲動緩衝區/渲染修正。2026年4月7日。v2.1.96(4月8日):Bedrock 驗證迴歸問題的緊急修正。 ↩

  18. Claude Code CHANGELOG,綜合參考 v2.1.116(2026年4月20日)、v2.1.117(2026年4月22日)、v2.1.118(2026年4月23日)與 v2.1.119(2026年4月23日)。v2.1.116:/resume 在 40MB 以上的工作階段快了 67%;多個 stdio 伺服器時 MCP 啟動更快(resources/templates/list 延後至首次 @ 提及時才載入);內嵌思考旋轉指示器(「still thinking」、「thinking more」、「almost done thinking」);/config 搜尋現在也會比對選項值;/doctor 可在回合進行中開啟;plugin 自動安裝缺少的相依套件;Bash 工具會顯示 gh GitHub API 速率限制提示;設定的 Usage 分頁立即顯示,且在用量端點受速率限制時仍可運作;透過 --agent 以主執行緒 agent 執行時,agent frontmatter 的 hooks: 會觸發;安全性修正:沙箱自動允許不再繞過針對 /、$HOME 或其他關鍵根目錄的 rm/rmdir 危險路徑檢查。(v2.1.116 所還原的 4月16日系統提示冗長度限制,記載於 150 的事後檢討中,而非 v2.1.116 的版本說明。)

    v2.1.117:外部建置可用 CLAUDE_CODE_FORK_SUBAGENT=1 啟用分叉 subagents;透過 --agent 的主執行緒 agent 工作階段會載入 agent frontmatter 的 mcpServers;即使專案釘選了不同模型,/model 的選擇仍會在重新啟動後保留,且啟動標頭會顯示釘選來源;/resume 提供過期工作階段摘要;預設並行啟動 MCP(本機與 claude.ai);plugin 安裝/更新/重新整理/自動更新時強制執行 blockedMarketplaces/strictKnownMarketplaces;Advisor Tool 實驗性功能,附有標籤、深入了解連結,以及啟用時的啟動通知;cleanupPeriodDays 保留期清理涵蓋 ~/.claude/tasks/、~/.claude/shell-snapshots/、~/.claude/backups/;OTel user_prompt 事件包含 command_name/command_source(自訂與 MCP 名稱預設遮蔽,除非設定 OTEL_LOG_TOOL_DETAILS=1);cost.usage/token.usage/api_request/api_error 包含 effort 屬性;原生 macOS/Linux 建置以內嵌的 bfs/ugrep 經由 Bash 工具取代 Glob/Grep;Pro/Max 在 Sonnet 4.6 與 Opus 4.6 上的預設 effort 現為 high(原為 medium);修正:Opus 4.7 工作階段原本以 200K 視窗而非原生 1M 計算 /context,導致過早自動壓縮。v2.1.118:vim 視覺模式(v)與視覺行模式(V),支援選取、運算子與視覺回饋;/cost 與 /stats 合併為 /usage(保留輸入捷徑);透過 /theme 或 ~/.claude/themes/*.json 使用具名主題(plugins 可隨附 themes/ 目錄);hooks 可透過 type: "mcp_tool" 直接呼叫 MCP 工具;DISABLE_UPDATES 環境變數封鎖所有更新路徑,包括手動的 claude update(比 DISABLE_AUTOUPDATER 更嚴格);WSL 透過 wslInheritsWindowsSettings 原則繼承 Windows 端的受管設定;autoMode.allow/soft_deny/environment 中的 $defaults 哨兵值可在內建清單之外加入自訂規則;「不再詢問」的 auto mode 選擇加入;claude plugin tag 建立發行 git 標籤並驗證版本。

    v2.1.119:/config 設定(主題、編輯器模式、詳細輸出)會保存至 ~/.claude/settings.json,並遵循專案/本機/原則的優先順序;prUrlTemplate 設定可讓頁尾的 PR 標記指向自訂的程式碼審查 URL,而非 github.com;CLAUDE_CODE_HIDE_CWD 在啟動標誌中隱藏工作目錄;--from-pr 接受 GitLab MR、Bitbucket PR 與 GitHub Enterprise PR 的 URL;--print 遵循 agent 的 tools:/disallowedTools: frontmatter;--agent <name> 對內建 agents 遵循 permissionMode;PowerShell 工具命令在權限模式下自動核准(與 Bash 一致);PostToolUse/PostToolUseFailure hook 輸入包含 duration_ms(工具執行時間,不含權限提示與 PreToolUse hooks);subagent 與 SDK 的 MCP 伺服器重新設定會並行連線伺服器;安全性:blockedMarketplaces 正確強制執行 hostPattern 與 pathPattern 項目;OTel tool_result 與 tool_decision 事件包含 tool_use_id;tool_result 包含 tool_input_size_bytes;狀態列 stdin JSON 包含 effort.level 與 thinking.enabled;Vertex AI 上預設停用工具搜尋(以 ENABLE_TOOL_SEARCH 選擇加入)。 ↩↩

  19. 近期Claude Code品質問題報告的最新說明。Anthropic工程事後檢討,2026年4月23日。涵蓋三項各自獨立的品質退化問題,均於4月20日(v2.1.116)解決,並於4月23日為所有訂閱者重設用量上限:(1)推理強度預設值:2026年3月4日由 high 改為 medium,以減少讓 UI 看似凍結的極長延遲;4月7日回復,因為使用者表示寧可預設使用較高的智慧,並在處理簡單任務時自行選擇較低的 effort。影響Sonnet 4.6與Opus 4.6。(2)Prompt cache 思考清除錯誤:一項原本旨在對閒置超過一小時的工作階段清除一次較舊思考內容的變更,卻變成在該工作階段其後的每一輪都清除,導致健忘、重複,以及用量上限消耗加快。影響期間為3月26日至4月10日,於v2.1.101修復。影響Sonnet 4.6與Opus 4.6。(3)系統提示詞的簡潔性限制:4月16日加入,用以處理 Opus 4.7 過於多話的問題;該文章指出「其中一項評估顯示 Opus 4.6 與 4.7 都下滑了 3%」以及「這影響了 Sonnet 4.6、Opus 4.6 與 Opus 4.7」;於4月20日在 v2.1.116 中回復。Anthropic 聲明的改善措施:讓更多內部員工使用與公開版完全相同的建置、改進其內部使用的 Code Review 工具、更嚴格管控系統提示的變更並為每項變更執行一套廣泛的逐模型評估,以及對任何可能犧牲智慧表現的變更採取「浸泡測試期、更廣泛的評估套件與漸進式推出」。擷取於2026年11月11日。 

  20. Claude Code版本說明,為v2.1.121(2026年4月28日,00:31 UTC)與v2.1.122(2026年4月28日,22:05 UTC)的綜合參考。v2.1.121:alwaysLoad MCP伺服器設定選項(略過工具搜尋延遲載入);MCP啟動時自動重試3次;claude plugin prune與--prune連鎖清理;/skills支援輸入即篩選;PostToolUse的hookSpecificOutput.updatedToolOutput從僅限MCP擴展至所有工具;.claude/skills/、.claude/agents/、.claude/commands/不再觸發--dangerously-skip-permissions提示;Vertex AI以X.509憑證為基礎的Workload Identity Federation(mTLS ADC);SDK mcp_authenticate redirectUri;OTel在LLM請求span中新增stop_reason、gen_ai.response.finish_reasons與user_system_prompt(須透過OTEL_LOG_USER_PROMPTS啟用);/terminal-setup啟用iTerm2剪貼簿存取,讓/copy可在tmux中使用;分頁標題遵循language設定;CLAUDE_CODE_FORK_SUBAGENT=1擴展至非互動式的claude -p;升級後啟動更快(版本說明啟動畫面移除了Recent Activity面板);claude.ai連接器針對相同上游URL去除重複。v2.1.122:ANTHROPIC_BEDROCK_SERVICE_TIER環境變數(default/flex/priority)以X-Amzn-Bedrock-Service-Tier傳送;/resume可依PR URL搜尋,涵蓋GitHub、GHE、GitLab、Bitbucket;/mcp顯示隱藏的連接器並附上移除重複項的提示,同時釐清瀏覽器授權後的未授權訊息;OTel新增claude_code.at_mention記錄事件,用於@提及的解析;api_request/api_error的數值屬性以數字輸出(先前為字串)。兩個版本中的重要修正:/usage約2GB的記憶體洩漏、圖片密集工作階段的RSS成長達數GB、--resume略過損毀的逐字稿行並修正大型外部建置工作階段當機、CWD被刪除或移動時的Bash復原、Bedrock在application inference profile上的thinking修正、Vertex/Bedrock在結構化輸出時對output_config額外輸入的拒絕、ToolSearch遺漏工作階段開始後才連線的非阻塞MCP工具、較新模型的圖片縮放上限由2576改為2000 px、bash模式中的!exit/!quit不再終止CLI、tmux/GNOME/Windows Terminal/Konsole上的回捲重複,以及格式錯誤的hooks項目不再使整個settings.json失效。 ↩

  21. Claude Code v2.1.132版本說明。2026年5月6日。為Bash工具子程序新增CLAUDE_CODE_SESSION_ID環境變數(與傳給hooks的session_id一致)。新增CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1環境變數,可選擇退出全螢幕替代畫面轉譯器,讓對話保留在終端機原生的回捲區中。更新/tui fullscreen啟動橫幅,說明轉譯器的更多優點(較低的記憶體用量、滑鼠支援、選取時自動複製)。另有20多項修正,涵蓋終端機/輸入處理(SIGINT、SSH斷線、終端機模式、游標定位)、文字編輯與貼上(emoji與字位損毀、vim運算子、跳脫序列、以/開頭的貼上內容後文字被吞掉)、UI/轉譯(休眠後全螢幕空白、捲動速度、滾輪處理、自動完成彈出視窗)、工作階段管理(--resume失敗、emoji截斷、計畫模式的--permission-mode旗標)、命令工具(/usage、/terminal-setup、/effort、/status、/login、/upgrade)、MCP伺服器整合(工具擷取、授權顯示、非協定資料、stdio MCP伺服器無限制的記憶體成長、tools/list重試)、平台特定問題(Windows Terminal、JetBrains IDE、macOS鍵盤、X11 Linux),以及設定ENABLE_PROMPT_CACHING_1H時Bedrock與Vertex的400錯誤。 ↩

  22. Claude Code v2.1.133 版本說明。2026年5月7日。新增 worktree.baseRef 設定(fresh | head);依版本說明所述:「the default fresh changes EnterWorktree’s base back to origin/<default> (it has been local HEAD since 2.1.128)」,以及「set worktree.baseRef: "head" to keep unpushed commits in new worktrees.」Hooks 現在可透過 effort.level JSON 輸入欄位與 $CLAUDE_EFFORT 環境變數取得目前的 effort 等級;Bash 工具的指令也能讀取 $CLAUDE_EFFORT。新增 sandbox.bwrapPath 與 sandbox.socatPath 受管設定(Linux/WSL),可自訂 bubblewrap 與 socat 二進位檔的位置。新增 parentSettingsBehavior 管理層級鍵('first-wins' | 'merge'),可將 SDK managedSettings(父層級)納入政策合併。修正 subagents 無法透過 Skill 工具找到專案、使用者或 plugin skills 的問題。其他修正:平行工作階段中重新整理權杖後出現 401 的競態條件、磁碟根目錄允許規則的範圍、MCP OAuth 代理與 mTLS 支援、Remote Control 的停止/中斷可完整執行取消、跨工作階段的 /effort 外洩,以及 --help 中列出 --remote-control。 ↩

  23. Claude Code v2.1.191 版本說明 與 Claude Code Changelog(正式版)。2026年6月24日。v2.1.191: /rewind 支援從執行 /clear 之前的狀態恢復對話;沙箱網路權限對話框會在本次工作階段中記住已允許的主機;串流回應期間 CPU 用量減少約 37%;降低終端機輸出快取造成的長工作階段記憶體成長。修正:從工作面板停止背景代理程式後現在會永久生效(不會再復活);在串流進行中閱讀先前輸出時,捲動不會再跳到底部;/voice 會說明組織政策的限制,而非顯示籠統的「無法使用」;/login 的 URL 在 Windows Terminal 換行時不再被截斷;透過 ssh/tmux 在全螢幕 Ghostty 中可用 Cmd+點擊開啟連結;claude agents 不再把內建斜線指令(例如 /usage)當作提示文字送出,並會為貼上的圖片顯示 [Image #N] 佔位符;使用逗號分隔比對器的 hooks(例如 Bash,PowerShell)不再無聲地永遠不觸發;/permissions 中「最近拒絕」的核准在關閉後會保留;代理程式面板不再超出溢位上限多跳一列;歡迎畫面不再在 80×24 的 Terminal 中溢出;受管理的 forceRemoteSettingsRefresh 現在可透過 MDM/檔案政策生效;改善 MCP 伺服器的可靠性。擷取於2026年6月25日。 ↩

  24. Claude Code Changelog(正式版),2026年6月25日至26日(v2.1.192 與 v2.1.194 未發布)。v2.1.193(6月25日): 新的 autoMode.classifyAllShell 設定會將所有 Bash/PowerShell 指令交由自動模式分類器處理,而不再只處理任意程式碼執行的模式;自動模式的拒絕原因會加入逐字稿、拒絕通知以及 /permissions 的最近拒絕清單;新的 claude_code.assistant_response OpenTelemetry 記錄事件帶有模型的回應文字,除非設定 OTEL_LOG_ASSISTANT_RESPONSES=1,否則會經過遮蔽處理。若未設定該變數,則沿用 OTEL_LOG_USER_PROMPTS 的設定,因此原本已記錄提示內容的部署在升級後會開始收到回應內容(設定 OTEL_LOG_ASSISTANT_RESPONSES=0 可維持只記錄提示);bash 模式(!)支援即時的檔案路徑自動完成;當 MCP 伺服器需要驗證時,啟動時會顯示通知並指向 /mcp;閒置的背景 shell 指令會在記憶體壓力下自動回收(可用 CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP=1 停用);另修正了 /login 之後 /model 狀態過時、誤觸的背景化取消、幻影式的已恢復子代理程式生成,以及 MCP headersHelper 在 401/403 時重新驗證等問題。v2.1.195(6月26日): 新的 CLAUDE_CODE_DISABLE_MOUSE_CLICKS 環境變數可在全螢幕模式下停用滑鼠點擊/拖曳/懸停,同時保留滾輪捲動;含連字號識別碼的 hook 比對器(例如 code-reviewer、mcp__brave-search)現在採用完全比對,而非子字串比對(若要比對含連字號 MCP 伺服器的所有工具,請使用 mcp__brave-search__.*);另包含語音聽寫修正(macOS 裝置切換時的靜音問題;不以空格分詞的語言可自動送出)、外掛啟用/同意的修正,以及背景工作/代理程式常駐程序的可靠性修正。擷取於2026年6月30日。 ↩

  25. Claude Code CHANGELOG,v2.1.214 條目。2026年7月。v2.1.214: 單一區段的 dir/** 允許規則(例如 Edit(src/**))現在只會比對 <cwd>/dir,而非目錄樹中任何巢狀的 dir/;deny/ask 規則仍維持任意深度比對,hook 的 if: 條件也套用相同的 cwd 範圍限制(若要比對任意深度,請寫 **/dir/**);權限的失敗即封閉(fail-closed)強化:修正 Windows PowerShell 5.1 的繞過問題、Bash 檔案描述元重新導向形式改為失敗即封閉、超過 10,000 個字元的命令一律提示確認、[[ ]] 內的 zsh 下標/修飾符會提示確認、不安全的 help/man 變體不再自動核准、遠端工作階段的提示在本機確認前無法繼續、docker/Podman 的常駐程式重新導向旗標(--url、--connection、--identity、遠端模式)會提示確認,而 file -m/--magic-file/-f/--files-from 需要權限;新增 EndConversation 工具,可在遇到高度辱罵性輸入或越獄嘗試時結束工作階段;SessionStart hooks 對分支出來的工作階段回報來源為 "fork"(先前為 "resume");OTel 日誌事件新增 message.uuid、client_request_id 與 tool_source 屬性,CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH 可設定 60 KB 的內容截斷上限,subagentStatusLine 的酬載也包含推理強度。擷取於2026年7月21日。(v2.1.213 從未發布。) ↩↩

  26. Claude Code CHANGELOG,v2.1.218 條目。2026年7月。v2.1.218: /code-review 改以背景子代理程式執行,審查工作不再佔據對話內容,堆疊的斜線指令仍是其審查目標;設定 context: fork 的 skills 預設在背景執行,可透過新的 background: false frontmatter 鍵逐一停用;危險 rm、背景 & 與可疑 Windows 路徑檢查不再開啟權限對話框,改由 auto 模式分類器裁決;在 auto 模式下的 plan 模式,對於靜態分析器無法證明為唯讀的 Bash 指令也不再提示;agent frontmatter hooks 須待 agent 檔案所在資料夾本身已接受工作區信任後才會執行;/deep-research 僅在手動呼叫時啟動。另有:左方向鍵捨棄確認,以及 Esc 從 agent 檢視返回;伺服器管理的無害功能/成本切換略過設定核准提示;拒絕含 : 的 agent 名稱;skill 與 plugin frontmatter 的布林值接受 yes/no/on/off/1/0;信任對話框會標明儲存庫根目錄;改善 IDE 互動的沙箱限制;Ctrl+B 背景 shell 上限;Bedrock ARN 支出計量;headless/SDK 工作階段在壓縮後保留 fork 工作階段的沿革;修正 Windows \u 路徑損壞;修正遠端工作階段的殭屍心跳。擷取於2026年7月24日,當時 v2.1.218(發布於 2026-07-22T21:24Z)為 npm latest。(歸屬更正,2026年7月25日:claude mcp list//mcp 顯示 HTTP 狀態與錯誤文字一項,以及 MCP 隱藏空白字元警告,原列於此處的 v2.1.218 之下;原始 changelog 將兩者皆置於 v2.1.219 條目。已移至 193。) ↩

  27. Claude Code CHANGELOG,v2.1.219 與 v2.1.220 條目。2026年7月。v2.1.219(7月24日): 新增 Claude Opus 5(claude-opus-5)作為新的預設 Opus 模型,具 1M 脈絡視窗,fast 模式定價為每 MTok $10/$50;新增 sandbox.network.strictAllowlist 設定,讓沙箱指令在不提示的情況下直接拒絕未列入允許清單的主機;新增 DirectoryAdded hook,在 /add-dir 或 SDK 的 register_repo_root 控制請求於工作階段中途登錄新工作目錄後觸發;在 headless stream-json 的 init 事件中新增 mcp_server_errors,列出因設定驗證而略過的 --mcp-config 項目(終端機執行時會印出啟動警告);新增 workflowSizeGuideline 設定鍵,讓建議性的 Dynamic workflow size 準則可由任一設定檔設定,設定後 /config 中對應的列會隱藏;stream-json 新增巢狀子代理程式轉送,設定 --forward-subagent-text 時,深度 2 以上產生的子代理程式也會出現,並以產生它們的 Agent tool_use id 作為鍵;動態工作流程改為預設採用中型規模準則(目標少於 15 個代理程式);將 Opus 4.7 自 fast 模式移除,/fast 現在適用於 Opus 5 與 Opus 4.8;子代理程式現在預設可產生最深達第 3 層的巢狀子代理程式(原為 1);設定 CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=1 可停用巢狀;更新 claude-api skill,預設改為 Claude Opus 5,並提供自 Opus 4.8 的遷移路徑;伺服器連線失敗時,claude mcp list 與 /mcp 會顯示 HTTP 狀態與錯誤文字,並對含隱藏前導或尾端空白字元的 MCP 設定值提出警告;

    受管理的 MCP 允許清單/拒絕清單中的 ${VAR} 項目改由啟動環境與受管理設定的 env 解析,不再使用設定檔的 env;在執行中工作流程的狀態列加入目前的預設工作流程規模;修正下列問題:claude -p 文字輸出在回合因串流中途的 API 錯誤而中止時遺失已產生的回答、Fable 列顯示過時的「Requires usage credits」標籤、/model 選擇器將合併後的 Opus 列顯示為單純的「Opus」而非「Opus (1M context)」、新版本醒目標示範圍超出最新模型名稱、GNU screen 選取即複製時印出 base64、Remote Control 用戶端在模型切換/重新連線/組織檢查失敗後仍保留過時的 fast 模式狀態、Windows 上的 CLAUDE_CODE_GIT_BASH_PATH 在路徑並非 bash/sh 二進位檔時直接結束或被當作 bash 使用(現在會忽略並顯示警告)、Vim 模式在空白提示下按 ← 無法從 NORMAL 模式返回 agent 檢視,以及螢幕閱讀器模式在每次按鍵時重寫整行輸入;改善「Remote Control is only available via api.anthropic.com」錯誤訊息,使其指出造成此情況的設定,並讓 claude --teleport 在不符時顯示目前 checkout 指向的儲存庫。v2.1.220(7月25日): 僅有錯誤修正與可靠性改善,沒有面向使用者的功能、設定、指令或定價變更。擷取於2026年7月25日。 ↩

  28. Claude Code CHANGELOG,2.1.248、2.1.250 與 2.1.251 各節,擷取於2026年8月30日。npm 於2026年8月27日 20:35 UTC 發布 2.1.248,同日 22:27 UTC 發布 2.1.250(其章節內容僅為逐字的「Bug fixes and reliability improvements」),並於2026年8月28日 15:34 UTC 發布 2.1.251(dist-tag latest:2.1.251);2.1.249 從未在 npm 上發布。2.1.248 原文:「Added --restricted (or CLAUDE_CODE_RESTRICTED=1): removes the built-in tools that run commands or code and WebFetch (unless named in --tools), keeps file tools inside the working directory, refuses bypassPermissions, and ignores user, project and local settings files」;「Added experimental.cacheTtl ("5m" or "1h") to agent frontmatter: a per-agent prompt cache TTL used when no subagent TTL setting is configured」;「Added claude self-hosted-runner --client-label <label> (or SELF_HOSTED_RUNNER_CLIENT_LABEL) to override the label the runner registers with (default: hostname)」;「Added server-managed settings diagnostics: a startup warning when the settings fail to load, and a /doctor and /status line explaining a load failure or why they weren’t fetched (Bedrock/Vertex/third-party provider, custom ANTHROPIC_BASE_URL)」;「Added /usage-credits for Enterprise organizations billed through AWS Marketplace, self-serve Enterprise, and Enterprise trials, so members can request a higher usage limit from their admin」;

    「Added cross-session messaging (SendMessage / ListAgents) between sessions on the same machine on Bedrock, Vertex, and Foundry, and when telemetry is disabled」;桌面版保留期修正:「the transcript cleanup now keeps desktop-written sessions while they are in the app (unless org policy manages retention); the new desktopSessionCleanupPeriodDays setting caps the exemption」;「Improved managed settings: client-side timeout, MCP startup-mode, and stream-watchdog env vars no longer trigger the settings-approval prompt」;「Changed /loop: self-paced dynamic mode and the no-prompt autonomous default are now always available, including on Bedrock/Vertex/Foundry」;「Improved the Workflow tool’s prompt footprint: its description is now about 1k tokens instead of 5.7k, with the script-writing reference moved into a bundled workflow-authoring skill」;以及上傳修正:「Fixed /ultrareview and locally seeded cloud sessions uploading uncommitted edits to prod.env-style and *.tfvars files, or to editor swap, temp, and backup copies of credential files (e.g. key.pem.tmp, id_rsa.swo); they now stay on your machine」。

    2.1.251 原文:「Added PreModelSwitch and PostModelSwitch hook events (block, confirm, or annotate a model switch); SessionStart resume hooks now receive session staleness and the estimated re-cache cost」;「Added live streaming of a foreground subagent’s tool calls and results to Remote Control clients (background subagents, the default, still show status only)」;「Added a Spend limit bar to /usage and a rate_limits.spend_limit status line field for developers behind a Claude apps gateway with spend limits」;「Added a per-session prompt-cache line to /cost (hit ratio, misses, tokens re-cached, warm/cold) and a matching prompt_cache object for status line scripts」;「Added attach, logs, stop, respawn, and rm to claude --help; the --resume message for a running background session now names the exact claude attach <id> command」;「Changed Claude in Chrome so browser actions always go through Claude Code’s permission checks, including in sessions with telemetry disabled, which previously used the Chrome extension’s own prompts」;「Changed CLAUDE_CODE_SUBAGENT_MODEL to set the default subagent model rather than override everything: an agent definition’s model: and an explicit per-spawn model now take precedence over it」;「Changed the default model for seat-based Enterprise subscriptions to Opus 5, matching other premium plans」;「Changed /effort to save your default effort level per model, so each model keeps its own setting when you switch」;

    「Changed server-managed settings that terminate sandbox TLS, route sandbox traffic through your own proxy, inject credentials, or weaken sandbox isolation to require approval before they apply」;「Changed ANTHROPIC_CUSTOM_HEADERS from managed or project settings to require approval when it sets a credential, org/tenant, routing, or API-behavior header (e.g. Authorization, Host)」;「Changed project-level .claude/settings.json env to no longer set CLAUDE_CONFIG_DIR, CLAUDE_CODE_TMPDIR, or TMPDIR/TMP/TEMP; set them in your shell, user, or managed settings instead」;「Fixed /usage-credits for Team and Enterprise members whose admin set the org’s usage-credit limit to $0: it now offers to ask the admin instead of saying a cap was reached」;安全性修正原文:「Fixed file tools (Read, Write, Edit) following a symlink swapped inside the working directory after the permission check, which could read or write outside the approved location」;「Fixed plugin commands declared in a marketplace entry being able to point outside the plugin directory; such paths are now rejected with a path-traversal error」;「Fixed Bash permission checks auto-approving commands that assign an arithmetic expression to an integer shell variable (e.g. OPTIND=1/0, RANDOM=2+2); these now prompt for approval」;「Fixed Grep and Glob not applying Read(...) deny rules to files reached through a symlinked search path」。 ↩↩↩

  29. Hooks 參考文件,擷取於2026年8月30日。PreModelSwitch:「Runs before Claude Code applies a model switch that you or a client requested」;「PreModelSwitch requires Claude Code v2.1.251 or later」;它會在 /model <name> 與選擇器、/config 中的 Model 設定、會變更工作階段模型的 fast-mode 切換,以及 SDK/Remote Control 的 set_model 或 apply_flag_settings 請求時執行,但不會在「for switches it makes on its own, such as an automatic model fallback or restoring the model when you resume a session. Those changes reach PostModelSwitch only」的情況下執行;「Claude Code compares the matcher against the canonical name of the model the session is switching to, ignoring any [1m] suffix」,而當它「can’t determine a canonical name for the target」時,「it runs every PreModelSwitch hook regardless of matcher」;決策控制:結束代碼 2 或 decision: "block" 會取消切換,permissionDecision 接受 "allow"、"deny" 與 "ask";命令型 hook 的預設逾時在 UserPromptSubmit、PreModelSwitch 與 PostModelSwitch 上降為 30 秒,且「On PreModelSwitch, a hook canceled at its timeout blocks the model switch.」

    PostModelSwitch:「Runs after the session’s model changes」;「It can’t block, because the model has already changed」;它屬於「Claude Code adds plain-text stdout as context that Claude can see and act on」的事件之一,並「with the next request after the switch」送達;其輸入新增了 source 值 "auto" 與 "resume"。SessionStart 恢復欄位:「When source is "resume" or "fork" and the transcript contains at least one response from Claude, SessionStart hooks also receive the four fields below」;「These fields require Claude Code v2.1.251 or later」:seconds_since_last_response、context_tokens、prompt_cache_likely_expired、estimated_cache_write_usd。 ↩↩↩

  30. Claude Code 版本說明 v2.1.266(2026年9月8日)、v2.1.267(9月9日)、v2.1.268(9月10日)、v2.1.269(9月11日)、v2.1.270(9月12日)、v2.1.271(9月14日)及 v2.1.272(npm 於9月14日發布,GitHub 版本於9月15日 00:42 UTC 發布),以及2026年9月15日的正式 CHANGELOG – 七個版本的說明內容與其 CHANGELOG 章節完全一致。9月15日(約 13:15 PT)的 npm dist-tags:latest 2.1.272、next 2.1.273、stable 2.1.236;2.1.273(9月15日 18:06 UTC 發布)沒有 GitHub 版本,也沒有 CHANGELOG 章節,因此其內容未收錄於此;2.1.263 仍只寫著「Bug fixes and reliability improvements」– 從未補上任何說明。以下內容的出處(引述處皆為原文):/output-style 的回歸(”Added /output-style [name] to list and switch output styles, including over Remote Control and in cloud and other headless sessions”,v2.1.269);claude plugin eval(”run a plugin’s eval suite against Claude Code and get scored, reproducible results (JSON + HTML report)”,v2.1.269);Claude Code Remote 工作階段中的 fast mode(”cloud and self-hosted runners: the host’s fast-mode setting or /fast typed in the session applies where your organization allows it”,v2.1.271)以及 /fast off 的修正;

    maxEffortLevel 設定(”top-level or per model under modelSettings: caps the effort level on every provider, including Bedrock, Vertex and Foundry; users can still pick a lower level”,v2.1.267);--system-prompt-snapshot off(v2.1.267);v2.1.267 的 prompt-cache 穩定性修正批次(恢復工作階段時的工具清單、工具描述與 MCP 宣告文字的改寫;/model 切換時重新傳送每一個工具定義,署名文字改為對話備註;--system-prompt/--append-system-prompt 工作階段只記錄一次提示詞與工具定義;工作階段中途加入的 MCP 與 plugin 工具改為延遲載入的定義);固定預設 effort 模型(Opus 4.7、Opus 4.8、Fable 5;v2.1.267)上 effort: frontmatter 的修正;marketplace 反斜線隔離修正(v2.1.267);任務追蹤工具的允許清單(「Changed the task-tracking tools (TaskCreate/Get/Update/List, TodoWrite) to be offered only on」Claude 3.x、Opus 4.0 至 4.7、Sonnet 4.0 至 4.6 與 Haiku 4.5,並附「set CLAUDE_CODE_ENABLE_TODO_TOOLS=1 elsewhere」,v2.1.268);符號連結目錄與 env -C/eval 拒絕規則的修正(v2.1.268);WebFetch 與 Artifact 規則的拆分(”Changed plain WebFetch deny and ask rules to no longer apply to Artifact tool reads and updates; use an Artifact rule (or WebFetch(domain:claude.ai)) to block or gate them”,v2.1.268);/plugin 變更於選單關閉時生效(v2.1.268);WebFetch 的 300 秒期限與 CLAUDE_CODE_WEBFETCH_DEADLINE_MS(v2.1.268);gatewayInternalNetworks、空白 allow_cidrs 的警告,以及 gateway pricing: 費率同步(v2.1.268),再加上 multiplier 可高於 1 並最高至 10(v2.1.271);

    ${VAR} 與 git URL 的機密防護修正(v2.1.268);claude auth status --json 中的 configDirectory(v2.1.268);第三方 ANTHROPIC_BASE_URL HTTP 400 迴歸問題的修正(v2.1.268);bashEditDiffEnabled(v2.1.269);署名提醒的修正(”Fixed the attribution reminder overriding a CLAUDE.md or memory rule against commit and pull request attribution; lines set by managed settings still apply”,v2.1.269);環境變數 OTEL_METRICS_INCLUDE_REPOSITORY、CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS(1-256)、CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS(預設 3 秒)及 CLAUDE_CODE_BG_TASKS_REPORT_RUNNING(v2.1.269);v2.1.247 鍵盤迴歸問題的修正,以及透過 SSH 的 kitty 查詢鍵盤支援(v2.1.269);Edit()/tee、Bash(tee:*) 與開頭 ! 的範圍判定修正(v2.1.269);啟用沙箱的 auto mode 下,Bash、PowerShell 與 Monitor 的逐命令 allowed_domains(v2.1.271);omitClaudeMd agent frontmatter 與 --agents JSON(v2.1.271);auto mode 的行內 ! 與 subagent 交還機制的變更(v2.1.271);claude plugin install/update 的 --accept-command <sha256>(v2.1.271);--resume 在不同模型系列間保留 [1m](v2.1.271);無法讀取的 managed-mcp.json 改為預設拒絕(v2.1.271);fmt/column、萬用字元展開、變數宣告旗標與 blockReadsOutsideWorkingDirectories 檢查器的修正(v2.1.271);以及 Markdown artifacts 改以具樣式的文件頁面呈現,artifact 監看數提高至 10(v2.1.271)。v2.1.266 只有一行(CLAUDE_CODE_USE_GATEWAY 迴歸問題的修正),v2.1.270 只有一行(v2.1.269 git 提示迴歸問題的修正),而 v2.1.272 僅寫著「Bug fixes and reliability improvements」。 ↩

  31. Claude Code v2.1.280 版本說明(npm 發布於 2026年9月22日 15:44 UTC;GitHub release 為 16:38 UTC),以及2026年9月22日與9月23日的正式 CHANGELOG。本指南中所有 v2.1.280 項目的來源。9月23日的 npm dist-tags:latest 與 next 為 2.1.280,stable 為 2.1.267;2.1.279 從未發布。關鍵引文:”新增 Claude Opus 5.5(claude-opus-5-5),現為預設的 Opus 模型”,並具備 “1M context、每 Mtok $4/$20,快取讀取每 Mtok $0.20”;”將 Pro 與 Team Standard 方案的預設模型從 Sonnet 改為 Opus,與 Max、Team Premium 和 Enterprise 一致”;”修正了當安全檢查未給出答案時,auto 模式不停歇地反覆拒絕動作的問題;重試現在會退避,連續十次後回合會停止並顯示訊息”。 ↩

  32. Claude Code 正式 CHANGELOG,2.1.293 至 2.1.296 各節,擷取於2026年10月11日,以及同日讀取的 @anthropic-ai/claude-code npm registry 中繼資料:2.1.293 發布於2026年10月7日 17:18 UTC,2.1.294 為10月8日 03:42 UTC,2.1.295 為10月8日 18:22 UTC,2.1.296 為10月9日 16:58 UTC;dist-tags 的 latest 與 next 為 2.1.296,stable 為 2.1.287。GitHub 的發行說明(發布於 18:10、05:03、19:48 與 19:28 UTC)分別含有 56、2、143 和 79 個條目,與 CHANGELOG 完全一致。本指南中所有 v2.1.293 至 v2.1.296 項目的來源。

    關鍵引文:「新增 Claude Haiku 5.5(claude-haiku-5-5),現為 Anthropic API 上的預設 Haiku 模型」,具備「1M 上下文,每 Mtok $0.10/$0.50(超過 100K 的提示為 $0.50/$2.50)」;「為命令與 HTTP hooks 新增 onFailure: "block":無法啟動、逾時或以非預期代碼結束的 hook 會阻擋該動作,而不是放行」;「將預先傳送的 MCP 工具描述與 MCP 伺服器指示的預設上限從 2,048 個字元改為 4,096 個字元」;「模型透過工具搜尋載入的 MCP 工具描述改為在 16,384 個字元處截斷,而非 2,048」;「將 subagents 改為最多從 skills 欄位預載 32 個 skills,每個僅載入一次」;「在 subagent frontmatter 與 --agents 定義中新增 autoCompactWindow,讓 subagent 能比主對話的視窗更早自動壓縮」;「更新 /cost、狀態列、--max-budget-usd 與 SDK 的費用數字,將 Sonnet 5.5 的快取讀取定價為每百萬 token $0.10(原為 $0.20)」;「為 Read 工具新增 allow_large 選項」;「還原 2.1.281 的自動模式拒絕訊息變更」;「修正在受管理設定將 forceLoginMethod 設為 gateway 但未設定 forceLoginGatewayUrl 的機器上,已儲存的 Claude apps gateway 登入會被忽略的問題(2.1.295 的回歸)」。 ↩

  33. Claude Code 文件,擷取於2026年10月11日。Hooks:onFailure 是「hook 失敗時,觸發該 hook 的動作是否繼續進行:"continue" 或 "block"……需要 Claude Code v2.1.295 或更新版本」;它所計入的失敗包括「無法啟動」、「結束代碼不是 0 或 2」、「HTTP 錯誤」、「逾時」與「無效輸出」;「設為 "block" 時,失敗的效果等同於該事件上的結束代碼 2,但在 PermissionRequest 上則會拒絕該請求」;「此欄位對」Stop、SubagentStop、TaskCompleted、TeammateIdle 以及背景(async、asyncRewake)命令 hooks「沒有作用」。環境變數:CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS「當 API 以 529 過載錯誤拒絕請求時,重試之間退避的起始延遲毫秒數(預設:500)……請以純數字提供 500 至 32000 之間的整數毫秒……需要 Claude Code v2.1.292 或更新版本」;CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS「未設定時,等待沒有上限。需要 Claude Code v2.1.295 或更新版本」;CLAUDE_CODE_WEB_SEARCH_REFILLS_PER_HOUR「在互動式終端機工作階段中預設為 100。在非互動式工作階段中預設為 0,即關閉補充」;CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS「Claude 使用 allow_large 參數進行的讀取,在上下文視窗仍有空間時可以超過此上限」;VERTEX_REGION_CLAUDE_HAIKU_5_5「於 v2.1.293 新增」;沒有 CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS 或 CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL 的條目。2026年11月25日重新讀取;措辭已有變動的引文,改以當日的措辭呈現。

    Sub-agents:skills 欄位預載「清單中最前面的 32 個不同名稱」;每次呼叫的 effort 參數「會覆寫 effort 欄位,並在 subagent 恢復時持續生效……需要 Claude Code v2.1.292 或更新版本」;autoCompactWindow 不在所列的 frontmatter 欄位之中。狀態列:agentType「需要 Claude Code v2.1.293 或更新版本」。MCP:「Claude Code 預設會向 stdio 伺服器要求該修訂版。若要讓 stdio 通道伺服器維持在較早的交握方式,請將 MCP_PROTOCOL_NEGOTIATION 設為 legacy,這會讓每個伺服器都維持在該方式。」Plugin CLI 參考:claude plugin install 接受 --marketplace <source>,「需要 Claude Code v2.1.292 或更新版本」。Mods 參考:仍寫明「截至 v2.1.290」;沒有 $.ui.notify 或 prompt.autocomplete 的條目。 ↩

  34. Claude Code v2.1.233 版本資訊,2026年8月14日。新增:--worktree/claude agents 支援 GitLab MR(!N)、可選擇啟用的 forward_user_identity gateway 設定、CLAUDE_CODE_TOOL_MEMORY_LIMIT(Bash 指令的 Linux cgroup)、CLAUDE_CODE_WEBFETCH_CACHE_TTL_MS;在 Opus 4.8、Sonnet 5、Fable 5、Mythos 5 及更新的模型上預設移除 todo/任務追蹤工具(CLAUDE_CODE_ENABLE_TODO_TOOLS=1 可還原);修正 v2.1.232 在 Windows 上 auto 模式核准的回歸問題,並還原 v2.1.232 的 Cygwin 符號連結與輸入重新導向權限變更,待推出範圍更窄的版本;NTLM \??\ 路徑驗證修正、MCP v2 重新連線修正、Notification hook 與 Linux 閒置 CPU 修正、內建 skill 別名遮蔽修正。擷取於2026年8月15日。 ↩

  35. Claude Code v2.1.163 版本說明 與 Claude Code Changelog(正式版)。2026年6月4日;changelog 從 v2.1.160 直接跳至 v2.1.163,未發布 161/162。新增 requiredMinimumVersion/requiredMaximumVersion 受管設定(版本不在核准範圍內即拒絕啟動)、/plugin list 的 --enabled/--disabled 篩選器、Stop/SubagentStop 的 hookSpecificOutput.additionalContext(提供非錯誤回饋並讓回合繼續進行)、/btw 的「c 複製」原始 markdown、skills 的 \$ 字面美元符號跳脫,以及 stdio MCP 伺服器在 --resume 時收到工作階段的 CLAUDE_CODE_SESSION_ID。修正項目包括:claude -p 在永不結束的背景命令上卡住、Bedrock/Vertex/Foundry 的 claude -p 在 CI=true 下要求 Anthropic 金鑰、v2.1.154 的 $TMPDIR 回歸問題破壞 bazel/受 EDR 保護的 Go、Windows 上 OneDrive/唯讀 session-env 的 EEXIST、組織受管權限規則延遲套用、背景工作階段在更新後遺失任務、hook if: "Bash(...)" 過度比對 $()/$VAR,以及 ~ 路徑拒絕規則未能封鎖 $HOME 參照。擷取於2026年6月4日。 ↩

  36. Claude Code v2.1.152 版本說明、Claude Code v2.1.153 版本說明、Claude Code v2.1.154 版本說明,以及 Claude Code Changelog(正式版)。2.1.151 從未發布;2026年5月23日那個僅含基礎架構變更的版本是 v2.1.150。v2.1.152(2026年5月27日)推出 /code-review --fix 套用至工作樹、disallowed-tools skill/command frontmatter、/reload-skills、SessionStart hook 的 reloadSkills/sessionTitle 輸出、MessageDisplay hook 事件、pluginSuggestionMarketplaces 受管設定、--fallback-model 工作階段中切換、移除 auto-mode 的選擇加入、vim / 反向歷史搜尋,以及渲染、效能與可靠性方面的修正。v2.1.153(2026年5月28日)為 plugin marketplace 新增 skipLfs、讓 /model 儲存為新工作階段的預設值(以 s 表示僅限本工作階段,並以 modelPicker:thisSessionOnly 按鍵綁定取代 modelPicker:setAsDefault)、在狀態列環境變數中加入 COLUMNS/LINES;macOS 背景 agent 會保留「隱私權與安全性」授權;另有25項以上的修正,涵蓋有狀態 MCP 的 tools/list 重連迴圈、自訂閘道的 OAuth 憑證外洩、subagent 的 MCP 政策強制執行、Windows 安裝程式 / 更新通道修正,以及背景工作階段附加的可靠性。

    v2.1.154(2026年5月28日)將 Opus 4.8 設為預設模型並預設採用 high effort,新增 /effort xhigh 等級,推出可透過 /workflows 在背景協調數十至數百個 agent 的動態 workflow,讓 Opus 4.8 的 Fast mode 以2倍標準費率換取2.5倍速度,將精簡系統提示設為除 Haiku/Sonnet/Opus 4.7 及更早版本外所有模型的預設值,將選擇題提示收斂至真正無法自行決定的情況,將 /simplify 回復為僅做清理的審查(與 /code-review --fix 的抓錯流程分開),將 /effort 滑桿重新標示為「Faster」/「Smarter」,新增 claude agents 的 ! <command> 背景 shell 工作階段以及 claude --bg --exec '<command>',允許外掛宣告 defaultEnabled: false,在 /plugin Discover 中將建議的外掛釘選至目前目錄,讓串流工具執行永遠開啟,將 CLAUDE_CODE_SESSION_ID 與 CLAUDECODE=1 傳入 stdio MCP 子程序環境,將未核准的 .mcp.json 伺服器標示為 ⏸ Pending approval 而非自動連線,並棄用 CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE(6月1日移除;請改用 /model claude-opus-4-6[1m] 再執行 /fast on)。擷取於2026年5月28日。 ↩

  37. Claude Code的正式CHANGELOG,2.1.299章節,擷取於2026年10月14日,以及同日讀取的@anthropic-ai/claude-code之npm registry中繼資料:2.1.299於2026年10月14日00:23 UTC發布,2.1.300於14:27 UTC發布;dist-tags為latest 2.1.299、next 2.1.300、stable 2.1.287;npm上沒有2.1.297或2.1.298,CHANGELOG也沒有這兩版或2.1.300的章節。GitHub發行版(02:49 UTC)包含190條項目,與CHANGELOG完全相同。本指南中所有v2.1.299項目的來源。重點引述:「終端機新增閒置壓縮:超過200K token的對話若閒置約54分鐘,會在其一小時提示快取過期前先行壓縮,讓您的下一則訊息不必重新處理全部內容」;「新增CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS以變更閒置壓縮的200K token下限;在settings.json中設定"idleCompaction": false可將其關閉。兩者皆需v2.1.290或更新版本」;「新增CLAUDE_CODE_DISABLE_FILE_MENTIONS環境變數:Claude只會取得@檔案提及的路徑,再以其檔案工具讀取,而非直接取得檔案內容」;「MCP允許規則現在只涵蓋其指名的伺服器:mcp__a不再允許名為a__b或a_的伺服器;請以伺服器完整的正規化名稱寫成mcp__<server>__*」;

    「agent的tools:清單現在只納入指名MCP伺服器的工具;名稱含有__的伺服器請寫成mcp__<whole name>__*」;「來自Anthropic位於api.anthropic.com的第一方MCP伺服器之MCP工具描述與伺服器指示,現在會完整送達Claude,而不再於4,096個字元處截斷」;「雲端工作階段與Remote Control的MCP連接器,在未擷取任何旗標的安裝上,現在預設協商MCP協定版本2026-07-28;可透過MCP_PROTOCOL_NEGOTIATION=legacy選擇退出」;「UserPromptSubmit hooks現在會在skill或自訂斜線命令展開之前執行,因此封鎖提示的hook現在也會一併阻止其內嵌的shell命令」;「turn.start mod hook現在也會收到subagents與隊友的回合,而不只是主迴圈的回合;可透過e.agentId區分(主迴圈上不存在此欄位)」;「修正了對不執行rm的shell -c指令碼仍跳出rm提示的問題。在Claude Code無法讀取的指令碼中於執行期組成的rm,不再觸發提示,除非設定CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT=1」;

    「為claude self-hosted-runner orchestrator新增--shutdown-drain-sec:收到SIGTERM時停止輪詢,並給予進行中的輪詢與執行中的spawn hooks至多該秒數的時間完成」;「為claude plugin eval新增--disallow-tools與disallowed_tools案例欄位,可將Agent等特定內建工具排除在eval執行之外」;「新增關閉Claude Desktop的Code分頁中署名區塊的支援:在Claude apps gateway的code政策之env中設定CLAUDE_CODE_ATTRIBUTION_HEADER=0」;「在agent檢視中新增/effort與/fast,用於設定新工作階段的起始值;在該處單獨輸入/model、/effort或/fast現在會開啟選擇器」;「當plugin hook無法接收動作或無法回傳其判定時,該hook可封鎖的動作現在會被拒絕而非放行;已執行的工具,其結果會被扣留」;「修正2.1.296的回歸問題:雲端與無頭工作階段在重新啟動後恢復時,若恰好有新訊息抵達,可能會將已核准的工具呼叫執行兩次」;「網路安全防護通知不再要求使用者申請Cyber Verification Program」。 ↩

  38. Claude Code 文件,擷取於2026年10月14日。設定參考:idleCompaction,「阻止 Claude Code 壓縮您已離開的冗長對話」;「符合條件的對話預設會啟用閒置壓縮。若要關閉,請將 idleCompaction 設為 false。需要 Claude Code v2.1.290 或更新版本」。環境變數:CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS「對話套用閒置壓縮的脈絡大小,以 token 計(預設值:200000)」,低於 100000 的值會被提高至 100000;CLAUDE_CODE_DISABLE_FILE_MENTIONS「需要 Claude Code v2.1.299 或更新版本」,在專案與本機設定中會被忽略;CLAUDE_CODE_ATTRIBUTION_HEADER「設為 0 可省略署名區塊」;CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS「當 API 以 529 過載錯誤拒絕請求時,該請求各次重試之間退避時間的上限,以毫秒計(預設值:32000)」;仍然沒有 CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL 或 CLAUDE_CODE_STRICT_INLINE_SHELL_RM_PROMPT 的條目。子代理:autoCompactWindow 現已列為 frontmatter 欄位,「100000 以上的 token 數」;tools 與 disallowedTools「也接受整個 MCP 伺服器的項目」。2026年11月25日重新讀取;措辭已有變動的引文,改以當日的措辭呈現。

    Mods 參考:仍然標示「截至 v2.1.290」;「在 skill.prompt 上,e.source、e.pluginName、e.path、e.frontmatter 與 e.frontmatterProblem 需要 Claude Code v2.1.299 或更新版本」;turn.start 列於事件清單中;沒有 $.prompt.media、$.session.identity、tabular 或 serverToolUses。Plugin evals:「在 v2.1.299 之前,這類執行是依其已產出的內容評分」;沒有 --disallow-tools。MCP:限制清單仍寫著「伺服器指示,以及預先載入之工具的描述:4,096 個字元」,沒有第一方例外;在 v2 執行階段上,Claude Code「會詢問 HTTP、stdio 與 claude.ai 連接器伺服器是否支援較新的修訂版,並對支援的伺服器使用該版本」。權限:「允許規則只在字面的 mcp__<server>__ 前綴之後才接受工具名稱 glob。伺服器區段不得含有 glob,如此規則才會指向您所設定的特定伺服器。」Hooks:有描述 CLAUDE_CODE_DISABLE_FILE_MENTIONS(「您相符的 PreToolUse hooks 會執行」);沒有說明 UserPromptSubmit 會在 skill 或命令展開之前執行。 ↩

  39. Claude Code 正式 CHANGELOG,2.1.300 章節,擷取於2026年10月14日(21:40 PT),以及同時讀取的 @anthropic-ai/claude-code npm 註冊表中繼資料:2.1.300 於10月14日 14:27 UTC 發布;dist-tags 為 latest 2.1.300、next 2.1.300、stable 2.1.292(當天早上還是 2.1.287)。GitHub 發行版(18:24 UTC)包含 88 個條目,與 CHANGELOG 完全相同。本指南中每一項 v2.1.300 項目的來源。關鍵引述:「在 AWS 上的 Claude Platform 新增 /advisor;在您透過 /advisor、advisorModel 或 --advisor 選定之前不會有任何 advisor 執行,而 CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1 會將其關閉」;「為 mod 的提示裝飾新增 virtualText:繪製在提示框中的文字,永遠不會進入草稿或送出的提示」;「為 mods 新增 $.ui.view({ agentId }):在您要求時於主檢視中顯示某個代理的逐字稿,而 $.ui.view({}) 會返回」;「新增 prompt.change mod hook,在提示框文字未經鍵入編輯而變更時觸發:召回的歷史條目、清除、復原,或是 plugin 的填入」;「在 OpenTelemetry api_request 事件中新增 cache_creation_5m_tokens 與 cache_creation_1h_tokens,依存留期區分快取寫入」;

    「在追蹤 span 中新增 OpenTelemetry GenAI 語意慣例屬性,例如 gen_ai.provider.name、gen_ai.conversation.id、gen_ai.tool.name 與 error.type」;「將傳送至 api.anthropic.com 的大型請求改為即使停用遙測也使用 gzip 壓縮;設定 CLAUDE_CODE_GZIP_REQUEST_BODIES=0 可將其關閉」;「變更 hooks:來自 PreToolUse 與 PermissionRequest hooks 的 updatedInput 現在會像 Claude 自身的輸入一樣進行驗證:未知的鍵會被捨棄,而被工具拒絕的輸入會使呼叫遭到拒絕」;「從 claude remote-control 移除原本沒有作用的 --sandbox 與 --no-sandbox 旗標;現在傳入任一旗標都會以錯誤結束。請在設定中設置 sandbox.enabled 以沙箱化工作階段」;「變更本機工作階段逐字稿,使其也記錄每個 API 請求的系統提示、工具與參數,讓您選擇分享的逐字稿能精確重現請求」;「變更結束行為:背景命令在被要求停止 1.5 秒後仍在執行時將被強制終止」;「修正在背景命令仍在執行時結束,SessionEnd hooks 有時不會執行的問題」;「修正 claude daemon stop --any 在卡住的背景服務仍在執行時仍印出「stopped」的問題:現在會等待、強制終止該服務,若服務仍在則以結束代碼 1 回報」。 ↩

  40. Claude Code 正式 CHANGELOG,2.1.301 與 2.1.302 兩節,擷取於2026年10月17日(太平洋時間 15:40),以及同時讀取的 @anthropic-ai/claude-code npm registry 中繼資料:2.1.301 於10月15日 14:34 UTC 發布,2.1.302 於10月16日 16:48 UTC 發布;dist-tags latest 為 2.1.302、next 為 2.1.302、stable 為 2.1.292。GitHub 發行版 v2.1.301(19:22 UTC,51 項)與 v2.1.302(20:53 UTC,63 項)與 CHANGELOG 完全一致。本指南中所有 v2.1.301 與 v2.1.302 項目的來源。重點引文,2.1.302:”Changed claude -p and Agent SDK sessions with no permission mode to start in default mode on third-party providers, with telemetry off or on a fresh install; --permission-mode auto keeps auto”;”Changed fork subagents (subagent_type: "fork") to be on by default in claude -p, the Agent SDK, the desktop app and VS Code, as they already are in the terminal; CLAUDE_CODE_FORK_SUBAGENT=0 turns them off, and claude mcp serve never offers them”;”Changed the desktop app and VS Code to always run the main conversation’s subagents in the background, as the terminal does, rather than let Claude choose; a subagent’s own Agent calls in claude -p, the Agent SDK, the desktop app and VS Code now run in the foreground by default”;

    “Changed prompt and agent hooks so that at most 12 of one event run at a time; the rest wait their turn”;”Added CLAUDE_CODE_AUTO_MODE_MODEL to choose the model the client-side auto mode classifier uses; it does not change the model for server-side auto mode”;”Added an Idle compaction row to /config for turning idle compaction off or back on; the notices shown after an idle compaction now say how to turn it off”;”Added a notice to /design-sync and /design-login that standalone Claude Design (claude.ai/design) closes by December 14, 2026”;”Fixed the Read tool loading an image file of any size, or a pipe or device named like an image, entirely into memory; image sources over 128 MB are now refused”;”Improved auto mode with the server-side classifier: a conversation too long for the safety check is now compacted, instead of every checked tool call being denied”。

    2.1.301:”Added CLAUDE_CODE_RETRY_WATCHDOG_MAX_USAGE_LIMIT_WAIT_MS so unattended retry mode (CLAUDE_CODE_RETRY_WATCHDOG) ends a request at a usage limit that resets too far away instead of waiting”;”Added the % motion to vim mode: jump to the matching bracket, alone or with d/c/y”;”Added rows to a mod’s Input: a text field of several lines in the terminal, where Enter submits and Shift+Enter or a backslash before Enter starts a new line”;”Added classifier_verdict and permission_mode to OpenTelemetry tool_decision events, so auto mode classifier decisions can be told apart from permission rules”;”Added classifier_category to OpenTelemetry tool_decision events, naming the built-in rule a classifier block matched, when OTEL_LOG_TOOL_DETAILS=1“;”Fixed the fable (and best) model alias erroring on the Anthropic API when the newest Fable model is not available to your organization: Claude Code now retries once on the previous Fable model”;”Improved switching to a model with a smaller context window: a conversation too long for the new model is now summarized by the previous model first”;”Changed a mod hook’s .catch handler to run only when the hook throws or times out; events raised beneath the hook’s own calls now skip that hook without asking its .catch“;”Changed a mod’s $.env.set to resolve with {} once the variable is set or unset, or with { deny } saying why when the write is not made”。 ↩

  41. Claude Code 文件,擷取於2026年10月17日。互動模式:”% | Jump to the matching (), [], or {} bracket, starting from the next bracket on the current line when the cursor isn’t on a bracket. Requires Claude Code v2.1.301 or later” 以及 “d%/c%/y% | Delete, change, or yank from the cursor through the bracket that % jumps to”。VS Code 頁面列出了 LaTeX 數學式渲染。仍停留在 2.1.302 之前規則的頁面:權限模式表格(”claude -p or the Agent SDK | default in sessions that fetch feature flags. In sessions that don’t, such as on a third-party provider or with telemetry off, auto with Claude Code v2.1.285 or later”);環境變數頁面(CLAUDE_CODE_FORK_SUBAGENT “is on by default in interactive sessions only. Set to 1 to turn it on in claude -p and the Agent SDK as well, or 0 to turn it off in every kind of session”);以及 subagents 頁面(”Fork mode is off in non-interactive mode with -p and in the Agent SDK unless you turn it on”)。

    文件中完全未提及的項目:CLAUDE_CODE_AUTO_MODE_MODEL、CLAUDE_CODE_RETRY_WATCHDOG_MAX_USAGE_LIMIT_WAIT_MS、tool_decision 的 classifier_verdict、permission_mode 與 classifier_category 屬性(監控頁面一項都未列出)、/config 的 Idle compaction 列、Claude Design 的關閉日期,以及 12 個 hooks 的上限(hooks:”All matching hooks run in parallel”)。mods 文件現已自成一節:概覽、參考(”Entries cover the Claude Code CLI and the Desktop app as of v2.1.290, and the VS Code extension as of v2.1.299”)、事件(.catch:”When guard throws or times out on a Bash call, Claude Code calls the handler with the same event”,未納入 v2.1.301 的重入規則)、API,以及介面;這些新頁面皆未提及 Input 的 rows、$.env.set、nothing-to-fork、virtualText、$.ui.view、prompt.change、$.prompt.media 或 $.session.identity。advisor 頁面仍寫著該工具 “is not available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry”。 ↩

  42. Hooks 參考,Claude Code 文件,擷取於2026年10月21日,並於2026年11月25日重新讀取;此處每一則引文皆為11月25日的措辭。JSON 輸出:「除了 JSON 物件之外,不要在 stdout 印出任何內容。」;「通用欄位(例如 continue)列於下表。每個事件都接受這些欄位,但有些事件會捨棄它們,或將 systemMessage 送往對話記錄以外的位置。各事件的章節會分別說明。」;「最上層的 decision 與 reason 由部分事件用來阻擋或提供回饋。」;「hookSpecificOutput 是一個巢狀物件,供需要更細緻控制的事件使用。它需要一個設定為事件名稱的 hookEventName 欄位。」通用欄位表:continue「若為 false,Claude 會在 hook 執行後完全停止處理。它不會封鎖 PreToolUse 的工具呼叫,因此若要封鎖,也請回傳 permissionDecision: "deny"」;stopReason「當 continue 為 false 時顯示給使用者的訊息。它會留在對話中,因此若對話繼續,Claude 會看到它」;suppressOutput「沒有作用」;systemMessage「顯示給使用者的警告訊息。在 Agent SDK 與 --output-format stream-json 輸出中,它可能以 SDKInformationalMessage 的形式送達」;terminalSequence「一段由 Claude Code 代您發出的終端機逸出序列,例如桌面通知、視窗標題或鈴聲。僅限 OSC 0/1/2/9/99/777 與 BEL。若值包含允許清單以外的任何內容,該欄位會被忽略。」,其限制為「Claude Code 只會在互動式工作階段中,且僅在其介面開啟時寫入該序列。在使用 -p 旗標的非互動模式與 Agent SDK 中,它會忽略此欄位。」continue: false 另有作用之處:「在 Stop 與 SubagentStop 等事件上,此欄位優先於結束代碼 2,因此 Claude 或該 subagent 會結束其回合」;「在 PreToolUse 上,無論有無此欄位,工具呼叫都會維持封鎖。」;TaskCreated:「Claude Code 會忽略來自此事件的 continue: false,Claude 會繼續工作。」結束代碼 0:「只有在您印出一個 JSON 物件(單行或多行皆可),且其周圍除空白字元外沒有其他內容時,您的 stdout 才會被視為 JSON 輸出」;「以 0 結束的 hook,其 stderr 絕不會讓 Claude 看到。」其他結束代碼:「帶有 Failed with non-blocking status code: 的 <hook name> hook error 通知,表示您的 hook 並未以 0 或 2 結束,且其 stdout 為純文字或空白。」;「若通知截斷了您的 stderr,請啟用除錯日誌」。在沒有 Git Bash 的 Windows 上失敗的 hooks:「未設定 onFailure 而失敗的 shell 形式 PreToolUse、PermissionRequest 或 PreSkillShellCommand command hook,反而可能封鎖該動作」;「hook 失敗時呼叫仍應繼續:在該 hook 中加入 "onFailure": "continue"」。計入的失敗:「MCP 失敗:mcp_tool hook 的伺服器未連線,或其工具回傳錯誤。」

    「modifications」一詞在該頁面僅出現於 ConfigChange 的說明文字中(「block unauthorized modifications to configuration files」),從未作為輸出欄位出現。結束代碼 0:「對大多數事件而言,Claude Code 會將 stdout 寫入除錯日誌,而不顯示在對話記錄中。例外是 UserPromptSubmit、UserPromptExpansion、SessionStart 與 PostModelSwitch,在這些事件中 Claude Code 會將純文字 stdout 加入為 Claude 可見並據以行動的脈絡。」JSON 輸出:「除了 JSON 物件之外,不要在 stdout 印出任何內容。對於非非同步的 hook,該處的其他文字(例如您的 shell 設定檔在啟動時回顯的一行)會讓 Claude Code 無法將該物件解讀為 JSON;「Hook JSON 沒有作用」一節說明如何找出並消除這些文字。」

    結束代碼 0 搭配 JSON:「Claude Code 會套用您的 hook 所印出的所有 JSON 輸出欄位,除非這些欄位阻擋或拒絕該動作,否則動作會照常進行。」其他結束代碼:「除非該 hook 屬於失敗即阻擋動作的類型,否則這是非阻擋性錯誤,因此您的 hook 並未停止該動作。」;「若要擷取 hook 的完整 stderr,而非通知所顯示的第一行,請啟用除錯日誌。」;而在輸出表中,任何其他結束代碼若搭配「通過結構描述驗證的 JSON 物件」,則為「成功。Claude Code 會忽略結束代碼,僅由欄位決定。對於失敗即阻擋動作的 hook,該次執行則視為失敗」。terminalSequence:「Claude Code 只會在互動式工作階段中,且僅當其介面顯示於螢幕上時寫入該序列。在使用 -p 旗標的非互動模式與 Agent SDK 中,它會忽略此欄位。」2026年11月10日重新讀取:該頁面現在在 stdout 會被採用的事件中新增了「PreCompact:您的 stdout 會成為壓縮摘要的指示」。 ↩↩↩↩↩

  43. Claude Code CHANGELOG,v2.1.311 至 v2.1.317(提交時間為 2026-10-26T21:51Z、10-27T20:23Z、10-30T01:06Z、10-31T01:01Z 與 11-03T01:25Z),以及對應的 GitHub 發行版本 v2.1.311(2026-10-26T21:51:23Z)、v2.1.312(10-27T20:24:20Z)、v2.1.314(10-30T01:06:26Z)、v2.1.316(10-31T01:01:35Z)與 v2.1.317(11-03T01:25:46Z),各版內容均與其 CHANGELOG 章節完全相同;npm 發布時間取自 npm view @anthropic-ai/claude-code time:2.1.311 為 2026-10-26T19:47:57Z、2.1.312 為 10-27T18:36:10Z、2.1.314 為 10-30T00:12:56Z、2.1.315 為 10-30T21:05:24Z(無 CHANGELOG 條目,亦無 GitHub 發行版本)、2.1.316 為 10-31T00:42:05Z、2.1.317 為 11-02T23:57:53Z;2026-11-02 當日的 dist-tags:latest 與 next 為 2.1.317,stable 為 2.1.311。原文摘錄,2.1.311:「將互動式終端機中的 ultrathink 改為透過 Anthropic 的 API,在 Opus 5.5、Sonnet 5.5、Haiku 5.5 與 Fable 5.1 上以 xhigh 強度等級執行該輪;若在 Claude 工作期間輸入,則提升該輪剩餘部分的強度」。2.1.316:「自2026年10月30日起棄用 Opus 4.8 的快速模式;將於2026年11月30日移除。移除後,Opus 4.8 上的快速模式請求會回傳錯誤,且不會回退至標準 Opus 4.8。請遷移至 Opus 5.5 以保留加速效果」。2.1.314:「新增 permissions.blockWritesOutsideWorkingDirectories:在所有權限模式下,Write、Edit 與 NotebookEdit 均拒絕工作目錄以外的路徑」。2.1.312:「將 prompt 與 agent hooks 改為每個工作階段最多同時執行 24 個(含 subagents),其中等待時間超過其事件逾時的最多 12 個;timeout 低於 1 秒者現在以 1 秒計」;「Claude Code 不再傳送 claude_code.safety_event OpenTelemetry 事件」。2.1.317:「在 OTel 指標、事件與 span 中新增 anthropic.plan、anthropic.seat_type、anthropic.provider 與 anthropic.custom_base_url」。 ↩↩↩

  44. 工具參考,Claude Code 文件,擷取於2026年11月10日。任務工具:「任務追蹤工具 TaskCreate、TaskGet、TaskUpdate、TaskList 與 TodoWrite,僅在 Opus 4.7、Sonnet 4.6、Haiku 4.5 及更早的模型上預設提供」,可用 CLAUDE_CODE_ENABLE_TODO_TOOLS=1 或 claude --allowedTools TaskCreate 選擇加入,且「在背景工作階段與雲端工作階段中,Claude Code 會在每個模型上提供相同的工具」。WebSearch:「互動式終端機工作階段的 WebSearch 呼叫上限為 200 次」;「在 Claude Code v2.1.290 或更新版本上,互動式終端機工作階段的上限會以每小時約 100 次的速度補充」;「此上限可以調高,但無法關閉」;「在使用 -p 的非互動模式與 Agent SDK 中,此上限以每個回合計算,而非每個工作階段。」 ↩

  45. Hooks 參考,Claude Code 文件,擷取於2026年11月10日。比對器:「只包含字母、數字、_、-、空格、, 與 |」的比對器會以「完全相符的字串,或完全相符字串的清單」進行比對,而且「.* 是必要的:像 mcp__memory 或 mcp__brave-search 這樣的比對器只包含完全比對字元,因此會被當作完全相符的字串比對,不會比對到任何工具。」事件:Setup 會在「您以 --init-only 啟動 Claude Code,或在 -p 模式下以 --init 或 --maintenance 啟動時」觸發,並且「只有在您以 --init-only 啟動 Claude Code,或在使用 -p 旗標的非互動模式下以 --init 或 --maintenance 啟動時才會觸發」;FileChanged:「matcher 欄位指定要監看哪些檔名」;WorktreeRemove:「若目錄在之後仍然存在,任何非零結束代碼都會讓 worktree 移除失敗」;PermissionRequest:「不會被讀取為決定。請改為透過 decision 物件拒絕」;PermissionDenied:「使用 JSON hookSpecificOutput.retry: true 告知模型可以重試」;InstructionsLoaded:「結束代碼會被忽略」。輸出:「PreCompact:您的 stdout 會成為壓縮摘要的指示」。PreToolUse 決定:「"allow" 會略過權限提示,但任何模式都不會自動核准的操作以及從網路路徑讀取的操作除外」,至於原因:「對於 "allow" 與 "defer",只會寫入除錯日誌」。此外,這也是以下內容的來源:通用的輸入欄位、hook 的位置(設定檔、plugin 的 hooks/hooks.json、skill 與 agent 的 frontmatter)、「CLAUDE_ENV_FILE 可用於 SessionStart、Setup、CwdChanged 與 FileChanged hooks」、updatedMCPToolOutput(「僅取代 MCP 工具的輸出。建議改用 updatedToolOutput」),以及除錯日誌:「--debug 旗標不會輸出到終端機。」2026年11月25日重新讀取;措辭已有變動的引文,改以當日的措辭呈現。 ↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩

  46. Hooks 參考,Claude Code 文件,擷取於2026年11月11日。依事件區分的 hook 類型:「支援全部五種 hook 類型(command、http、mcp_tool、prompt 與 agent)的事件」列出了 PermissionDenied、PostToolBatch、PostToolUse、PostToolUseFailure、PreToolUse、Stop、SubagentStop、TaskCompleted、TaskCreated、TeammateIdle、UserPromptExpansion 與 UserPromptSubmit;「PermissionRequest 支援 command、http、mcp_tool 與 prompt hooks,但不支援 agent hooks」;「PermissionRequest:ok: false 不會拒絕該請求」;「Agent hooks 屬於實驗性功能。」逾時:「預設值:command、http 與 mcp_tool 為 600;prompt 為 30;agent 為 60。」並行:「若其中超過 12 個是 prompt 或 agent hooks,會同時執行其中 12 個,其餘的則在執行中的 hooks 完成後才開始。」Skills 與 agents 中的 hooks:以「與基於設定的 hooks 相同的設定格式」定義;「Claude Code 會將此處的 Stop hook 轉換為 SubagentStop」;skill hooks 會「在工作階段的其餘時間」保留;once:「若為 true,Claude Code 會在 hook 第一次成功執行後將其移除 … 僅對在 skill frontmatter 中宣告的 hooks 有效;在設定檔與 agent frontmatter 中會被忽略」。該頁面的 skill 範例將每個處理程式巢狀放在其比對器項目內的 hooks: 清單之下。2026年11月25日重新讀取;措辭已有變動的引文,改以當日的措辭呈現。 ↩↩↩↩↩

  47. 環境變數,Claude Code 文件,擷取於2026年11月10日:CLAUDE_CODE_SESSION_ID:「在 Bash 與 PowerShell 工具的子程序、hook 指令的子程序以及 stdio MCP 伺服器的子程序中,會自動設為目前的工作階段 ID」;CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION:「已於 v2.1.224 移除,現已無作用」;CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING:「設為 1 可在 Opus 4.6 與 Sonnet 4.6 上停用自適應推理,並退回由 MAX_THINKING_TOKENS 控制的固定思考預算」;MAX_THINKING_TOKENS:「Claude Code 會將其上限設為比請求的最大輸出 token 少一個 token,且絕不低於 1,024 … 未設定且已啟用思考時,具備自適應推理的模型會自行選擇思考深度,其他模型則使用該上限 … 若為正值,在採用自適應推理的模型上,Claude Code 會忽略該數值本身」。 ↩

  48. 使用 hooks 自動化操作與 Hooks 參考,Claude Code 文件,擷取於2026年11月10日。指南:「當 Stop hook 連續封鎖八次,且其間 Claude 沒有任何工具呼叫時,Claude Code 會覆寫該 Stop hook。您的 hook 指令碼需要檢查它是否已經觸發過一次繼續執行。請從 JSON 輸入中解析 stop_hook_active 欄位」。參考:timeout 為「取消前的秒數」;以代碼 2 結束時,PostToolUse「會向 Claude 顯示 stderr;工具已經執行」,Stop 則「會阻止 Claude 停止,並繼續對話」。 ↩

  49. Hooks 參考,Claude Code 文件,擷取於2026年11月11日。非同步 hooks:「設定 "async": true,即可在 Claude 繼續工作的同時於背景執行該 hook」;「此欄位僅適用於 type: "command" hooks。」duration_ms:「選用。工具執行時間(毫秒)。不包含花在權限提示與 PreToolUse hooks 上的時間」。Read、Edit 與 Write 工具的輸入各自列出 file_path:「要讀取之檔案的絕對路徑」、「要編輯之檔案的絕對路徑」、「要寫入之檔案的絕對路徑」。使用 hooks 自動化操作,同次擷取,「封鎖對受保護檔案的編輯」一節:「在 .claude/settings.json 中新增 PreToolUse hook,在任何 Edit 或 Write 工具呼叫之前執行該指令碼」。設定權限,同次擷取:「Read 與 Edit 拒絕規則適用於 Claude 的內建檔案工具,以及 Claude Code 在 Bash 中能辨識的檔案指令,例如 cat、head、tail、sed 與 tee」;「若要對沙箱內的 shell 指令進行作業系統層級的強制執行,請啟用沙箱並關閉在沙箱外的重試。」2026年11月25日重新讀取;措辭已有變動的引文,改以當日的措辭呈現。 ↩↩↩

  50. Agent SDK 的 CHANGELOG,擷取於2026年11月11日。TypeScript SDK CHANGELOG,0.3.208:「Fixed a caller abort during a pending SDK hook callback being converted into hook success, which let PreToolUse-gated tools execute after the abort」。Python SDK CHANGELOG,0.2.127:「Previously, closing stdin too early caused SDK-MCP tool calls from background tasks to fail with "Stream closed" and silently bypassed PreToolUse hooks.」 ↩

  51. Claude Code CHANGELOG,擷取於2026年11月11日。2.0.72:「Changed thinking toggle from Tab to Alt+T to avoid accidental triggers」。2.1.0:「Added hooks support to agent frontmatter, allowing agents to define PreToolUse, PostToolUse, and Stop hooks scoped to the agent’s lifecycle」;「Added hooks support for skill and slash command frontmatter」;「Improved subagents (Task tool) to continue working after permission denial, allowing them to try alternative approaches」。2.1.7:「Enabled MCP tool search auto mode by default for all users. When MCP tool descriptions exceed 10% of the context window, they are automatically deferred and discovered via the MCPSearch tool instead of being loaded upfront.」 ↩

  52. 建立自訂 subagents,Claude Code 文件,擷取於2026年11月11日。權限模式:「若您未設定,subagent 會繼承主對話的權限模式。」;「主對話的權限模式決定 Claude Code 是否採用您設定的值」;「主對話處於 bypassPermissions、acceptEdits 或 auto mode 時,您的 subagent 會以相同模式執行,且 Claude Code 會忽略您設定的 permissionMode。」;「主對話處於 plan 模式時,無論您設定哪個 permissionMode,subagent 都會維持在規劃模式,除非它依 agent teams 規則以 agent team 隊友的身分執行。」;「主對話處於 default 或 dontAsk 模式時,subagent 會以您設定的權限模式執行。在下列這類情況下,它會改為沿用主對話的權限模式」;「您設定了 bypassPermissions。bypassPermissions 這項例外需要 Claude Code v2.1.267 或更新版本。」;「您設定了 auto,但 subagent 無法使用 auto mode」。2026年11月25日重新讀取;措辭已有變動的引文,改以當日的措辭呈現。

    工具:「若要限制工具,請將 tools 欄位作為允許清單,或將 disallowedTools 欄位作為拒絕清單。」;「省略時會繼承 subagents 可用的所有工具。」;Explore 與 Plan 各自列出「唯讀工具;Write 與 Edit 會被拒絕」。上下文與模型:「每個 subagent 都從全新、隔離的上下文視窗開始。」;「fork 是一種繼承至今為止整段對話、而非從頭開始的 subagent。」;模型順序為「每次呼叫的 model 參數」、「subagent 定義的 model frontmatter,其中 inherit 會選取主對話的模型」、「CLAUDE_CODE_SUBAGENT_MODEL 環境變數,當您將其設為模型別名或模型 ID 時」、「主對話的模型」。

    omitClaudeMd:「受管政策檔案仍會載入,但受管 subagents 除外」;「當 agent 透過 --agent 或 agent 設定以主工作階段 agent 的身分執行時會被忽略。」experimental:「在您的 Claude 訂閱使用用量額度期間會忽略 1h」。memory:「若您透過 autoMemoryEnabled 設定或 CLAUDE_CODE_DISABLE_AUTO_MEMORY 關閉自動記憶,memory 欄位就沒有作用」。skills:「您無法預先載入設定了 disable-model-invocation: true 的 skills」。mcpServers:「Claude Code 只有在您信任 agent 檔案所在的資料夾之後,才會從專案 .claude/agents/ 目錄或 --add-dir 目錄之 .claude/agents/ 中的 agent 檔案載入內嵌的 MCP 伺服器。在 v2.1.238 之前,Claude Code 會在不檢查信任的情況下載入這些伺服器。」frontmatter hooks:「若要讓專案層級 subagent 的 frontmatter hooks 執行,請接受包含該 agent 檔案之資料夾的工作區信任對話框。來自 ~/.claude/agents/ 中使用者層級 subagents 的 hooks,以及來自您以 --agents 傳入之定義的 hooks,無須此步驟即可執行。」選擇權限模式,同次擷取:「在 Claude Code v2.1.283 或更新版本中,auto mode 是互動式終端機與 VS Code 工作階段內建的起始權限模式。」 ↩

  53. Agent SDK 參考 - Python 與 Agent SDK 參考 - TypeScript,Claude Code 文件,擷取於2026年11月11日。Python,ClaudeAgentOptions 上的 include_hook_events(預設為 False):「在訊息串流中以 HookEventMessage 物件的形式包含 hook 生命週期事件」。TypeScript,includeHookEvents(預設為 false):「在訊息串流中以 SDKHookStartedMessage、SDKHookProgressMessage 與 SDKHookResponseMessage 的形式包含 hook 生命週期事件。」 ↩

  54. Claude Code 文件,擷取於2026年11月11日。Claude Code 設定:「設定檔是嚴格的 JSON:// 註解或結尾逗號都屬於語法錯誤,Claude Code 會在下次啟動時將該檔案回報為 Settings Error。」Hooks 參考,「比對器模式」一節:比對器為 *、空字串或完全沒有比對器時,會被評估為「比對全部」;「Bash 比對 Bash 工具」;「mcp__memory__.* 比對來自 memory 伺服器的所有工具」;「若您在不支援比對器的事件上加入 matcher 欄位,該欄位會被默默忽略。」;列出 UserPromptSubmit 的那一列寫著「不支援比對器」與「每次發生時一律觸發」。協調多個 Claude Code 工作階段組成的團隊:「若要啟用,請將 CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 環境變數設為 1,可在 shell 環境中設定,或透過 settings.json 設定」。 ↩

  55. Claude Code CHANGELOG,v2.1.323 至 v2.1.332,擷取於2026年11月25日(2.1.323、2.1.325、2.1.326、2.1.327、2.1.328、2.1.329、2.1.330、2.1.331 與 2.1.332 分別有 294、139、367、173、144、130、142、135 與 150 條最上層項目;沒有 2.1.324 章節),以及 GitHub 發行版本 v2.1.323(2026-11-12T22:12:13Z)、v2.1.325(11-13T20:40:01Z)、v2.1.326(11-16T22:11:05Z)、v2.1.327(11-17T23:17:45Z)、v2.1.328(11-19T01:14:04Z)、v2.1.329(11-19T22:14:41Z)、v2.1.330(11-20T22:32:56Z)、v2.1.331(11-23T21:34:41Z)與 v2.1.332(11-25T01:32:14Z);不存在 v2.1.324 發行版本。npm 發布時間取自 npm view @anthropic-ai/claude-code time:2.1.323 為 2026-11-12T20:29:28Z、2.1.324 為 11-13T18:42:36Z、2.1.325 為 11-13T20:07:25Z、2.1.326 為 11-16T18:43:39Z、2.1.327 為 11-17T20:33:19Z、2.1.328 為 11-18T23:09:39Z、2.1.329 為 11-19T18:40:25Z、2.1.330 為 11-20T19:16:01Z、2.1.331 為 11-23T18:36:26Z、2.1.332 為 11-24T22:06:38Z;2026-11-25 當日的 dist-tags:latest 2.1.332、next 2.1.332、stable 2.1.326。2.1.332 原文:「Changed the default model on Microsoft Foundry to Sonnet 5.5: deploy claude-sonnet-5-5, or set ANTHROPIC_DEFAULT_SONNET_MODEL to a model you have deployed」;「Changed the sonnet model alias on Google Cloud’s Agent Platform and Microsoft Foundry to Sonnet 5.5, and Foundry’s opus alias to Opus 5.5; sonnet on Amazon Bedrock stays at Sonnet 4.5」;「Added a PreSkillShellCommand hook event that can refuse a skill or command’s inline shell commands as it loads; on 2.1.331 and older, a settings file naming it opens a dialog at start」;「Added skills from MCP servers (beta). They show as server:skill in the / menu; other skills keep their names」;「Changed /schedule, permission prompts and /loop’s cloud offer to say “cloud scheduled task” instead of “routine” or “cloud schedule”; /routines still works」。2.1.330:「Changed recurring scheduled tasks and /loop to run up to 30 days instead of 7 while their session keeps running, and say when they end; tasks made before this release still end at 7 days」。2.1.328:「Added auto mode for Claude Opus 4.6 and Sonnet 4.6 on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry and Claude apps gateway; interactive sessions with no permission mode start in it」。2.1.325:「Changed sandboxed Bash commands to follow the normal permission flow by default; set sandbox.autoAllowBashIfSandboxed: true to keep running them without prompts」。2.1.323:「Added Code Mode, an experimental opt-in in which Claude writes JavaScript to call its tools」;「Removed the subagentStatusLine setting: subagent rows always use the default look, and settings files that still hold the key load as before」;「Changed the context window assumed for a model ID that Claude Code doesn’t recognize from 200K to 1M; use /autocompact to compact earlier, or CLAUDE_CODE_DISABLE_1M_CONTEXT=1 to keep 200K」;「Changed MCP_SDK_GENERATION=v1 to run the v2 MCP client in a compatibility mode (earlier handshake, relaxed OAuth sign-in checks), because the v1 MCP client is removed」。 ↩↩

  56. Hooks 參考,Claude Code 文件,擷取於2026年11月25日(事件表格中有 34 列)。PreSkillShellCommand:「在注入指令(即 skill 或 /security-review 等指令載入時執行的 shell 指令)之前執行。PreToolUse hooks 不會對注入指令觸發。」;「需要 Claude Code v2.1.332 或更新版本,在桌面應用程式與 VS Code 擴充功能中亦同。」;「v2.1.331 等較早版本會在每個互動式終端機工作階段開啟時顯示警告對話框:Unknown hook event "PreSkillShellCommand" was ignored」;「若您在此事件上設定 prompt 或 agent hook,Claude Code 無法執行它,並會封鎖該 hook 比對到的每道指令。」;「您的指令碼會在注入指令的權限檢查之後執行,因此會收到通過檢查的指令。它在 bypassPermissions 模式下也會執行。」;「您可以從此 hook 封鎖指令,但無法核准或變更指令。」失敗時:「在 command、http 或 mcp_tool hook 上設定 "onFailure": "block"。需要 Claude Code v2.1.295 或更新版本。在 mcp_tool hooks 上,onFailure 需要 v2.1.328 或更新版本。」重複使用指令碼:「您可以重複使用『Hook 的解析方式』中的封鎖指令碼。」;「若要在兩個事件上使用同一個指令碼,請將 hookEventName 保留為 PreToolUse。」;「Hook 的解析方式」一節中印出的指令碼儲存為 .claude/hooks/block-rm.sh,該頁面並補充「安裝 jq,並確認它位於您的 PATH 上」。 ↩↩↩↩

  57. 使用 hooks 攔截並控制 agent 行為,Claude Agent SDK 文件,擷取於2026年11月25日,「在回呼失敗時封鎖該操作」:「在大多數事件上,若回呼拋出例外或回傳的輸出未通過驗證,該操作會照常進行,您的應用程式則會收到一則 tag 為 hook_callback_failed 的 SDKInformationalMessage 警告。」;「若要改為封鎖該操作,請在比對器上,於 TypeScript 中設定 onFailure: "block",或於 Python 中設定 on_failure="block"。需要 TypeScript Agent SDK v0.3.317 或更新版本,或 Python Agent SDK v0.2.177 或更新版本。」;「Stop、SubagentStop、TaskCompleted 與 TeammateIdle:這些事件會忽略此選項,因此操作會照常進行。」;「設定 "block" 後,沒有 return 的路徑會封鎖該操作。」TypeScript Agent SDK CHANGELOG,0.3.317:「Added onFailure to hook matchers: with "block", a hook that throws or returns invalid output blocks the action」;0.3.325:「Added a system/informational warning, tagged hook_no_verdict, when a PreToolUse hook can’t run or answer, or times out, without refusing its tool call」。Python Agent SDK CHANGELOG,0.2.177:「Set on_failure="block" to block the action when a callback raises, returns None, or returns a value the CLI rejects.」 ↩